Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1826b18927 | ||
|
|
db5092914d |
+13
-2
@@ -62,5 +62,16 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`inference.model.tool_call_parser`**: Changed default from `"hermes"` to auto-detection from model name. Uses `MODEL_TOOL_CALL_PARSER` dict to infer the correct vLLM tool call parser (e.g. Qwen3→`hermes`, GLM-4.5→`glm45`, GLM-4.7→`glm47`, MiniMax-M2→`minimax_m2`, INTELLECT-3→`hermes`). Unknown models default to `None`. Explicit values still take priority. (#1795, 2026-02-16)
|
||||
- **`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)
|
||||
- **`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)
|
||||
|
||||
- **`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
|
||||
- **`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)
|
||||
- **`[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)
|
||||
- **`[slurm]` (SFT)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run sft` generates and submits an sbatch script instead of running locally (2026-02-23)
|
||||
- **`hf_hub_offline` (RL/SFT SLURM)**: Removed. `HF_HUB_OFFLINE=1` is now hardcoded in the multi-node SLURM templates (2026-02-23)
|
||||
- **SLURM templates**: Moved from `src/prime_rl/slurm/` to `src/prime_rl/templates/` and renamed to `single_node_rl.sbatch.j2`, `multi_node_rl.sbatch.j2`, `single_node_sft.sbatch.j2`, `multi_node_sft.sbatch.j2` (2026-02-23)
|
||||
- **Entrypoints**: Moved `rl` and `sft` entrypoints from `prime_rl.rl` / `prime_rl.sft` to `prime_rl.entrypoints.rl` / `prime_rl.entrypoints.sft`. No change to CLI usage (`uv run rl`, `uv run sft`) (2026-02-24)
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
inference_gpu_ids = [0,1,2,3,4,5]
|
||||
trainer_gpu_ids = [6,7]
|
||||
|
||||
max_steps = 500
|
||||
seq_len = 8192
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
inference_gpu_ids = [0,1,2,3,4,5]
|
||||
trainer_gpu_ids = [6,7]
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 16384
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 25
|
||||
seq_len = 2048
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 25
|
||||
seq_len = 2048
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
|
||||
@@ -3,12 +3,13 @@
|
||||
# - 300 instead of 500 steps
|
||||
# - No checkpointing
|
||||
# - No evals
|
||||
inference_gpu_ids = [0,1,2,3]
|
||||
trainer_gpu_ids = [4,5,6,7]
|
||||
|
||||
max_steps = 300
|
||||
seq_len = 8192
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
inference_gpu_ids = [0,1,2,3]
|
||||
trainer_gpu_ids = [4,5,6,7]
|
||||
|
||||
max_steps = 300
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
# Based on configs/multimodal/rl_color_codeword.toml but tuned for CI
|
||||
inference_gpu_ids = [0,1,2,3]
|
||||
trainer_gpu_ids = [4,5,6,7]
|
||||
|
||||
max_steps = 25
|
||||
seq_len = 4096
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-VL-4B-Instruct"
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
inference_gpu_ids = [0,1,2,3,4,5]
|
||||
trainer_gpu_ids = [6,7]
|
||||
|
||||
max_steps = 500
|
||||
seq_len = 8192
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
inference_gpu_ids = [0,1,2,3,4,5]
|
||||
trainer_gpu_ids = [6,7]
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 16384
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
inference_gpu_ids = [0,1,2,3,4,5]
|
||||
trainer_gpu_ids = [6,7]
|
||||
|
||||
max_steps = 1500
|
||||
seq_len = 24576
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
|
||||
@@ -43,4 +43,4 @@ sync_interval = 5.0
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
@@ -1,9 +1,10 @@
|
||||
trainer_gpu_ids = [0,1,2,3]
|
||||
inference_gpu_ids = [4,5,6,7]
|
||||
|
||||
max_steps = 300
|
||||
seq_len = 8192
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[wandb]
|
||||
project = "env-mix-debug"
|
||||
name = "env-mix"
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 100
|
||||
seq_len = 2048
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
trainer_gpu_ids = [0]
|
||||
inference_gpu_ids = [1]
|
||||
|
||||
max_steps = 500
|
||||
seq_len = 2048
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 3000
|
||||
seq_len = 8192
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
trainer_gpu_ids = [0]
|
||||
inference_gpu_ids = [1]
|
||||
|
||||
max_steps = 500
|
||||
|
||||
[wandb]
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 15
|
||||
seq_len = 4096
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 500
|
||||
seq_len = 4096
|
||||
|
||||
|
||||
+152
-94
@@ -1,91 +1,113 @@
|
||||
# SLURM
|
||||
|
||||
## RL
|
||||
Both `rl` and `sft` have built-in SLURM support. Adding a `[slurm]` section to your config switches from local execution to SLURM job submission — no separate entrypoint needed.
|
||||
|
||||
For RL on SLURM clusters, use the `rl_slurm` entrypoint. It resolves the full config (trainer, orchestrator, inference), dumps sub-configs as TOML files, renders a SLURM batch script from a Jinja2 template, and submits it with `sbatch`.
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
uv run rl_slurm @ examples/slurm/hendrycks_math.toml
|
||||
# Local run
|
||||
uv run rl @ examples/reverse_text/rl.toml
|
||||
|
||||
# SLURM run (same entrypoint, just add [slurm] to the config)
|
||||
uv run rl @ examples/reverse_text/slurm_rl.toml
|
||||
```
|
||||
|
||||
This will:
|
||||
The SLURM config is a thin overlay that inherits from a base config and adds `[slurm]` + `[deployment]` sections:
|
||||
|
||||
1. Write resolved sub-configs to `{output_dir}/configs/` (trainer.toml, orchestrator.toml, inference.toml)
|
||||
2. Render the SLURM script to `{output_dir}/rl.sh`
|
||||
3. Submit the job via `sbatch`
|
||||
```toml
|
||||
# examples/reverse_text/slurm_rl.toml
|
||||
toml_files = ["rl.toml"]
|
||||
|
||||
To only generate the script without submitting, use `--dry-run`:
|
||||
output_dir = "outputs/reverse-text-rl"
|
||||
|
||||
```bash
|
||||
uv run rl_slurm @ examples/slurm/hendrycks_math.toml --dry-run
|
||||
[slurm]
|
||||
job_name = "reverse-text-rl"
|
||||
```
|
||||
|
||||
## How it works
|
||||
|
||||
When `[slurm]` is present, the entrypoint:
|
||||
|
||||
1. Resolves the full config
|
||||
2. Renders a SLURM batch script from a Jinja2 template
|
||||
3. Writes the script and resolved config to `{output_dir}/`
|
||||
4. Submits via `sbatch` (or prints the script with `--slurm.dry-run`)
|
||||
|
||||
For **single-node** jobs, the entire config is dumped to a TOML file and the template simply runs `uv run rl @` or `uv run sft @` on the allocated node.
|
||||
|
||||
For **multi-node** jobs, sub-configs are written separately and `srun` dispatches processes across nodes.
|
||||
|
||||
## Configuration
|
||||
|
||||
The SLURM config extends the standard RL config with the following fields:
|
||||
### `[slurm]` — Job submission (shared between RL and SFT)
|
||||
|
||||
| Field | Description |
|
||||
|---|---|
|
||||
| `job_name` | SLURM job name |
|
||||
| `output_dir` | Directory for outputs, sub-configs, and logs |
|
||||
| `project_dir` | Path to the project root on the cluster (defaults to cwd) |
|
||||
| `num_train_nodes` | Number of nodes for training |
|
||||
| `num_infer_nodes` | Number of nodes for inference |
|
||||
| `gpus_per_node` | Number of GPUs per node (default: 8) |
|
||||
| `nodes_per_fsdp_group` | Number of train nodes per FSDP island (optional, auto-sets `trainer.dp_replicate`) |
|
||||
| `slurm_template` | Path to a custom Jinja2 template (optional) |
|
||||
| `dry_run` | Only generate the script without submitting (default: false) |
|
||||
| Field | Description | Default |
|
||||
|---|---|---|
|
||||
| `job_name` | SLURM job name | `"prime-rl"` |
|
||||
| `project_dir` | Path to the project root on the cluster | `"."` |
|
||||
| `template_path` | Path to a custom Jinja2 template | auto-selected |
|
||||
| `partition` | SLURM partition | `"cluster"` |
|
||||
| `dry_run` | Generate script without submitting | `false` |
|
||||
|
||||
All standard RL config fields (model, trainer, orchestrator, inference, wandb, ckpt, etc.) are available and will be resolved into the sub-configs.
|
||||
### `[deployment]` — Node and GPU allocation
|
||||
|
||||
### Dense model (Hendrycks Math)
|
||||
**RL** uses a discriminated union with `type = "single_node"` (default) or `type = "multi_node"`:
|
||||
|
||||
| Field | single_node | multi_node |
|
||||
|---|---|---|
|
||||
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
|
||||
| `num_train_gpus` | Training GPUs | — |
|
||||
| `num_infer_gpus` | Inference GPUs | — |
|
||||
| `num_train_nodes` | — | Training nodes |
|
||||
| `num_infer_nodes` | — | Inference nodes |
|
||||
| `nodes_per_fsdp_group` | — | Nodes per FSDP island (optional) |
|
||||
|
||||
**SFT** follows the same pattern but only has training nodes:
|
||||
|
||||
| Field | single_node | multi_node |
|
||||
|---|---|---|
|
||||
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
|
||||
| `num_gpus` | Number of GPUs (default: 1) | — |
|
||||
| `num_nodes` | — | Training nodes (default: 2) |
|
||||
| `nodes_per_fsdp_group` | — | Nodes per FSDP island (optional) |
|
||||
|
||||
The SLURM template is auto-selected based on `deployment.type`. You can override it with `slurm.template_path`.
|
||||
|
||||
### Constraints
|
||||
|
||||
- `output_dir` must be explicitly set when using SLURM (the default `"outputs"` is rejected)
|
||||
- Multi-node deployment requires `[slurm]` to be set
|
||||
|
||||
---
|
||||
|
||||
## RL Examples
|
||||
|
||||
### Single-node SLURM
|
||||
|
||||
The simplest case: run on a single allocated node. No `[deployment]` needed — defaults to `single_node`.
|
||||
|
||||
```toml
|
||||
job_name = "hendrycks-math"
|
||||
output_dir = "/shared/outputs/my-rl-run"
|
||||
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
max_steps = 500
|
||||
seq_len = 2048
|
||||
|
||||
[wandb]
|
||||
project = "hendrycks-math"
|
||||
name = "hendrycks-math"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 1
|
||||
dp = 8
|
||||
[slurm]
|
||||
job_name = "my-rl-run"
|
||||
```
|
||||
|
||||
### MoE model (Hendrycks Math)
|
||||
|
||||
For MoE models like `Qwen3-30B-A3B`, the config is designed to minimize memory usage on a single training node. It enables activation checkpointing with offloading, optimizer CPU offload, and NCCL weight broadcast:
|
||||
### Multi-node SLURM (Hendrycks Math)
|
||||
|
||||
```toml
|
||||
job_name = "hendrycks-math-moe"
|
||||
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
output_dir = "outputs/rl-math-moe"
|
||||
max_steps = 500
|
||||
seq_len = 2048
|
||||
|
||||
[slurm]
|
||||
job_name = "hendrycks-math-rl-moe"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
@@ -120,49 +142,85 @@ tp = 4
|
||||
dp = 2
|
||||
```
|
||||
|
||||
### Custom SLURM Templates
|
||||
See [`examples/hendrycks_math/rl.toml`](../examples/hendrycks_math/rl.toml) for the full example.
|
||||
|
||||
The default RL template handles a standard multi-node setup with NCCL weight broadcast, InfiniBand detection, and `srun`-based process dispatch. For more advanced use cases (custom partitions, account settings, module loads, different networking setups, etc.), provide your own Jinja2 template:
|
||||
---
|
||||
|
||||
```bash
|
||||
uv run rl_slurm \
|
||||
@ my_config.toml \
|
||||
--slurm-template path/to/my_template.sh.j2
|
||||
## SFT Examples
|
||||
|
||||
### Single-node SLURM
|
||||
|
||||
```toml
|
||||
output_dir = "/shared/outputs/my-sft-run"
|
||||
|
||||
[slurm]
|
||||
job_name = "my-sft-run"
|
||||
```
|
||||
|
||||
The template receives the following variables: `job_name`, `project_dir`, `output_dir`, `config_dir`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `hf_hub_offline`. See `src/prime_rl/slurm/rl_slurm.sh.j2` for the default template as a starting point.
|
||||
### Multi-node SLURM (MoE SFT)
|
||||
|
||||
### Monitoring
|
||||
```toml
|
||||
output_dir = "outputs/sft-moe-math"
|
||||
max_steps = 500
|
||||
|
||||
After submission, the logs are available at:
|
||||
[slurm]
|
||||
job_name = "sft-moe-math"
|
||||
|
||||
```bash
|
||||
tail -f {output_dir}/slurm/latest_train_node_rank_0.log
|
||||
tail -f {output_dir}/slurm/latest_infer_node_rank_0.log
|
||||
tail -f {output_dir}/slurm/latest_orchestrator.log
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 2
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
optim_cpu_offload = true
|
||||
|
||||
[model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
[model.ac]
|
||||
freq = 1
|
||||
|
||||
[data]
|
||||
type = "sft"
|
||||
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
|
||||
subsets = ["default"]
|
||||
splits = ["math"]
|
||||
batch_size = 128
|
||||
seq_len = 8192
|
||||
```
|
||||
|
||||
For convenience, a tmux launcher is provided that sets up a session with all three log streams:
|
||||
See [`examples/hendrycks_math/sft.toml`](../examples/hendrycks_math/sft.toml) for the full example.
|
||||
|
||||
---
|
||||
|
||||
## Custom SLURM Templates
|
||||
|
||||
The default templates handle standard setups with InfiniBand detection, environment setup, and `srun`-based process dispatch. For advanced use cases (custom partitions, account settings, module loads, etc.), provide your own Jinja2 template:
|
||||
|
||||
```bash
|
||||
uv run rl @ my_config.toml --slurm.template-path path/to/my_template.sbatch.j2
|
||||
```
|
||||
|
||||
See [`src/prime_rl/templates/`](../src/prime_rl/templates/) for the default templates as a starting point.
|
||||
|
||||
## Monitoring
|
||||
|
||||
After submission, logs are available at:
|
||||
|
||||
```bash
|
||||
# Single-node
|
||||
tail -F {output_dir}/logs/trainer/rank_0.log
|
||||
|
||||
# Multi-node RL
|
||||
tail -F {output_dir}/slurm/latest_train_node_rank_0.log
|
||||
tail -F {output_dir}/slurm/latest_infer_node_rank_0.log
|
||||
tail -F {output_dir}/slurm/latest_orchestrator.log
|
||||
```
|
||||
|
||||
For convenience, a tmux launcher sets up a session with all log streams:
|
||||
|
||||
```bash
|
||||
bash scripts/slurm_tmux.sh my-rl-job /shared/outputs/my-rl-job
|
||||
```
|
||||
|
||||
This creates a tmux session `slurm-my-rl-job` with two windows:
|
||||
|
||||
- **Window 0 (Terminal)**: a plain shell for running commands
|
||||
- **Window 1 (Logs)**: three vertical panes tailing trainer, orchestrator, and inference logs
|
||||
|
||||
The trainer and inference panes use glob patterns (`latest_train_node_rank_*.log`, `latest_infer_node_rank_*.log`) to follow logs from all node ranks. Re-running the same command attaches to the existing session.
|
||||
|
||||
---
|
||||
|
||||
## SFT
|
||||
|
||||
For SFT on SLURM, use the `sft_slurm` entrypoint. It works the same way as `rl_slurm` but only needs a trainer config — no inference or orchestrator nodes.
|
||||
|
||||
```bash
|
||||
uv run sft_slurm @ examples/slurm/sft_moe.toml
|
||||
```
|
||||
|
||||
See [`examples/slurm/sft_moe.toml`](../examples/slurm/sft_moe.toml) for a MoE example with activation checkpointing, CPU offload, and compilation. Use `--dry-run` to generate the script without submitting.
|
||||
|
||||
@@ -90,7 +90,8 @@ The correct alphabetical order by last name should be: Akman, Cakir, Durgun. The
|
||||
|
||||
We train with LoRA (rank 32, alpha 64) for 100 steps.
|
||||
|
||||

|
||||

|
||||
|
||||
*Check out the logs on [W&B](https://wandb.ai/primeintellect/alphabet-sort-4b-lora/workspace?nw=nwuserandrewpi).*
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
|
||||
|
Before Width: | Height: | Size: 141 KiB After Width: | Height: | Size: 141 KiB |
@@ -0,0 +1,6 @@
|
||||
toml_files = ["rl.toml"]
|
||||
|
||||
output_dir = "outputs/alphabet-sort"
|
||||
|
||||
[slurm]
|
||||
job_name = "alphabet-sort"
|
||||
@@ -1,12 +1,15 @@
|
||||
job_name = "hendrycks-math-moe"
|
||||
output_dir = "outputs/hendrycks-math-moe"
|
||||
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
output_dir = "outputs/rl-math-moe"
|
||||
max_steps = 500
|
||||
seq_len = 2048
|
||||
|
||||
[slurm]
|
||||
job_name = "hendrycks-math-rl-moe"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
@@ -25,7 +28,6 @@ impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
optim_cpu_offload = true
|
||||
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
job_name = "sft-moe-math"
|
||||
output_dir = "/shared/outputs/sft-moe-math"
|
||||
num_nodes = 1
|
||||
gpus_per_node = 8
|
||||
|
||||
output_dir = "outputs/sft-moe-math"
|
||||
max_steps = 500
|
||||
|
||||
[slurm]
|
||||
job_name = "sft-moe-math"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 2
|
||||
|
||||
[wandb]
|
||||
project = "sft-moe-intellect"
|
||||
name = "sft-moe-math"
|
||||
@@ -36,7 +36,7 @@ This is of course just a quick vibe check and no full-fledged evaluation, but we
|
||||
|
||||
We will fine-tune `PrimeIntellect/Qwen3-0.6B` ([HF](https://huggingface.co/PrimeIntellect/Qwen3-0.6B)), which is a clone of `Qwen/Qwen3-0.6B` ([HF](https://huggingface.co/Qwen/Qwen3-0.6B)) with a chat template suitable for multi-turn RL, on `willcb/R1-reverse-wikipedia-paragraphs-v1-1000` ([HF](https://huggingface.co/datasets/willcb/R1-reverse-wikipedia-paragraphs-v1-1000)) which contains 1K examples of reversals of small paragraphs.
|
||||
|
||||

|
||||

|
||||
*Check out the logs of the SFT run on [W&B](https://wandb.ai/primeintellect/examples?nw=s3p14m48jod).*
|
||||
|
||||
To train on a single GPU, run
|
||||
@@ -72,7 +72,7 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT
|
||||
|
||||
For the RL we will only do 20 steps at 8x16 rollouts, for a total batch size of 128 and sequence length 128. Because of the small context, training should be extremely quick.
|
||||
|
||||

|
||||

|
||||
*Check out the logs of the RL run on [W&B](https://wandb.ai/primeintellect/examples?nw=yxjwjc556do).*
|
||||
|
||||
```bash
|
||||
|
||||
|
Before Width: | Height: | Size: 129 KiB After Width: | Height: | Size: 129 KiB |
@@ -1,2 +0,0 @@
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
@@ -1,15 +0,0 @@
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
seq_len = 2048
|
||||
max_steps = 20
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[sampling]
|
||||
max_tokens = 128
|
||||
|
||||
[[env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[ckpt]
|
||||
@@ -1,9 +0,0 @@
|
||||
max_steps = 20
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt]
|
||||
|
Before Width: | Height: | Size: 77 KiB After Width: | Height: | Size: 77 KiB |
@@ -1,14 +0,0 @@
|
||||
max_steps = 100
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
|
||||
[data]
|
||||
name = "willcb/R1-reverse-wikipedia-paragraphs-v1-1000"
|
||||
seq_len = 4096
|
||||
batch_size = 32
|
||||
|
||||
[optim]
|
||||
lr = 2e-5
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
@@ -0,0 +1,6 @@
|
||||
toml_files = ["rl.toml"]
|
||||
|
||||
output_dir = "outputs/reverse-text-rl"
|
||||
|
||||
[slurm]
|
||||
job_name = "reverse-text-rl"
|
||||
@@ -0,0 +1,6 @@
|
||||
toml_files = ["sft.toml"]
|
||||
|
||||
output_dir = "outputs/reverse-text-sft"
|
||||
|
||||
[slurm]
|
||||
job_name = "reverse-text-sft"
|
||||
@@ -1,41 +0,0 @@
|
||||
job_name = "hendrycks-math"
|
||||
output_dir = "outputs/hendrycks-math"
|
||||
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
max_steps = 500
|
||||
seq_len = 2048
|
||||
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
[wandb]
|
||||
project = "hendrycks-math-debug"
|
||||
name = "hendrycks-math"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference.parallel]
|
||||
tp = 1
|
||||
dp = 8
|
||||
@@ -1,9 +1,10 @@
|
||||
inference_gpu_ids = [0,1,2,3,4,5]
|
||||
trainer_gpu_ids = [6,7]
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 4096
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
toml_files = ["rl.toml"]
|
||||
|
||||
output_dir = "outputs/wiki-search"
|
||||
|
||||
[slurm]
|
||||
job_name = "wiki-search"
|
||||
@@ -1,9 +1,10 @@
|
||||
inference_gpu_ids = [0,1,2,3,4,5]
|
||||
trainer_gpu_ids = [6,7]
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 8192
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[wandb]
|
||||
project = "wordle"
|
||||
name = "wordle"
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
toml_files = ["rl.toml"]
|
||||
|
||||
output_dir = "outputs/wordle-rl"
|
||||
|
||||
[slurm]
|
||||
job_name = "wordle-rl"
|
||||
@@ -0,0 +1,6 @@
|
||||
toml_files = ["sft.toml"]
|
||||
|
||||
output_dir = "outputs/wordle-sft"
|
||||
|
||||
[slurm]
|
||||
job_name = "wordle-sft"
|
||||
+2
-4
@@ -38,14 +38,12 @@ dependencies = [
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
rl = "prime_rl.rl:main"
|
||||
rl_slurm = "prime_rl.slurm.rl:main"
|
||||
rl = "prime_rl.entrypoints.rl:main"
|
||||
sft = "prime_rl.entrypoints.sft:main"
|
||||
trainer = "prime_rl.trainer.rl.train:main"
|
||||
orchestrator = "prime_rl.orchestrator.orchestrator:main"
|
||||
inference = "prime_rl.inference.server:main"
|
||||
env-server = "prime_rl.orchestrator.env_server.env_server:main"
|
||||
sft = "prime_rl.trainer.sft.train:main"
|
||||
sft_slurm = "prime_rl.slurm.sft:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
|
||||
|
||||
@@ -67,20 +67,75 @@ Use the string `"None"` in TOML to set a field to None:
|
||||
max_model_len = "None"
|
||||
```
|
||||
|
||||
## SLURM mode
|
||||
|
||||
Both `rl` and `sft` commands support SLURM execution via an optional `[slurm]` section. When present, the run is submitted as a SLURM job instead of running locally.
|
||||
|
||||
### RL SLURM
|
||||
|
||||
```toml
|
||||
output_dir = "/shared/experiments/my-run"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
gpus_per_node = 8
|
||||
# nodes_per_fsdp_group = 1
|
||||
|
||||
[slurm]
|
||||
job_name = "my-rl-job"
|
||||
# dry_run = true # generate script without submitting
|
||||
# template_path = "path/to/custom.sh.j2"
|
||||
# project_dir = "/path/to/project"
|
||||
```
|
||||
|
||||
When `[slurm]` is set for RL:
|
||||
- `output_dir` must be explicitly set (the default `outputs` is rejected)
|
||||
- Teacher inference is not supported in multi-node deployment
|
||||
|
||||
### SFT SLURM
|
||||
|
||||
```toml
|
||||
output_dir = "/shared/experiments/my-sft-run"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 2
|
||||
gpus_per_node = 8
|
||||
# nodes_per_fsdp_group = 1
|
||||
|
||||
[slurm]
|
||||
job_name = "my-sft-job"
|
||||
# dry_run = true
|
||||
# template_path = "path/to/custom.sh.j2"
|
||||
# project_dir = "/path/to/project"
|
||||
```
|
||||
|
||||
SFT deployment follows the same pattern as RL:
|
||||
- `[deployment]` configures node/GPU allocation (`single_node` default or `multi_node`)
|
||||
- `[slurm]` configures SLURM submission (job name, partition, template)
|
||||
- `output_dir` must be explicitly set when using SLURM
|
||||
- Multi-node deployment requires `[slurm]` to be set
|
||||
|
||||
## Available commands
|
||||
|
||||
All accept `@ config.toml` and CLI overrides:
|
||||
|
||||
| Command | Config class | Description |
|
||||
|---------|-------------|-------------|
|
||||
| `uv run rl` | full RL pipeline | Orchestrator + inference + trainer |
|
||||
| `uv run rl` | full RL pipeline | Orchestrator + inference + trainer (local or SLURM) |
|
||||
| `uv run inference` | `InferenceConfig` | vLLM inference server |
|
||||
| `uv run trainer` | trainer config | RL trainer |
|
||||
| `uv run orchestrator` | orchestrator config | Rollout orchestrator |
|
||||
| `uv run env-server` | env server config | Environment server |
|
||||
| `uv run sft` | SFT config | Supervised fine-tuning |
|
||||
| `uv run sft` | SFT config | Supervised fine-tuning (local or SLURM) |
|
||||
|
||||
## Key files
|
||||
|
||||
- `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/trainer/sft/train.py` — unified SFT entrypoint (local + SLURM)
|
||||
- `src/prime_rl/trainer/sft/config.py` — `SFTTrainerConfig`, `SFTSlurmConfig`
|
||||
- `configs/` — all config files, organized by task
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
|
||||
import pynvml
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.rl_config import RLConfig
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
from prime_rl.utils.utils import (
|
||||
get_broadcast_dir,
|
||||
get_free_port,
|
||||
get_log_dir,
|
||||
get_rollout_dir,
|
||||
)
|
||||
|
||||
|
||||
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
"""Write resolved subconfigs to disk as TOML files."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(output_dir / "trainer.toml", "wb") as f:
|
||||
tomli_w.dump(config.trainer.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
with open(output_dir / "orchestrator.toml", "wb") as f:
|
||||
tomli_w.dump(config.orchestrator.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
if config.inference is not None:
|
||||
with open(output_dir / "inference.toml", "wb") as f:
|
||||
tomli_w.dump(config.inference.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
teacher_inference = getattr(config, "teacher_inference", None)
|
||||
if teacher_inference is not None:
|
||||
with open(output_dir / "teacher_inference.toml", "wb") as f:
|
||||
tomli_w.dump(teacher_inference.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
|
||||
def check_gpus_available(gpu_ids: list[int]) -> None:
|
||||
"""Raise error if there are existing processes on the specified GPUs."""
|
||||
pynvml.nvmlInit()
|
||||
|
||||
occupied = []
|
||||
for gpu_id in gpu_ids:
|
||||
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_id)
|
||||
processes = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
|
||||
if processes:
|
||||
pids = [p.pid for p in processes]
|
||||
occupied.append((gpu_id, pids))
|
||||
|
||||
if occupied:
|
||||
msg = "Existing processes found on GPUs:\n"
|
||||
for gpu_id, pids in occupied:
|
||||
msg += f" GPU {gpu_id}: PIDs {pids}\n"
|
||||
msg += "Kill these processes or use different GPUs."
|
||||
raise RuntimeError(msg)
|
||||
|
||||
|
||||
def maybe_clean(config: RLConfig, log_dir: Path, orch_log_dir: Path, broadcast_dir: Path, rollout_dir: Path):
|
||||
logger = get_logger()
|
||||
logger.info("Cleaning checkpoint, logs, weights, broadcast and rollout directories")
|
||||
|
||||
# Cleaning logs (so that streaming logs to terminal works)
|
||||
logger.info(f"Cleaning log dir ({log_dir})")
|
||||
shutil.rmtree(log_dir, ignore_errors=True)
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
logger.info(f"Cleaning orchestrator log dir ({orch_log_dir})")
|
||||
shutil.rmtree(orch_log_dir, ignore_errors=True)
|
||||
orch_log_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Cleaning broadcast dir (so that orchestrator does not pre-maturely update weights)
|
||||
if not (
|
||||
config.ckpt
|
||||
and config.ckpt.resume_step
|
||||
and config.trainer.weight_broadcast
|
||||
and config.trainer.weight_broadcast.type == "filesystem"
|
||||
):
|
||||
logger.info(f"Cleaning broadcast directory ({broadcast_dir})")
|
||||
shutil.rmtree(broadcast_dir, ignore_errors=True)
|
||||
|
||||
# Cleaning rollouts (so that trainer does not train on old rollouts)
|
||||
logger.info(f"Cleaning rollout dir ({rollout_dir})")
|
||||
shutil.rmtree(rollout_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def rl_local(config: RLConfig):
|
||||
assert config.output_dir is not None
|
||||
|
||||
# Setup logger
|
||||
logger = setup_logger(
|
||||
config.log.level or "info",
|
||||
log_file=config.output_dir / "logs" / "rl.log" if config.log.file else None,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
|
||||
# If dump_config is set, write resolved subconfigs and exit early
|
||||
if config.dump_config is not None:
|
||||
logger.warning(
|
||||
"--dump-config is set. No RL training will be started. Only writing resolved subconfigs to disk."
|
||||
)
|
||||
write_subconfigs(config, config.dump_config)
|
||||
logger.info(f"Dumping resolved subconfigs to {config.dump_config}")
|
||||
logger.info(f" Wrote trainer config to {config.dump_config / 'trainer.toml'}")
|
||||
logger.info(f" Wrote orchestrator config to {config.dump_config / 'orchestrator.toml'}")
|
||||
if config.inference is not None:
|
||||
logger.info(f" Wrote inference config to {config.dump_config / 'inference.toml'}")
|
||||
if config.teacher_inference is not None:
|
||||
logger.info(f" Wrote teacher inference config to {config.dump_config / 'teacher_inference.toml'}")
|
||||
logger.success(f"Config dump complete. Files written to {config.dump_config}")
|
||||
logger.warning("To start an RL run, remove --dump-config from your command.")
|
||||
return
|
||||
|
||||
# Derive GPU IDs from deployment config
|
||||
assert config.deployment.type == "single_node"
|
||||
gpu_offset = 0
|
||||
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
|
||||
infer_gpu_ids = list(range(gpu_offset, gpu_offset + num_infer_gpus))
|
||||
gpu_offset += num_infer_gpus
|
||||
trainer_gpu_ids = list(range(gpu_offset, gpu_offset + config.deployment.num_train_gpus))
|
||||
gpu_offset += config.deployment.num_train_gpus
|
||||
num_teacher_gpus = config.deployment.num_teacher_gpus or 0
|
||||
teacher_gpu_ids = list(range(gpu_offset, gpu_offset + num_teacher_gpus)) if num_teacher_gpus > 0 else []
|
||||
|
||||
start_command = sys.argv
|
||||
logger.info("Starting RL run")
|
||||
logger.debug(f"RL start command: {' '.join(start_command)}")
|
||||
|
||||
# Check for existing processes on GPUs
|
||||
all_gpu_ids = list(set(infer_gpu_ids + trainer_gpu_ids + teacher_gpu_ids))
|
||||
check_gpus_available(all_gpu_ids)
|
||||
|
||||
# Validate client port matches inference server port
|
||||
if config.inference is not None and not config.orchestrator.client.is_elastic:
|
||||
from urllib.parse import urlparse
|
||||
|
||||
base_url = config.orchestrator.client.base_url[0]
|
||||
parsed = urlparse(base_url)
|
||||
client_port = parsed.port
|
||||
expected_port = config.inference.server.port
|
||||
if client_port != expected_port:
|
||||
raise ValueError(
|
||||
f"orchestrator.client.base_url port ({client_port}) does not match "
|
||||
f"inference.server.port ({expected_port}). "
|
||||
f"Update the base_url to use port {expected_port} to match the inference server."
|
||||
)
|
||||
|
||||
# Prepare paths to communicate with the trainer
|
||||
log_dir = get_log_dir(config.output_dir)
|
||||
orch_log_dir = get_log_dir(config.orchestrator.output_dir)
|
||||
rollout_dir = get_rollout_dir(config.orchestrator.output_dir)
|
||||
broadcast_dir = get_broadcast_dir(config.orchestrator.output_dir)
|
||||
|
||||
if config.clean:
|
||||
maybe_clean(config, log_dir, orch_log_dir, broadcast_dir, rollout_dir)
|
||||
|
||||
# Write all resolved subconfigs to disk
|
||||
config_dir = Path(".pydantic_config") / uuid.uuid4().hex
|
||||
write_subconfigs(config, config_dir)
|
||||
|
||||
# Start processes
|
||||
processes: list[Popen] = []
|
||||
monitor_threads: list[Thread] = []
|
||||
error_queue: list[Exception] = []
|
||||
stop_events: dict[str, Event] = {}
|
||||
|
||||
try:
|
||||
# Optionally, start inference process
|
||||
if config.inference:
|
||||
inference_cmd = ["uv", "run", "inference", "@", (config_dir / "inference.toml").as_posix()]
|
||||
logger.info(f"Starting inference process on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
|
||||
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
|
||||
# If we don't log stdout, the server hangs
|
||||
with open(log_dir / "inference.stdout", "w") as log_file:
|
||||
inference_process = Popen(
|
||||
inference_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(inference_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["inference"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(inference_process, stop_event, error_queue, "inference"),
|
||||
daemon=True,
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
else:
|
||||
logger.warning(
|
||||
"No inference config specified, skipping starting inference server. Make sure your inference server is running."
|
||||
)
|
||||
|
||||
# Optionally, start teacher inference process
|
||||
if config.teacher_inference:
|
||||
if not teacher_gpu_ids:
|
||||
raise ValueError(
|
||||
"teacher_inference is configured but deployment.num_teacher_gpus is not set. "
|
||||
"Either set deployment.num_teacher_gpus to start a teacher inference server, "
|
||||
"or omit teacher_inference and configure orchestrator.teacher_model to use an existing server."
|
||||
)
|
||||
|
||||
teacher_inference_cmd = ["uv", "run", "inference", "@", (config_dir / "teacher_inference.toml").as_posix()]
|
||||
logger.info(f"Starting teacher inference process on GPU(s) {' '.join(map(str, teacher_gpu_ids))}")
|
||||
logger.debug(f"Teacher inference start command: {' '.join(teacher_inference_cmd)}")
|
||||
with open(log_dir / "teacher_inference.stdout", "w") as log_file:
|
||||
teacher_inference_process = Popen(
|
||||
teacher_inference_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, teacher_gpu_ids)),
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(teacher_inference_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["teacher_inference"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(teacher_inference_process, stop_event, error_queue, "teacher_inference"),
|
||||
daemon=True,
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
elif (
|
||||
config.trainer.loss.type == "default" and config.trainer.loss.teacher_tau > 0
|
||||
) or config.orchestrator.teacher_model:
|
||||
logger.warning(
|
||||
"No teacher_inference config specified, skipping starting teacher inference server. "
|
||||
"Is your teacher inference server running? Make sure orchestrator.teacher_model is configured."
|
||||
)
|
||||
|
||||
# Start orchestrator process
|
||||
orchestrator_cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"orchestrator",
|
||||
"@",
|
||||
(config_dir / "orchestrator.toml").as_posix(),
|
||||
]
|
||||
logger.info("Starting orchestrator process")
|
||||
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
|
||||
with open(log_dir / "orchestrator.stdout", "w") as log_file:
|
||||
orchestrator_process = Popen(
|
||||
orchestrator_cmd,
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
env={
|
||||
**os.environ,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
},
|
||||
)
|
||||
processes.append(orchestrator_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["orchestrator"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(orchestrator_process, stop_event, error_queue, "orchestrator"),
|
||||
daemon=True,
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
# Start training process
|
||||
trainer_cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"env",
|
||||
"PYTHONUNBUFFERED=1",
|
||||
"PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True",
|
||||
"torchrun",
|
||||
f"--rdzv-endpoint=localhost:{get_free_port()}",
|
||||
f"--rdzv-id={uuid.uuid4().hex}",
|
||||
# Pipe all logs to file, and only master rank logs to stdout
|
||||
f"--log-dir={config.output_dir / 'torchrun'}",
|
||||
"--local-ranks-filter=0",
|
||||
"--redirect=3",
|
||||
"--tee=3",
|
||||
f"--nproc-per-node={len(trainer_gpu_ids)}",
|
||||
"-m",
|
||||
"prime_rl.trainer.rl.train",
|
||||
"@",
|
||||
(config_dir / "trainer.toml").as_posix(),
|
||||
]
|
||||
logger.info(f"Starting trainer process on GPU(s) {' '.join(map(str, trainer_gpu_ids))}")
|
||||
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
|
||||
with open(log_dir / "trainer.stdout", "w") as log_file:
|
||||
trainer_process = Popen(
|
||||
trainer_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
|
||||
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(trainer_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["trainer"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process, args=(trainer_process, stop_event, error_queue, "trainer"), daemon=True
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
# Monitor all processes for failures
|
||||
logger.success("Startup complete. Showing trainer logs...")
|
||||
|
||||
tail_process = Popen(["tail", "-F", log_dir / "trainer.stdout"])
|
||||
processes.append(tail_process)
|
||||
|
||||
# Check for errors from monitor threads
|
||||
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
|
||||
if error_queue:
|
||||
error = error_queue[0]
|
||||
logger.error(f"Error: {error}")
|
||||
logger.error("Terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
# Small delay to avoid busy waiting
|
||||
time.sleep(1)
|
||||
|
||||
# Check if any critical process failed
|
||||
if orchestrator_process.returncode != 0:
|
||||
logger.error(f"Orchestrator failed with exit code {orchestrator_process.returncode}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
if trainer_process.returncode != 0:
|
||||
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
logger.success("RL training finished!")
|
||||
|
||||
# Cleanup threads and processes
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.warning("Received interrupt signal, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
logger.error(f"Error occurred: {e}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
raise
|
||||
|
||||
|
||||
def render_slurm_script(config: RLConfig, config_dir: Path) -> tuple[str, str]:
|
||||
"""Render the SLURM script template. Returns (script, log_message)."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
assert config.output_dir is not None
|
||||
assert config.slurm is not None
|
||||
assert config.slurm.template_path is not None
|
||||
|
||||
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
|
||||
template = env.get_template(config.slurm.template_path.name)
|
||||
|
||||
log_dir = config.output_dir / "logs"
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
import tomli_w
|
||||
|
||||
config_path = config_dir / "rl.toml"
|
||||
config_dict = config.model_dump(exclude={"slurm"}, exclude_none=True, mode="json")
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
with open(config_path, "wb") as f:
|
||||
tomli_w.dump(config_dict, f)
|
||||
|
||||
script = template.render(
|
||||
config_path=config_path,
|
||||
job_name=config.slurm.job_name,
|
||||
project_dir=config.slurm.project_dir,
|
||||
partition=config.slurm.partition,
|
||||
output_dir=config.output_dir,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
log_message = (
|
||||
f"Logs:\n"
|
||||
f" Trainer: tail -F {log_dir}/trainer.stdout\n"
|
||||
f" Orchestrator: tail -F {log_dir}/orchestrator.stdout\n"
|
||||
f" Inference: tail -F {log_dir}/inference.stdout"
|
||||
)
|
||||
else:
|
||||
script = template.render(
|
||||
config_dir=config_dir,
|
||||
job_name=config.slurm.job_name,
|
||||
project_dir=config.slurm.project_dir,
|
||||
partition=config.slurm.partition,
|
||||
output_dir=config.output_dir,
|
||||
orchestrator_output_dir=config.orchestrator.output_dir,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes,
|
||||
num_teacher_nodes=config.deployment.num_teacher_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
slurm_log_dir = config.output_dir / "slurm"
|
||||
log_message = (
|
||||
f"Logs:\n"
|
||||
f" Trainer: tail -F {slurm_log_dir}/latest_train_node_rank_0.log\n"
|
||||
f" Orchestrator: tail -F {slurm_log_dir}/latest_orchestrator.log\n"
|
||||
f" Inference: tail -F {slurm_log_dir}/latest_infer_node_rank_0.log"
|
||||
)
|
||||
|
||||
return script, log_message
|
||||
|
||||
|
||||
def rl_slurm(config: RLConfig):
|
||||
assert config.slurm is not None
|
||||
assert config.output_dir is not None
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = config.output_dir / "configs"
|
||||
|
||||
if config.deployment.type == "multi_node":
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
|
||||
script, log_message = render_slurm_script(config, config_dir)
|
||||
script_path = config.output_dir / "rl.sbatch"
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
if config.slurm.dry_run:
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
return
|
||||
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
|
||||
|
||||
def rl(config: RLConfig):
|
||||
if config.slurm is not None:
|
||||
rl_slurm(config)
|
||||
else:
|
||||
rl_local(config)
|
||||
|
||||
|
||||
def main():
|
||||
rl(parse_argv(RLConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,202 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.trainer.sft.config import SFTTrainerConfig
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
|
||||
def write_trainer_config(config: SFTTrainerConfig, output_dir: Path) -> None:
|
||||
"""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")
|
||||
with open(output_dir / "trainer.toml", "wb") as f:
|
||||
tomli_w.dump(trainer_data, f)
|
||||
|
||||
|
||||
def render_slurm_script(config: SFTTrainerConfig, config_dir: Path) -> tuple[str, str]:
|
||||
"""Render the SLURM script template. Returns (script, log_message)."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
assert config.slurm is not None
|
||||
assert config.slurm.template_path is not None
|
||||
|
||||
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
|
||||
template = env.get_template(config.slurm.template_path.name)
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
config_path = config_dir / "sft.toml"
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
with open(config_path, "wb") as f:
|
||||
tomli_w.dump(config.model_dump(exclude={"slurm"}, exclude_none=True, mode="json"), f)
|
||||
|
||||
script = template.render(
|
||||
config_path=config_path,
|
||||
output_dir=config.output_dir,
|
||||
job_name=config.slurm.job_name,
|
||||
project_dir=config.slurm.project_dir,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
partition=config.slurm.partition,
|
||||
)
|
||||
log_dir = config.output_dir / "logs"
|
||||
log_message = f"Logs:\n Trainer: tail -F {log_dir}/trainer/rank_0.log"
|
||||
else:
|
||||
script = template.render(
|
||||
config_dir=config_dir,
|
||||
output_dir=config.output_dir,
|
||||
job_name=config.slurm.job_name,
|
||||
project_dir=config.slurm.project_dir,
|
||||
num_nodes=config.deployment.num_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
partition=config.slurm.partition,
|
||||
)
|
||||
log_message = f"Logs:\n Trainer: tail -F {config.output_dir}/slurm/latest_train_node_rank_0.log"
|
||||
|
||||
return script, log_message
|
||||
|
||||
|
||||
def sft_slurm(config: SFTTrainerConfig):
|
||||
"""Run SFT training via SLURM."""
|
||||
assert config.slurm is not None
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = config.output_dir / "configs"
|
||||
|
||||
if config.deployment.type == "multi_node":
|
||||
write_trainer_config(config, config_dir)
|
||||
logger.info(f"Wrote trainer config to {config_dir}")
|
||||
|
||||
script, log_message = render_slurm_script(config, config_dir)
|
||||
script_path = config.output_dir / "sft.sbatch"
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
if config.slurm.dry_run:
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
return
|
||||
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
|
||||
|
||||
def sft_local(config: SFTTrainerConfig):
|
||||
"""Run SFT training locally with process monitoring and cleanup."""
|
||||
assert config.deployment.type == "single_node"
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = Path(".pydantic_config") / uuid.uuid4().hex
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
config_path = config_dir / "trainer.toml"
|
||||
with open(config_path, "wb") as f:
|
||||
tomli_w.dump(config.model_dump(exclude={"deployment"}, exclude_none=True, mode="json"), f)
|
||||
|
||||
log_dir = config.output_dir / "logs"
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
trainer_cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"env",
|
||||
"PYTHONUNBUFFERED=1",
|
||||
"PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True",
|
||||
"torchrun",
|
||||
f"--rdzv-endpoint=localhost:{get_free_port()}",
|
||||
f"--rdzv-id={uuid.uuid4().hex}",
|
||||
f"--log-dir={config.output_dir / 'torchrun'}",
|
||||
"--local-ranks-filter=0",
|
||||
"--redirect=3",
|
||||
"--tee=3",
|
||||
f"--nproc-per-node={config.deployment.num_gpus}",
|
||||
"-m",
|
||||
"prime_rl.trainer.sft.train",
|
||||
"@",
|
||||
config_path.as_posix(),
|
||||
]
|
||||
|
||||
logger.info(f"Starting SFT trainer with {config.deployment.num_gpus} GPU(s)")
|
||||
logger.debug(f"Trainer command: {' '.join(trainer_cmd)}")
|
||||
|
||||
processes: list[Popen] = []
|
||||
monitor_threads: list[Thread] = []
|
||||
error_queue: list[Exception] = []
|
||||
|
||||
try:
|
||||
with open(log_dir / "trainer.stdout", "w") as log_file:
|
||||
trainer_process = Popen(
|
||||
trainer_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(trainer_process)
|
||||
|
||||
stop_event = Event()
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(trainer_process, stop_event, error_queue, "trainer"),
|
||||
daemon=True,
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
logger.success("Startup complete. Showing trainer logs...")
|
||||
tail_process = Popen(["tail", "-F", str(log_dir / "trainer.stdout")])
|
||||
processes.append(tail_process)
|
||||
|
||||
stop_event.wait()
|
||||
|
||||
if trainer_process.returncode != 0:
|
||||
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
logger.success("SFT training finished!")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.warning("Received interrupt signal, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
logger.error(f"Error occurred: {e}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
raise
|
||||
|
||||
|
||||
def sft(config: SFTTrainerConfig):
|
||||
if config.slurm is not None:
|
||||
sft_slurm(config)
|
||||
else:
|
||||
sft_local(config)
|
||||
|
||||
|
||||
def main():
|
||||
sft(parse_argv(SFTTrainerConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,666 +0,0 @@
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
from typing import Annotated, Literal
|
||||
|
||||
import pynvml
|
||||
import tomli_w
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.rl_config import BaseRLConfig
|
||||
from prime_rl.trainer.rl.config import FakeDataLoaderConfig
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pydantic_config import BaseSettings, parse_argv
|
||||
from prime_rl.utils.utils import (
|
||||
get_broadcast_dir,
|
||||
get_free_port,
|
||||
get_log_dir,
|
||||
get_rollout_dir,
|
||||
)
|
||||
|
||||
|
||||
class SharedLogConfig(BaseSettings):
|
||||
"""Configures shared logging."""
|
||||
|
||||
level: Annotated[str | None, Field(description="The log level to use.")] = "info"
|
||||
|
||||
file: Annotated[bool | None, Field(description="Whether to log to a file.")] = True
|
||||
|
||||
json_logging: Annotated[
|
||||
bool,
|
||||
Field(description="Emit JSON logs (newline-delimited) for log aggregation (Loki, Grafana, etc.)."),
|
||||
] = False
|
||||
|
||||
|
||||
class SharedWandbConfig(BaseSettings):
|
||||
"""Configures shared W&B configs."""
|
||||
|
||||
project: Annotated[str | None, Field(description="The W&B project to use.")] = "prime-rl"
|
||||
|
||||
name: Annotated[str | None, Field(description="The W&B run name to use.")] = None
|
||||
|
||||
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
|
||||
|
||||
|
||||
class SharedCheckpointConfig(BaseSettings):
|
||||
"""Configures shared checkpoint configs."""
|
||||
|
||||
interval: Annotated[int | None, Field(description="The interval at which to save checkpoints.")] = None
|
||||
|
||||
resume_step: Annotated[
|
||||
int | None, Field(description="The step to resume from. If None, will not resume from a checkpoint.")
|
||||
] = None
|
||||
|
||||
keep_last: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency.",
|
||||
),
|
||||
] = None
|
||||
|
||||
keep_interval: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Keep checkpoints at every N steps permanently (e.g., keep_interval=100 keeps step 100, 200, ...). If None, no interval-based keeping.",
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class SharedModelConfig(BaseSettings):
|
||||
"""Configures shared model settings."""
|
||||
|
||||
name: Annotated[
|
||||
str,
|
||||
Field(description="The name of the model to use."),
|
||||
] = "Qwen/Qwen3-0.6B"
|
||||
|
||||
|
||||
class SharedWeightBroadcastConfig(BaseSettings):
|
||||
"""Configures shared weight broadcast settings."""
|
||||
|
||||
type: Annotated[Literal["nccl", "filesystem"], Field(description="The type of weight broadcast to use.")] = (
|
||||
"filesystem"
|
||||
)
|
||||
|
||||
|
||||
class RLConfig(BaseRLConfig):
|
||||
"""Configures an RL training run."""
|
||||
|
||||
clean: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to clean the rollouts, checkpoint, checkpoint weights and logs directories at the beginning of the run. If True, will forceably, and irreversibly, delete all directories.",
|
||||
),
|
||||
] = True
|
||||
|
||||
inference_gpu_ids: Annotated[list[int], Field(description="The GPU IDs to use for inference.")] = [0]
|
||||
trainer_gpu_ids: Annotated[list[int], Field(description="The GPU IDs to use for trainer.")] = [1]
|
||||
teacher_gpu_ids: Annotated[
|
||||
list[int] | None,
|
||||
Field(
|
||||
description="The GPU IDs to use for teacher inference. If None, teacher inference server will not be started."
|
||||
),
|
||||
] = None
|
||||
|
||||
teacher_inference: Annotated[
|
||||
InferenceConfig | None,
|
||||
Field(
|
||||
description="The teacher inference config. If None, will use the same config as inference (if available) or a default config. Only used when teacher_gpu_ids is set."
|
||||
),
|
||||
] = None
|
||||
|
||||
### Shared configurations
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
Field(description="The directory to store the outputs. Should typically be set to an experiment identifier."),
|
||||
] = Path("outputs") # NOTE: Must match `OUTPUT_DIR` in `tmux.sh` to see logs
|
||||
|
||||
bench: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to run in benchmark mode. It will automatically set the trainer and orchestrator to benchmark mode and, if present, configure the W&B project by suffixing the project with `-bench`.",
|
||||
),
|
||||
] = False
|
||||
|
||||
dump_config: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="If set, dump resolved subconfigs (trainer, orchestrator, inference) to this directory and exit without starting any processes."
|
||||
),
|
||||
] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_dp(self):
|
||||
if self.inference and len(self.inference_gpu_ids) != self.inference.parallel.dp * self.inference.parallel.tp:
|
||||
assert len(self.inference_gpu_ids) % self.inference.parallel.tp == 0, (
|
||||
"Number of inference GPUs must be divisible by the tensor parallel size"
|
||||
)
|
||||
self.inference.parallel.dp = len(self.inference_gpu_ids) // self.inference.parallel.tp
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_num_train_workers(self):
|
||||
non_data_parallel_size = self.trainer.model.cp * self.trainer.model.tp
|
||||
|
||||
if len(self.trainer_gpu_ids) > 1:
|
||||
self.orchestrator.num_train_workers = len(self.trainer_gpu_ids) // non_data_parallel_size
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench:
|
||||
# Set trainer and orchestrator to benchmark mode
|
||||
self.trainer.bench = True
|
||||
self.orchestrator.bench = True
|
||||
|
||||
# Configure the trainer fake data to match the orchestrator config
|
||||
self.trainer.data.fake = FakeDataLoaderConfig(
|
||||
batch_size=self.orchestrator.batch_size,
|
||||
)
|
||||
|
||||
trainer_bench_enabled = self.trainer.bench is not None
|
||||
if trainer_bench_enabled != self.orchestrator.bench:
|
||||
raise ValueError(
|
||||
f"Trainer benchmark mode ({self.trainer.bench}) and orchestrator benchmark mode ({self.orchestrator.bench}) are not the same. Please specify the same benchmark mode for both."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_lora(self):
|
||||
if self.trainer.model.lora is not None:
|
||||
if self.trainer.weight_broadcast.type == "nccl":
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
|
||||
# Ensure orchestrator has LoRA config
|
||||
if self.orchestrator.model.lora is None:
|
||||
from prime_rl.orchestrator.config import LoRAConfig
|
||||
|
||||
self.orchestrator.model.lora = LoRAConfig()
|
||||
|
||||
# Validate orchestrator LoRA rank/alpha don't conflict with trainer
|
||||
if (
|
||||
self.orchestrator.model.lora.rank is not None
|
||||
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
|
||||
):
|
||||
raise ValueError(
|
||||
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
|
||||
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
|
||||
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
|
||||
)
|
||||
|
||||
if (
|
||||
self.orchestrator.model.lora.alpha is not None
|
||||
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
|
||||
):
|
||||
raise ValueError(
|
||||
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
|
||||
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
|
||||
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
|
||||
)
|
||||
|
||||
# Propagate rank/alpha from trainer when not explicitly set
|
||||
if self.orchestrator.model.lora.rank is None:
|
||||
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
|
||||
|
||||
if self.orchestrator.model.lora.alpha is None:
|
||||
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
|
||||
|
||||
# Auto-generate name if not provided
|
||||
if self.orchestrator.model.lora.name is None:
|
||||
self.orchestrator.model.lora.name = (
|
||||
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
|
||||
)
|
||||
|
||||
if self.inference is not None:
|
||||
self.inference.enable_lora = True
|
||||
self.inference.max_lora_rank = self.trainer.model.lora.rank
|
||||
else:
|
||||
warnings.warn(
|
||||
"LoRA is enabled, but inference is not configured. When manually starting the inference server, make sure to set `--enable_lora` and `--max-lora-rank`."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_enough_devices_for_nccl(self):
|
||||
if self.trainer.weight_broadcast.type == "nccl":
|
||||
num_gpus = len(set(self.trainer_gpu_ids + self.inference_gpu_ids))
|
||||
if num_gpus < 2:
|
||||
raise ValueError("NCCL weight broadcast requires at least 2 GPUs to build the broadcast process group.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_teacher_inference(self):
|
||||
"""Auto-configure teacher inference server and orchestrator teacher_model client."""
|
||||
if self.teacher_gpu_ids is None or len(self.teacher_gpu_ids) == 0:
|
||||
return self
|
||||
|
||||
import copy
|
||||
|
||||
from prime_rl.orchestrator.config import TeacherModelConfig
|
||||
|
||||
# Create or complete teacher_inference config
|
||||
if self.teacher_inference is None:
|
||||
self.teacher_inference = copy.deepcopy(self.inference) if self.inference else InferenceConfig()
|
||||
# Avoid port conflict with main inference by using next port
|
||||
if self.inference is not None:
|
||||
self.teacher_inference.server.port = self.inference.server.port + 1
|
||||
elif self.inference is not None and self.teacher_inference.server.port == self.inference.server.port:
|
||||
raise ValueError(
|
||||
f"teacher_inference.server.port ({self.teacher_inference.server.port}) conflicts with "
|
||||
f"inference.server.port ({self.inference.server.port}). "
|
||||
"Either use different ports or let teacher_inference be auto-configured."
|
||||
)
|
||||
|
||||
# Auto-configure DP based on GPU count
|
||||
tp = self.teacher_inference.parallel.tp
|
||||
if len(self.teacher_gpu_ids) != self.teacher_inference.parallel.dp * tp:
|
||||
assert len(self.teacher_gpu_ids) % tp == 0, (
|
||||
"Number of teacher GPUs must be divisible by tensor parallel size"
|
||||
)
|
||||
assert len(self.teacher_gpu_ids) > 0, "teacher_gpu_ids cannot be empty"
|
||||
self.teacher_inference.parallel.dp = len(self.teacher_gpu_ids) // tp
|
||||
|
||||
# Auto-configure orchestrator's teacher_model client
|
||||
if self.orchestrator.teacher_model is None:
|
||||
self.orchestrator.teacher_model = TeacherModelConfig()
|
||||
host = self.teacher_inference.server.host or "localhost"
|
||||
port = self.teacher_inference.server.port
|
||||
self.orchestrator.teacher_model.client.base_url = [f"http://{host}:{port}/v1"]
|
||||
self.orchestrator.teacher_model.model.name = self.teacher_inference.model.name
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_teacher_model(self):
|
||||
if self.trainer.loss.teacher_tau > 0 and not self.orchestrator.teacher_model:
|
||||
raise ValueError(
|
||||
"teacher_model must be configured when teacher_tau > 0. "
|
||||
"Either set teacher_tau = 0, set teacher_gpu_ids, or configure teacher_model manually."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
def cleanup_threads(threads: list[Thread]):
|
||||
for thread in threads:
|
||||
thread.join(timeout=5)
|
||||
|
||||
|
||||
def cleanup_processes(processes: list[Popen]):
|
||||
for process in processes:
|
||||
if process.poll() is None: # Process is still running
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=60) # 60 seconds to terminate gracefully
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
|
||||
|
||||
def monitor_process(process: Popen, stop_event: Event, error_queue: list, process_name: str):
|
||||
"""Monitor a subprocess and signal errors via shared queue"""
|
||||
try:
|
||||
# Wait for process to complete
|
||||
process.wait()
|
||||
|
||||
if process.returncode != 0:
|
||||
err_msg = f"{process_name.capitalize()} failed with exit code {process.returncode}"
|
||||
if process.stderr:
|
||||
err_msg += f"\n{process.stderr.read().decode('utf-8')}"
|
||||
error_queue.append(RuntimeError(err_msg))
|
||||
stop_event.set()
|
||||
except Exception as e:
|
||||
error_queue.append(RuntimeError(f"Error monitoring {process_name}: {e}"))
|
||||
stop_event.set()
|
||||
|
||||
|
||||
def check_gpus_available(gpu_ids: list[int]) -> None:
|
||||
"""Raise error if there are existing processes on the specified GPUs."""
|
||||
pynvml.nvmlInit()
|
||||
|
||||
occupied = []
|
||||
for gpu_id in gpu_ids:
|
||||
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_id)
|
||||
processes = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
|
||||
if processes:
|
||||
pids = [p.pid for p in processes]
|
||||
occupied.append((gpu_id, pids))
|
||||
|
||||
if occupied:
|
||||
msg = "Existing processes found on GPUs:\n"
|
||||
for gpu_id, pids in occupied:
|
||||
msg += f" GPU {gpu_id}: PIDs {pids}\n"
|
||||
msg += "Kill these processes or use different GPUs."
|
||||
raise RuntimeError(msg)
|
||||
|
||||
|
||||
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
"""Write resolved subconfigs to disk as TOML files."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(output_dir / "trainer.toml", "wb") as f:
|
||||
tomli_w.dump(config.trainer.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
with open(output_dir / "orchestrator.toml", "wb") as f:
|
||||
tomli_w.dump(config.orchestrator.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
if config.inference is not None:
|
||||
with open(output_dir / "inference.toml", "wb") as f:
|
||||
tomli_w.dump(config.inference.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
if config.teacher_inference is not None:
|
||||
with open(output_dir / "teacher_inference.toml", "wb") as f:
|
||||
tomli_w.dump(config.teacher_inference.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
|
||||
def rl(config: RLConfig):
|
||||
# Setup logger
|
||||
logger = setup_logger(
|
||||
config.log.level or "info",
|
||||
log_file=config.output_dir / "logs" / "rl.log" if config.log.file else None,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
|
||||
# If dump_config is set, write resolved subconfigs and exit early
|
||||
if config.dump_config is not None:
|
||||
logger.warning(
|
||||
"--dump-config is set. No RL training will be started. Only writing resolved subconfigs to disk."
|
||||
)
|
||||
write_subconfigs(config, config.dump_config)
|
||||
logger.info(f"Dumping resolved subconfigs to {config.dump_config}")
|
||||
logger.info(f" Wrote trainer config to {config.dump_config / 'trainer.toml'}")
|
||||
logger.info(f" Wrote orchestrator config to {config.dump_config / 'orchestrator.toml'}")
|
||||
if config.inference is not None:
|
||||
logger.info(f" Wrote inference config to {config.dump_config / 'inference.toml'}")
|
||||
if config.teacher_inference is not None:
|
||||
logger.info(f" Wrote teacher inference config to {config.dump_config / 'teacher_inference.toml'}")
|
||||
logger.success(f"Config dump complete. Files written to {config.dump_config}")
|
||||
logger.warning("To start an RL run, remove --dump-config from your command.")
|
||||
return
|
||||
|
||||
start_command = sys.argv
|
||||
logger.info("Starting RL run")
|
||||
logger.debug(f"RL start command: {' '.join(start_command)}")
|
||||
|
||||
# Check for existing processes on GPUs
|
||||
all_gpu_ids = list(set(config.inference_gpu_ids + config.trainer_gpu_ids + (config.teacher_gpu_ids or [])))
|
||||
check_gpus_available(all_gpu_ids)
|
||||
|
||||
# Validate client port matches inference server port
|
||||
if config.inference is not None and not config.orchestrator.client.is_elastic:
|
||||
from urllib.parse import urlparse
|
||||
|
||||
base_url = config.orchestrator.client.base_url[0]
|
||||
parsed = urlparse(base_url)
|
||||
client_port = parsed.port
|
||||
expected_port = config.inference.server.port
|
||||
if client_port != expected_port:
|
||||
raise ValueError(
|
||||
f"orchestrator.client.base_url port ({client_port}) does not match "
|
||||
f"inference.server.port ({expected_port}). "
|
||||
f"Update the base_url to use port {expected_port} to match the inference server."
|
||||
)
|
||||
|
||||
# Prepare paths to communicate with the trainer
|
||||
log_dir = get_log_dir(config.output_dir)
|
||||
orch_log_dir = get_log_dir(config.orchestrator.output_dir)
|
||||
rollout_dir = get_rollout_dir(config.orchestrator.output_dir)
|
||||
broadcast_dir = get_broadcast_dir(config.orchestrator.output_dir)
|
||||
|
||||
# Clean up directories if specified
|
||||
if config.clean:
|
||||
logger.info("Cleaning checkpoint, logs, weights, broadcast and rollout directories")
|
||||
|
||||
# Cleaning logs (so that streaming logs to terminal works)
|
||||
logger.info(f"Cleaning log dir ({log_dir})")
|
||||
shutil.rmtree(log_dir, ignore_errors=True)
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
logger.info(f"Cleaning orchestrator log dir ({orch_log_dir})")
|
||||
shutil.rmtree(orch_log_dir, ignore_errors=True)
|
||||
orch_log_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Cleaning broadcast dir (so that orchestrator does not pre-maturely update weights)
|
||||
if not (
|
||||
config.ckpt
|
||||
and config.ckpt.resume_step
|
||||
and config.trainer.weight_broadcast
|
||||
and config.trainer.weight_broadcast.type == "filesystem"
|
||||
):
|
||||
logger.info(f"Cleaning broadcast directory ({broadcast_dir})")
|
||||
shutil.rmtree(broadcast_dir, ignore_errors=True)
|
||||
|
||||
# Cleaning rollouts (so that trainer does not train on old rollouts)
|
||||
logger.info(f"Cleaning rollout dir ({rollout_dir})")
|
||||
shutil.rmtree(rollout_dir, ignore_errors=True)
|
||||
|
||||
# Write all resolved subconfigs to disk
|
||||
config_dir = Path(".pydantic_config") / uuid.uuid4().hex
|
||||
write_subconfigs(config, config_dir)
|
||||
|
||||
# Start processes
|
||||
processes: list[Popen] = []
|
||||
monitor_threads: list[Thread] = []
|
||||
error_queue: list[Exception] = []
|
||||
stop_events: dict[str, Event] = {}
|
||||
|
||||
try:
|
||||
# Optionally, start inference process
|
||||
if config.inference:
|
||||
inference_cmd = ["uv", "run", "inference", "@", (config_dir / "inference.toml").as_posix()]
|
||||
logger.info(f"Starting inference process on GPU(s) {' '.join(map(str, config.inference_gpu_ids))}")
|
||||
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
|
||||
# If we don't log stdout, the server hangs
|
||||
with open(log_dir / "inference.stdout", "w") as log_file:
|
||||
inference_process = Popen(
|
||||
inference_cmd,
|
||||
env={**os.environ, "CUDA_VISIBLE_DEVICES": ",".join(map(str, config.inference_gpu_ids))},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(inference_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["inference"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(inference_process, stop_event, error_queue, "inference"),
|
||||
daemon=True,
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
else:
|
||||
logger.warning(
|
||||
"No inference config specified, skipping starting inference server. Is your inference server running?"
|
||||
)
|
||||
|
||||
# Optionally, start teacher inference process
|
||||
if config.teacher_inference:
|
||||
if config.teacher_gpu_ids is None or len(config.teacher_gpu_ids) == 0:
|
||||
raise ValueError(
|
||||
"teacher_inference is configured but teacher_gpu_ids is not set or is empty. "
|
||||
"Either set teacher_gpu_ids to start a teacher inference server, "
|
||||
"or omit teacher_inference and configure orchestrator.teacher_model to use an existing server."
|
||||
)
|
||||
|
||||
teacher_inference_cmd = ["uv", "run", "inference", "@", (config_dir / "teacher_inference.toml").as_posix()]
|
||||
logger.info(f"Starting teacher inference process on GPU(s) {' '.join(map(str, config.teacher_gpu_ids))}")
|
||||
logger.debug(f"Teacher inference start command: {' '.join(teacher_inference_cmd)}")
|
||||
with open(log_dir / "teacher_inference.stdout", "w") as log_file:
|
||||
teacher_inference_process = Popen(
|
||||
teacher_inference_cmd,
|
||||
env={**os.environ, "CUDA_VISIBLE_DEVICES": ",".join(map(str, config.teacher_gpu_ids))},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(teacher_inference_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["teacher_inference"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(teacher_inference_process, stop_event, error_queue, "teacher_inference"),
|
||||
daemon=True,
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
elif config.trainer.loss.teacher_tau > 0 or config.orchestrator.teacher_model:
|
||||
logger.warning(
|
||||
"No teacher_inference config specified, skipping starting teacher inference server. "
|
||||
"Is your teacher inference server running? Make sure orchestrator.teacher_model is configured."
|
||||
)
|
||||
|
||||
# Start orchestrator process
|
||||
orchestrator_cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"orchestrator",
|
||||
"@",
|
||||
(config_dir / "orchestrator.toml").as_posix(),
|
||||
]
|
||||
logger.info("Starting orchestrator process")
|
||||
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
|
||||
with open(log_dir / "orchestrator.stdout", "w") as log_file:
|
||||
orchestrator_process = Popen(
|
||||
orchestrator_cmd,
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
env={
|
||||
**os.environ,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
},
|
||||
)
|
||||
processes.append(orchestrator_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["orchestrator"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(orchestrator_process, stop_event, error_queue, "orchestrator"),
|
||||
daemon=True,
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
# Start training process
|
||||
trainer_cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"env",
|
||||
"PYTHONUNBUFFERED=1",
|
||||
"PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True",
|
||||
"torchrun",
|
||||
f"--rdzv-endpoint=localhost:{get_free_port()}",
|
||||
f"--rdzv-id={uuid.uuid4().hex}",
|
||||
# Pipe all logs to file, and only master rank logs to stdout
|
||||
f"--log-dir={config.output_dir / 'torchrun'}",
|
||||
"--local-ranks-filter=0",
|
||||
"--redirect=3",
|
||||
"--tee=3",
|
||||
f"--nproc-per-node={len(config.trainer_gpu_ids)}",
|
||||
"-m",
|
||||
"prime_rl.trainer.rl.train",
|
||||
"@",
|
||||
(config_dir / "trainer.toml").as_posix(),
|
||||
]
|
||||
logger.info(f"Starting trainer process on GPU(s) {' '.join(map(str, config.trainer_gpu_ids))}")
|
||||
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
|
||||
with open(log_dir / "trainer.stdout", "w") as log_file:
|
||||
trainer_process = Popen(
|
||||
trainer_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, config.trainer_gpu_ids)),
|
||||
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(trainer_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["trainer"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process, args=(trainer_process, stop_event, error_queue, "trainer"), daemon=True
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
# Monitor all processes for failures
|
||||
logger.success("Startup complete. Showing trainer logs...")
|
||||
|
||||
tail_process = Popen(["tail", "-F", log_dir / "trainer.stdout"])
|
||||
processes.append(tail_process)
|
||||
|
||||
# Check for errors from monitor threads
|
||||
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
|
||||
if error_queue:
|
||||
error = error_queue[0]
|
||||
logger.error(f"Error: {error}")
|
||||
logger.error("Terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
# Small delay to avoid busy waiting
|
||||
time.sleep(1)
|
||||
|
||||
# Check if any critical process failed
|
||||
if orchestrator_process.returncode != 0:
|
||||
logger.error(f"Orchestrator failed with exit code {orchestrator_process.returncode}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
if trainer_process.returncode != 0:
|
||||
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
logger.success("RL training finished!")
|
||||
|
||||
# Cleanup threads and processes
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.warning("Received interrupt signal, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
logger.error(f"Error occurred: {e}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
raise
|
||||
|
||||
|
||||
def main():
|
||||
rl(parse_argv(RLConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+357
-31
@@ -1,8 +1,10 @@
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic.config import ConfigDict
|
||||
from pydantic.main import BaseModel
|
||||
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.inference.config import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
@@ -10,7 +12,9 @@ from prime_rl.orchestrator.config import CheckpointConfig as OrchestratorCheckpo
|
||||
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
|
||||
@@ -96,26 +100,93 @@ class SharedWeightBroadcastConfig(BaseSettings):
|
||||
timeout: Annotated[int, Field(description="The timeout in seconds for NCCL weight broadcast.")] = 1200
|
||||
|
||||
|
||||
class BaseRLConfig(BaseSettings):
|
||||
"""Configures an RL training run."""
|
||||
class BaseDeploymentConfig(BaseModel):
|
||||
"""Configures a base deployment."""
|
||||
|
||||
### Submodule configurations
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
trainer: TrainerConfig
|
||||
orchestrator: OrchestratorConfig
|
||||
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
|
||||
|
||||
output_dir: Annotated[
|
||||
Path | None,
|
||||
Field(description="The directory to store the outputs. Should typically be set to an experiment identifier."),
|
||||
] = None
|
||||
inference: Annotated[
|
||||
InferenceConfig | None,
|
||||
|
||||
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
"""Configures a single node deployment."""
|
||||
|
||||
type: Literal["single_node"] = "single_node"
|
||||
|
||||
num_train_gpus: Annotated[int, Field(description="Number of training GPUs")] = 1
|
||||
num_infer_gpus: Annotated[int, Field(description="Number of inference GPUs")] = 1
|
||||
num_teacher_gpus: Annotated[int | None, Field(description="Number of teacher inference GPUs")] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_gpu_count(self):
|
||||
total = self.num_train_gpus + self.num_infer_gpus + (self.num_teacher_gpus or 0)
|
||||
if total > self.gpus_per_node:
|
||||
raise ValueError(
|
||||
f"Total GPU count ({total} = {self.num_train_gpus} train + {self.num_infer_gpus} infer"
|
||||
f" + {self.num_teacher_gpus or 0} teacher) exceeds gpus_per_node ({self.gpus_per_node})."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
"""Configures a multi node deployment."""
|
||||
|
||||
type: Literal["multi_node"] = "multi_node"
|
||||
|
||||
num_train_nodes: Annotated[int, Field(description="Number of training nodes.")]
|
||||
num_infer_nodes: Annotated[int, Field(description="Number of inference nodes.")]
|
||||
num_teacher_nodes: Annotated[int | None, Field(description="Number of teacher inference nodes.")] = None
|
||||
|
||||
nodes_per_fsdp_group: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="The inference config. If None, will not start an inference process. Only viable, if an inference server was started manually."
|
||||
description="Number of training nodes per FSDP island. Auto-sets trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group."
|
||||
),
|
||||
] = None
|
||||
|
||||
### Top-level configurations
|
||||
@model_validator(mode="after")
|
||||
def teacher_inference_not_supported(self):
|
||||
if self.num_teacher_nodes is not None:
|
||||
raise ValueError("Teacher inference is not yet supported in multi node deployment.")
|
||||
return self
|
||||
|
||||
|
||||
DeploymentConfigType: TypeAlias = Annotated[
|
||||
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class RLConfig(BaseSettings):
|
||||
"""Configures an RL training run."""
|
||||
|
||||
trainer: TrainerConfig
|
||||
orchestrator: OrchestratorConfig
|
||||
inference: Annotated[
|
||||
InferenceConfig | None,
|
||||
Field(
|
||||
description="The inference config. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."
|
||||
),
|
||||
] = None
|
||||
|
||||
teacher_inference: Annotated[
|
||||
InferenceConfig | None,
|
||||
Field(
|
||||
description="Teacher inference config. If None, will use the same config as inference or a default config. Only used when teacher GPUs or nodes are set."
|
||||
),
|
||||
] = None
|
||||
|
||||
output_dir: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="The directory to store the outputs. Should be set to a unique directory identifying the experiment."
|
||||
),
|
||||
] = None
|
||||
|
||||
deployment: Annotated[DeploymentConfigType, Field(discriminator="type")] = SingleNodeDeploymentConfig()
|
||||
|
||||
slurm: Annotated[SlurmConfig | None, Field(description="SLURM configuration. If None, will run locally.")] = None
|
||||
|
||||
### Shared configurations
|
||||
|
||||
log: Annotated[
|
||||
SharedLogConfig,
|
||||
@@ -177,10 +248,108 @@ class BaseRLConfig(BaseSettings):
|
||||
SharedWeightBroadcastConfig | None, Field(description="The weight broadcast config.")
|
||||
] = None
|
||||
|
||||
### Setup and validate shared configs
|
||||
### Local-only fields
|
||||
|
||||
clean: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to clean the rollouts, checkpoint, checkpoint weights and logs directories at the beginning of the run.",
|
||||
),
|
||||
] = True
|
||||
|
||||
bench: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to run in benchmark mode. Automatically sets the trainer and orchestrator to benchmark mode and, if present, suffixes the W&B project with `-bench`.",
|
||||
),
|
||||
] = False
|
||||
|
||||
dump_config: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="If set, dump resolved subconfigs (trainer, orchestrator, inference) to this directory and exit without starting any processes."
|
||||
),
|
||||
] = None
|
||||
|
||||
### Pre-validation normalization
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def normalize_deployment(cls, data):
|
||||
# nested_model_default_partial_update=True merges the SingleNodeDeploymentConfig()
|
||||
# default into loaded data before validation. When the user switches to multi_node,
|
||||
# single-node-only fields (num_train_gpus etc.) get carried over and cause errors.
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
deployment = data.get("deployment")
|
||||
if isinstance(deployment, dict) and deployment.get("type") == "multi_node":
|
||||
for key in ("num_train_gpus", "num_infer_gpus", "num_teacher_gpus"):
|
||||
deployment.pop(key, None)
|
||||
return data
|
||||
|
||||
### Validate configs (e.g. raise for unsupported (combinations of) configs)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_deployment(self):
|
||||
if self.deployment.type == "multi_node":
|
||||
if self.slurm is None:
|
||||
raise ValueError("Must use SLURM for multi-node deployment.")
|
||||
if not self.inference:
|
||||
raise ValueError("Must configure inference when using multi-node deployment.")
|
||||
return self
|
||||
|
||||
# TODO: fix this
|
||||
@model_validator(mode="after")
|
||||
def validate_no_teacher_in_multinode(self):
|
||||
if self.deployment.type == "multi_node" and self.teacher_inference is not None:
|
||||
raise ValueError(
|
||||
"Teacher inference is not supported in multi-node deployment. "
|
||||
"The SLURM template only handles inference and training nodes."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_enough_devices_for_nccl(self):
|
||||
if self.deployment.type == "single_node":
|
||||
if self.trainer.weight_broadcast.type == "nccl":
|
||||
if self.deployment.num_train_gpus + self.deployment.num_infer_gpus < 2:
|
||||
raise ValueError(
|
||||
"NCCL weight broadcast requires at least 2 GPUs to build the broadcast process group."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_teacher_model(self):
|
||||
if (
|
||||
self.trainer.loss.type == "default" and self.trainer.loss.teacher_tau > 0
|
||||
) and not self.orchestrator.teacher_model:
|
||||
raise ValueError(
|
||||
"teacher_model must be configured when teacher_tau > 0. "
|
||||
"Either set teacher_tau = 0, set deployment.num_teacher_gpus, or configure teacher_model manually."
|
||||
)
|
||||
return self
|
||||
|
||||
### Auto-setup and validate shared configs
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_output_dir(self):
|
||||
"""Auto-setup shared output directory for trainer and orchestrator. With SLURM, no default is set to avoid overwriting experiment outputs."""
|
||||
if self.slurm is None:
|
||||
if self.output_dir is None:
|
||||
self.output_dir = Path("outputs")
|
||||
else:
|
||||
if self.output_dir is None:
|
||||
raise ValueError("output_dir must be set explicitly when using SLURM.")
|
||||
self.trainer.output_dir = self.output_dir
|
||||
self.orchestrator.output_dir = self.output_dir / "run_default"
|
||||
|
||||
validate_shared_output_dir(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_logs(self):
|
||||
"""Auto-setup shared log config for trainer and orchestrator."""
|
||||
if self.log is not None:
|
||||
if self.log.level is not None:
|
||||
self.trainer.log.level = self.log.level
|
||||
@@ -195,7 +364,7 @@ class BaseRLConfig(BaseSettings):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_ckpt(self):
|
||||
# If specified, automatically setup checkpoint configs for trainer and orchestrator
|
||||
"""Auto-setup shared checkpoint config for trainer and orchestrator."""
|
||||
if self.ckpt is not None:
|
||||
# Create checkpoint configs if not specified
|
||||
if self.trainer.ckpt is None:
|
||||
@@ -228,7 +397,7 @@ class BaseRLConfig(BaseSettings):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_wandb(self):
|
||||
# If specified, automatically use shared W&B project for orchestrator and trainer
|
||||
"""Auto-setup shared W&B config for trainer and orchestrator."""
|
||||
if self.wandb is not None:
|
||||
if not self.trainer.wandb:
|
||||
self.trainer.wandb = WandbConfig()
|
||||
@@ -255,7 +424,7 @@ class BaseRLConfig(BaseSettings):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_model(self):
|
||||
# Use the same model for trainer, orchestrator and inference
|
||||
"""Auto-setup shared model config for trainer, orchestrator, and inference."""
|
||||
if self.model is not None:
|
||||
self.trainer.model.name = self.model.name
|
||||
self.orchestrator.model.name = self.model.name
|
||||
@@ -271,7 +440,7 @@ class BaseRLConfig(BaseSettings):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_max_steps(self):
|
||||
# If specified, use the same max steps for trainer and orchestrator
|
||||
"""Auto-setup shared max steps for trainer and orchestrator."""
|
||||
if self.max_steps is not None:
|
||||
self.trainer.max_steps = self.max_steps
|
||||
self.orchestrator.max_steps = self.max_steps
|
||||
@@ -282,7 +451,7 @@ class BaseRLConfig(BaseSettings):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_async_level(self):
|
||||
# If specified, use the same async level for trainer and orchestrator
|
||||
"""Auto-setup shared async level for trainer and orchestrator."""
|
||||
if self.max_async_level is not None:
|
||||
self.trainer.max_async_level = self.max_async_level
|
||||
self.orchestrator.max_async_level = self.max_async_level
|
||||
@@ -293,7 +462,7 @@ class BaseRLConfig(BaseSettings):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_seq_len(self):
|
||||
# If specified, use the same seq_len for trainer and orchestrator
|
||||
"""Auto-setup shared seq_len for trainer and orchestrator."""
|
||||
if self.seq_len is not None:
|
||||
self.trainer.model.seq_len = self.seq_len
|
||||
self.orchestrator.seq_len = self.seq_len
|
||||
@@ -308,6 +477,7 @@ class BaseRLConfig(BaseSettings):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_weight_broadcast(self):
|
||||
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference."""
|
||||
if self.weight_broadcast is not None:
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
|
||||
@@ -332,6 +502,172 @@ class BaseRLConfig(BaseSettings):
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench:
|
||||
self.trainer.bench = BenchConfig()
|
||||
self.orchestrator.bench = True
|
||||
self.trainer.data.fake = FakeDataLoaderConfig(
|
||||
batch_size=self.orchestrator.batch_size,
|
||||
)
|
||||
|
||||
trainer_bench_enabled = self.trainer.bench is not None
|
||||
if trainer_bench_enabled != self.orchestrator.bench:
|
||||
raise ValueError(
|
||||
f"Trainer benchmark mode ({self.trainer.bench}) and orchestrator benchmark mode "
|
||||
f"({self.orchestrator.bench}) must match. Use the top-level bench = true to set both."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_lora(self):
|
||||
if self.trainer.model.lora is not None:
|
||||
if self.trainer.weight_broadcast.type == "nccl":
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
|
||||
if self.orchestrator.model.lora is None:
|
||||
from prime_rl.orchestrator.config import LoRAConfig
|
||||
|
||||
self.orchestrator.model.lora = LoRAConfig()
|
||||
|
||||
if (
|
||||
self.orchestrator.model.lora.rank is not None
|
||||
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
|
||||
):
|
||||
raise ValueError(
|
||||
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
|
||||
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
|
||||
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
|
||||
)
|
||||
|
||||
if (
|
||||
self.orchestrator.model.lora.alpha is not None
|
||||
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
|
||||
):
|
||||
raise ValueError(
|
||||
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
|
||||
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
|
||||
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
|
||||
)
|
||||
|
||||
if self.orchestrator.model.lora.rank is None:
|
||||
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
|
||||
|
||||
if self.orchestrator.model.lora.alpha is None:
|
||||
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
|
||||
|
||||
if self.orchestrator.model.lora.name is None:
|
||||
self.orchestrator.model.lora.name = (
|
||||
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
|
||||
)
|
||||
|
||||
if self.inference is not None:
|
||||
self.inference.enable_lora = True
|
||||
self.inference.max_lora_rank = self.trainer.model.lora.rank
|
||||
else:
|
||||
warnings.warn(
|
||||
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
|
||||
"make sure to set --enable_lora and --max-lora-rank."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_deployment(self):
|
||||
if self.deployment.type == "single_node": # single-node
|
||||
# set num_train_workers to the number of data replicas
|
||||
non_data_parallel_size = self.trainer.model.cp * self.trainer.model.tp
|
||||
if self.deployment.num_train_gpus > 1:
|
||||
self.orchestrator.num_train_workers = self.deployment.num_train_gpus // non_data_parallel_size
|
||||
|
||||
# fill up inference capacity with dp ranks
|
||||
if self.inference is not None:
|
||||
num_infer_gpus = self.deployment.num_infer_gpus
|
||||
if num_infer_gpus != self.inference.parallel.dp * self.inference.parallel.tp:
|
||||
assert num_infer_gpus % self.inference.parallel.tp == 0, (
|
||||
"Number of inference GPUs must be divisible by the tensor parallel size"
|
||||
)
|
||||
self.inference.parallel.dp = num_infer_gpus // self.inference.parallel.tp
|
||||
|
||||
elif self.deployment.type == "multi_node": # multi-node
|
||||
self.orchestrator.num_train_workers = self.deployment.num_train_nodes * self.deployment.gpus_per_node
|
||||
|
||||
if self.deployment.nodes_per_fsdp_group is not None:
|
||||
if self.deployment.num_train_nodes % self.deployment.nodes_per_fsdp_group != 0:
|
||||
raise ValueError(
|
||||
f"deployment.num_train_nodes ({self.deployment.num_train_nodes}) must be divisible by "
|
||||
f"deployment.nodes_per_fsdp_group ({self.deployment.nodes_per_fsdp_group})"
|
||||
)
|
||||
self.trainer.model.dp_replicate = (
|
||||
self.deployment.num_train_nodes // self.deployment.nodes_per_fsdp_group
|
||||
)
|
||||
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
|
||||
assert self.trainer.weight_broadcast.type == "nccl"
|
||||
self.trainer.weight_broadcast.host = "0.0.0.0"
|
||||
self.trainer.weight_broadcast.inference_world_size = (
|
||||
self.deployment.gpus_per_node * self.deployment.num_infer_nodes
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_teacher_inference(self):
|
||||
"""Auto-configure teacher inference server and orchestrator teacher_model client."""
|
||||
if self.deployment.type != "single_node":
|
||||
return self
|
||||
if self.deployment.num_teacher_gpus is None or self.deployment.num_teacher_gpus == 0:
|
||||
return self
|
||||
|
||||
import copy
|
||||
|
||||
from prime_rl.orchestrator.config import TeacherModelConfig
|
||||
|
||||
if self.teacher_inference is None:
|
||||
if self.inference is None:
|
||||
self.teacher_inference = InferenceConfig()
|
||||
else:
|
||||
self.teacher_inference = copy.deepcopy(self.inference)
|
||||
self.teacher_inference.server.port = (self.inference.server.port if self.inference else 8000) + 1
|
||||
elif self.inference is not None and self.teacher_inference.server.port == self.inference.server.port:
|
||||
raise ValueError(
|
||||
f"teacher_inference.server.port ({self.teacher_inference.server.port}) conflicts with "
|
||||
f"inference.server.port ({self.inference.server.port}). "
|
||||
"Either use different ports or let teacher_inference be auto-configured."
|
||||
)
|
||||
|
||||
tp = self.teacher_inference.parallel.tp
|
||||
num_teacher_gpus = self.deployment.num_teacher_gpus
|
||||
if num_teacher_gpus != self.teacher_inference.parallel.dp * tp:
|
||||
assert num_teacher_gpus % tp == 0, "Number of teacher GPUs must be divisible by tensor parallel size"
|
||||
assert num_teacher_gpus > 0, "num_teacher_gpus cannot be zero"
|
||||
self.teacher_inference.parallel.dp = num_teacher_gpus // tp
|
||||
|
||||
if self.orchestrator.teacher_model is None:
|
||||
self.orchestrator.teacher_model = TeacherModelConfig()
|
||||
host = self.teacher_inference.server.host or "localhost"
|
||||
port = self.teacher_inference.server.port
|
||||
self.orchestrator.teacher_model.client.base_url = [f"http://{host}:{port}/v1"]
|
||||
self.orchestrator.teacher_model.model.name = self.teacher_inference.model.name
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_slurm_template(self):
|
||||
"""Auto-setup the default single-node/multi-node SLURM template if no custom template is provided."""
|
||||
if self.slurm is not None and self.slurm.template_path is None:
|
||||
import prime_rl
|
||||
|
||||
templates_dir = Path(prime_rl.__file__).parent / "templates"
|
||||
if self.deployment.type == "single_node":
|
||||
self.slurm.template_path = templates_dir / "single_node_rl.sbatch.j2"
|
||||
else:
|
||||
self.slurm.template_path = templates_dir / "multi_node_rl.sbatch.j2"
|
||||
return self
|
||||
|
||||
### Warnings
|
||||
|
||||
@model_validator(mode="after")
|
||||
def warn_wandb_resume_id_missing(self):
|
||||
if self.trainer.ckpt is not None and self.trainer.ckpt.resume_step is not None:
|
||||
@@ -345,13 +681,3 @@ class BaseRLConfig(BaseSettings):
|
||||
"W&B run ID is not set for orchestrator even though resuming training. The current run will be created as a new run."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_output_dir(self):
|
||||
if self.output_dir is not None:
|
||||
self.trainer.output_dir = self.output_dir
|
||||
self.orchestrator.output_dir = self.output_dir / "run_default"
|
||||
|
||||
validate_shared_output_dir(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import tomli_w
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.rl_config import BaseRLConfig
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
|
||||
TEMPLATE_DIR = Path(__file__).parent
|
||||
TEMPLATE_NAME = "rl_slurm.sh.j2"
|
||||
|
||||
|
||||
class RLSLURMConfig(BaseRLConfig):
|
||||
output_dir: Path
|
||||
|
||||
job_name: str
|
||||
num_train_nodes: int
|
||||
num_infer_nodes: int
|
||||
gpus_per_node: int = Field(default=8, description="Number of GPUs per node.")
|
||||
nodes_per_fsdp_group: int | None = Field(
|
||||
default=None,
|
||||
description="Number of train nodes per FSDP island. Auto-sets trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group.",
|
||||
)
|
||||
|
||||
project_dir: Path = Field(
|
||||
default_factory=lambda: Path.cwd(),
|
||||
description="Path to the project root. Used to source .env, activate .venv, and run uv sync.",
|
||||
)
|
||||
hf_hub_offline: bool = Field(
|
||||
default=False, description="Set HF_HUB_OFFLINE=1 on training nodes to prevent downloading models at runtime."
|
||||
)
|
||||
|
||||
slurm_template: Path | None = Field(
|
||||
default=None, description="The path to the SLURM template file. If none, will use the default template."
|
||||
)
|
||||
dry_run: bool = Field(default=False, description="Only generate the SLURM script and configs without submitting.")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_dp_replicate(self):
|
||||
if self.nodes_per_fsdp_group is not None:
|
||||
if self.num_train_nodes % self.nodes_per_fsdp_group != 0:
|
||||
raise ValueError(
|
||||
f"num_train_nodes ({self.num_train_nodes}) must be divisible by nodes_per_fsdp_group ({self.nodes_per_fsdp_group})"
|
||||
)
|
||||
self.trainer.dp_replicate = self.num_train_nodes // self.nodes_per_fsdp_group
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_slurm_nccl(self):
|
||||
"""Set SLURM-specific values for NCCL weight broadcast and num_train_workers."""
|
||||
# Set num_train_workers based on SLURM topology
|
||||
self.orchestrator.num_train_workers = self.num_train_nodes * self.gpus_per_node
|
||||
|
||||
# Set NCCL-specific values if using NCCL weight broadcast
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
|
||||
# Trainer listens on all interfaces
|
||||
self.trainer.weight_broadcast.host = "0.0.0.0"
|
||||
# Compute inference world size from SLURM topology
|
||||
self.trainer.weight_broadcast.inference_world_size = self.gpus_per_node * self.num_infer_nodes
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_inference_config(self):
|
||||
"""Validate that inference config is provided when num_infer_nodes > 0."""
|
||||
if self.num_infer_nodes > 0 and self.inference is None:
|
||||
raise ValueError(
|
||||
f"inference config is required when num_infer_nodes > 0 (got {self.num_infer_nodes}). "
|
||||
"The SLURM template will launch inference servers on these nodes."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
def write_subconfigs(config: RLSLURMConfig, output_dir: Path) -> None:
|
||||
"""Write resolved subconfigs to disk as TOML files."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(output_dir / "trainer.toml", "wb") as f:
|
||||
tomli_w.dump(config.trainer.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
with open(output_dir / "orchestrator.toml", "wb") as f:
|
||||
tomli_w.dump(config.orchestrator.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
if config.inference is not None:
|
||||
with open(output_dir / "inference.toml", "wb") as f:
|
||||
tomli_w.dump(config.inference.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
|
||||
def render_slurm_script(config: RLSLURMConfig, config_dir: Path) -> str:
|
||||
"""Render the SLURM script template with config values."""
|
||||
if config.slurm_template is not None:
|
||||
template_dir = config.slurm_template.parent
|
||||
template_name = config.slurm_template.name
|
||||
else:
|
||||
template_dir = TEMPLATE_DIR
|
||||
template_name = TEMPLATE_NAME
|
||||
env = Environment(loader=FileSystemLoader(template_dir), keep_trailing_newline=True)
|
||||
template = env.get_template(template_name)
|
||||
return template.render(
|
||||
job_name=config.job_name,
|
||||
output_dir=config.output_dir,
|
||||
orchestrator_output_dir=config.orchestrator.output_dir,
|
||||
config_dir=config_dir,
|
||||
num_train_nodes=config.num_train_nodes,
|
||||
num_infer_nodes=config.num_infer_nodes,
|
||||
project_dir=config.project_dir,
|
||||
gpus_per_node=config.gpus_per_node,
|
||||
hf_hub_offline=config.hf_hub_offline,
|
||||
)
|
||||
|
||||
|
||||
def rl_slurm(config: RLSLURMConfig):
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = config.output_dir / "configs"
|
||||
write_subconfigs(config, config_dir)
|
||||
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
|
||||
script = render_slurm_script(config, config_dir)
|
||||
script_path = config.output_dir / "rl.sh"
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
slurm_log_dir = config.output_dir / "slurm"
|
||||
log_message = (
|
||||
f"Logs:\n"
|
||||
f" Trainer: tail -f {slurm_log_dir}/latest_train_node_rank_0.log\n"
|
||||
f" Inference: tail -f {slurm_log_dir}/latest_infer_node_rank_0.log\n"
|
||||
f" Orchestrator: tail -f {slurm_log_dir}/latest_orchestrator.log"
|
||||
)
|
||||
|
||||
if config.dry_run:
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
return
|
||||
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
|
||||
|
||||
def main():
|
||||
rl_slurm(parse_argv(RLSLURMConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,113 +0,0 @@
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import tomli_w
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.trainer.sft.config import SFTTrainerConfig
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
|
||||
TEMPLATE_DIR = Path(__file__).parent
|
||||
TEMPLATE_NAME = "sft_slurm.sh.j2"
|
||||
|
||||
|
||||
class SFTSLURMConfig(SFTTrainerConfig):
|
||||
job_name: str
|
||||
num_nodes: int = Field(default=1, description="Number of training nodes.")
|
||||
gpus_per_node: int = Field(default=8, description="Number of GPUs per node.")
|
||||
nodes_per_fsdp_group: int | None = Field(
|
||||
default=None,
|
||||
description="Number of nodes per FSDP island. Auto-sets model.dp_replicate = num_nodes / nodes_per_fsdp_group.",
|
||||
)
|
||||
|
||||
project_dir: Path = Field(
|
||||
default_factory=lambda: Path.cwd(),
|
||||
description="Path to the project root. Used to source .env, activate .venv, and run uv sync.",
|
||||
)
|
||||
hf_hub_offline: bool = Field(
|
||||
default=False, description="Set HF_HUB_OFFLINE=1 on training nodes to prevent downloading models at runtime."
|
||||
)
|
||||
|
||||
slurm_template: Path | None = Field(
|
||||
default=None, description="The path to the SLURM template file. If none, will use the default template."
|
||||
)
|
||||
dry_run: bool = Field(default=False, description="Only generate the SLURM script and configs without submitting.")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_dp_replicate(self):
|
||||
if self.nodes_per_fsdp_group is not None:
|
||||
if self.num_nodes % self.nodes_per_fsdp_group != 0:
|
||||
raise ValueError(
|
||||
f"num_nodes ({self.num_nodes}) must be divisible by nodes_per_fsdp_group ({self.nodes_per_fsdp_group})"
|
||||
)
|
||||
self.model.dp_replicate = self.num_nodes // self.nodes_per_fsdp_group
|
||||
return self
|
||||
|
||||
|
||||
def write_trainer_config(config: SFTSLURMConfig, output_dir: Path) -> None:
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
slurm_only_fields = set(SFTSLURMConfig.model_fields) - set(SFTTrainerConfig.model_fields)
|
||||
trainer_data = config.model_dump(exclude_none=True, mode="json", exclude=slurm_only_fields)
|
||||
with open(output_dir / "trainer.toml", "wb") as f:
|
||||
tomli_w.dump(trainer_data, f)
|
||||
|
||||
|
||||
def render_slurm_script(config: SFTSLURMConfig, config_dir: Path) -> str:
|
||||
if config.slurm_template is not None:
|
||||
template_dir = config.slurm_template.parent
|
||||
template_name = config.slurm_template.name
|
||||
else:
|
||||
template_dir = TEMPLATE_DIR
|
||||
template_name = TEMPLATE_NAME
|
||||
env = Environment(loader=FileSystemLoader(template_dir), keep_trailing_newline=True)
|
||||
template = env.get_template(template_name)
|
||||
return template.render(
|
||||
job_name=config.job_name,
|
||||
output_dir=config.output_dir,
|
||||
config_dir=config_dir,
|
||||
num_nodes=config.num_nodes,
|
||||
project_dir=config.project_dir,
|
||||
gpus_per_node=config.gpus_per_node,
|
||||
hf_hub_offline=config.hf_hub_offline,
|
||||
)
|
||||
|
||||
|
||||
def sft_slurm(config: SFTSLURMConfig):
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = config.output_dir / "configs"
|
||||
write_trainer_config(config, config_dir)
|
||||
|
||||
logger.info(f"Wrote trainer config to {config_dir}")
|
||||
|
||||
script = render_slurm_script(config, config_dir)
|
||||
script_path = config.output_dir / "sft.sh"
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
log_message = f"Logs:\n Trainer: tail -f {config.output_dir}/slurm/latest_train_node_rank_0.log"
|
||||
|
||||
if config.dry_run:
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
return
|
||||
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
|
||||
|
||||
def main():
|
||||
sft_slurm(parse_argv(SFTSLURMConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+19
-23
@@ -4,10 +4,10 @@
|
||||
#SBATCH --nodes={{ num_train_nodes + num_infer_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --partition=cluster
|
||||
#SBATCH --exclusive # Get the ENTIRE node exclusively
|
||||
#SBATCH --output=/shared/logs/job_%j.log
|
||||
#SBATCH --error=/shared/logs/job_%j.log
|
||||
#SBATCH --partition={{ partition }}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
|
||||
# Configs
|
||||
export NUM_TRAIN_NODES={{ num_train_nodes }}
|
||||
@@ -28,7 +28,6 @@ rm -rf $OUTPUT_DIR/run_*/rollouts
|
||||
rm -rf $OUTPUT_DIR/run_*/broadcasts
|
||||
rm -rf $OUTPUT_DIR/rollouts
|
||||
|
||||
|
||||
# General
|
||||
export CUDA_DEVICE_ORDER=PCI_BUS_ID
|
||||
export PYTHONUNBUFFERED=1
|
||||
@@ -58,22 +57,19 @@ export MASTER_PORT=29500
|
||||
echo "MASTER_ADDR=${MASTER_ADDR}"
|
||||
echo "MASTER_PORT=${MASTER_PORT}"
|
||||
|
||||
|
||||
# Install environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
|
||||
# Install environment as local package
|
||||
cd $PROJECT_DIR && uv sync --all-extras
|
||||
|
||||
# Setup environment
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
uv sync --all-extras
|
||||
|
||||
# Run RL
|
||||
srun bash -c '
|
||||
# Setup environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
|
||||
# Disable sync to avoid conflicts with lockfile
|
||||
# Source environment
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
# Do not sync to avoid conflicts with lockfile
|
||||
|
||||
# Higher ulimit
|
||||
ulimit -n 65536
|
||||
@@ -84,14 +80,14 @@ srun bash -c '
|
||||
export NCCL_IB_HCA=$IB_HCA
|
||||
|
||||
if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
# This is required for vLLM graph compile to work
|
||||
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:False"
|
||||
INFER_NODE_RANK=$SLURM_PROCID
|
||||
export VLLM_WORKER_MULTIPROC_METHOD=spawn
|
||||
|
||||
uv run inference \
|
||||
@ $CONFIG_DIR/inference.toml \
|
||||
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${INFER_NODE_RANK}_infer_node_rank_${INFER_NODE_RANK}.log
|
||||
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_infer_node_rank_${INFER_NODE_RANK}.log
|
||||
|
||||
else
|
||||
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
|
||||
|
||||
@@ -103,13 +99,13 @@ else
|
||||
2>&1 | tee $OUTPUT_DIR/slurm/latest_orchestrator.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_orchestrator.log & disown
|
||||
fi
|
||||
|
||||
export HF_HUB_OFFLINE={{ 1 if hf_hub_offline else 0 }}
|
||||
|
||||
export HF_HUB_OFFLINE=1
|
||||
|
||||
# This is required for compilation to work correctly
|
||||
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
|
||||
|
||||
echo $HOSTNAMES | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
|
||||
echo $HOSTNAMES | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
|
||||
|
||||
uv run torchrun \
|
||||
--nnodes=$NUM_TRAIN_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
+4
-4
@@ -4,10 +4,10 @@
|
||||
#SBATCH --nodes={{ num_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --partition=cluster
|
||||
#SBATCH --partition={{ partition }}
|
||||
#SBATCH --exclusive # Get the ENTIRE node exclusively
|
||||
#SBATCH --output=/shared/logs/job_%j.log
|
||||
#SBATCH --error=/shared/logs/job_%j.log
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
|
||||
# Configs
|
||||
export NUM_NODES={{ num_nodes }}
|
||||
@@ -57,7 +57,7 @@ srun bash -c '
|
||||
|
||||
TRAIN_NODE_RANK=$SLURM_PROCID
|
||||
|
||||
export HF_HUB_OFFLINE={{ 1 if hf_hub_offline else 0 }}
|
||||
export HF_HUB_OFFLINE=1
|
||||
|
||||
# This is required for compilation to work correctly
|
||||
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/bash
|
||||
|
||||
#SBATCH --job-name={{ job_name }}
|
||||
#SBATCH --nodes=1
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --partition={{ partition }}
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
|
||||
# Setup environment
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
uv sync --all-extras
|
||||
|
||||
uv run rl @ {{ config_path }}
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/bash
|
||||
|
||||
#SBATCH --job-name={{ job_name }}
|
||||
#SBATCH --nodes=1
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --partition={{ partition }}
|
||||
#SBATCH --output={{ output_dir }}/job_%j.log
|
||||
#SBATCH --error={{ output_dir }}/job_%j.log
|
||||
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
|
||||
# Setup environment
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
uv sync --all-extras
|
||||
|
||||
uv run sft @ {{ config_path }}
|
||||
@@ -465,6 +465,32 @@ 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."""
|
||||
|
||||
|
||||
@@ -189,6 +189,19 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
if self._flash_attn_version == 4:
|
||||
self._flash_attn_call = torch._dynamo.disable(self.func)
|
||||
|
||||
def _compute_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens, max_seqlen):
|
||||
"""Run the flash attention kernel. q/k/v are [total_tokens, heads, dim]."""
|
||||
args = [q, k, v, cu_seqlens, cu_seqlens]
|
||||
if self._flash_attn_version != 4:
|
||||
args.extend([max_seqlen, max_seqlen])
|
||||
kwargs: dict = {"causal": True}
|
||||
if self.sliding_window is not None:
|
||||
kwargs["window_size"] = (self.sliding_window - 1, 0)
|
||||
out = self._flash_attn_call(*args, **kwargs)
|
||||
if isinstance(out, tuple):
|
||||
out = out[0]
|
||||
return out
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -209,7 +222,6 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
if self.is_local_attention:
|
||||
# apply_rotary_pos_emb expects [batch, heads, seq, dim]
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
cos, sin = position_embeddings
|
||||
@@ -217,18 +229,7 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
|
||||
# Flash attention varlen expects [total_tokens, heads, dim]
|
||||
args = [query_states[0], key_states[0], value_states[0], cu_seqlens, cu_seqlens]
|
||||
if self._flash_attn_version != 4:
|
||||
args.extend([max_seqlen, max_seqlen])
|
||||
|
||||
kwargs: dict = {"causal": True}
|
||||
if self.sliding_window is not None:
|
||||
kwargs["window_size"] = (self.sliding_window - 1, 0)
|
||||
|
||||
out = self._flash_attn_call(*args, **kwargs)
|
||||
if isinstance(out, tuple):
|
||||
out = out[0]
|
||||
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
|
||||
attn_output = out.contiguous().view(*input_shape, -1)
|
||||
attn_output = attn_output * torch.sigmoid(gate_states)
|
||||
|
||||
@@ -91,6 +91,20 @@ class FlashAttention(nn.Module):
|
||||
if self._flash_attn_version == 4:
|
||||
self._flash_attn_call = torch._dynamo.disable(self.func)
|
||||
|
||||
def _compute_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens, max_seqlen):
|
||||
"""Run the flash attention kernel. q/k/v are [total_tokens, heads, dim]."""
|
||||
args = [q, k, v, cu_seqlens, cu_seqlens]
|
||||
if self._flash_attn_version != 4:
|
||||
args.extend([max_seqlen, max_seqlen])
|
||||
kwargs: dict = {"causal": True}
|
||||
sliding_window = getattr(self, "sliding_window", None)
|
||||
if sliding_window is not None:
|
||||
kwargs["window_size"] = (sliding_window - 1, 0)
|
||||
out = self._flash_attn_call(*args, **kwargs)
|
||||
if isinstance(out, tuple):
|
||||
out = out[0]
|
||||
return out
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -129,22 +143,7 @@ class FlashAttention(nn.Module):
|
||||
key_states = key_states.transpose(1, 2)
|
||||
value_states = value_states.transpose(1, 2)
|
||||
|
||||
args = [
|
||||
query_states[0],
|
||||
key_states[0],
|
||||
value_states[0],
|
||||
cu_seqlens,
|
||||
cu_seqlens,
|
||||
]
|
||||
if self._flash_attn_version != 4:
|
||||
args.extend([max_seqlen, max_seqlen])
|
||||
|
||||
out = self._flash_attn_call(
|
||||
*args,
|
||||
causal=True,
|
||||
)
|
||||
if isinstance(out, tuple):
|
||||
out = out[0]
|
||||
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
|
||||
out = out.contiguous()
|
||||
attn_output = out.view(1, out.shape[0], -1)
|
||||
@@ -242,11 +241,12 @@ ATTN_IMPL2CLASS = {
|
||||
}
|
||||
|
||||
|
||||
def substitute_prime_rl_flash_attn(
|
||||
def substitute_ring_attn(
|
||||
process_group: torch.distributed.ProcessGroup,
|
||||
heads_k_stride: int,
|
||||
attn_impl: str = "flash_attention_2",
|
||||
) -> None:
|
||||
"""Patch _compute_attention on FlashAttention (and AfmoeFlashAttention) to use ring attention."""
|
||||
from ring_flash_attn import llama3_flash_attn_varlen_func
|
||||
|
||||
from .ring_attn import ring_fa3_varlen_func
|
||||
@@ -254,72 +254,34 @@ def substitute_prime_rl_flash_attn(
|
||||
use_fa3 = attn_impl == "flash_attention_3"
|
||||
ring_func = ring_fa3_varlen_func if use_fa3 else llama3_flash_attn_varlen_func
|
||||
|
||||
class RingFlashAttention(FlashAttention):
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
def _ring_compute_attention(self, q, k, v, cu_seqlens, max_seqlen):
|
||||
from ring_flash_attn.adapters.hf_adapter import DATA_PARAMS
|
||||
|
||||
query_states = self.q_proj(hidden_states)
|
||||
key_states = self.k_proj(hidden_states)
|
||||
value_states = self.v_proj(hidden_states)
|
||||
window_size = (-1, -1)
|
||||
sliding_window = getattr(self, "sliding_window", None)
|
||||
if sliding_window is not None:
|
||||
window_size = (sliding_window - 1, 0)
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_layer":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
out = ring_func(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
cu_seqlens_q=DATA_PARAMS["cu_seqlens_q"],
|
||||
cu_seqlens_k=DATA_PARAMS["cu_seqlens_k"],
|
||||
max_seqlen_q=DATA_PARAMS["max_seqlen_q"],
|
||||
max_seqlen_k=DATA_PARAMS["max_seqlen_k"],
|
||||
local_k_slice=DATA_PARAMS["local_k_slice"],
|
||||
causal=True,
|
||||
window_size=window_size,
|
||||
group=process_group,
|
||||
heads_k_stride=heads_k_stride,
|
||||
)
|
||||
if isinstance(out, tuple):
|
||||
out = out[0]
|
||||
return out
|
||||
|
||||
query_states = query_states.view(hidden_shape)
|
||||
key_states = key_states.view(hidden_shape)
|
||||
value_states = value_states.view(hidden_shape)
|
||||
FlashAttention._compute_attention = _ring_compute_attention
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_head":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
|
||||
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
value_states = value_states.transpose(1, 2)
|
||||
|
||||
cos, sin = position_embeddings
|
||||
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
||||
|
||||
from ring_flash_attn.adapters.hf_adapter import DATA_PARAMS
|
||||
|
||||
cu_seqlens_q = DATA_PARAMS["cu_seqlens_q"]
|
||||
cu_seqlens_k = DATA_PARAMS["cu_seqlens_k"]
|
||||
max_seqlen_q = DATA_PARAMS["max_seqlen_q"]
|
||||
max_seqlen_k = DATA_PARAMS["max_seqlen_k"]
|
||||
local_k_slice = DATA_PARAMS["local_k_slice"]
|
||||
|
||||
# TODO: Can we optimize the rotary application instead of double transpose?
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
value_states = value_states.transpose(1, 2)
|
||||
out = ring_func(
|
||||
query_states[0],
|
||||
key_states[0],
|
||||
value_states[0],
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
local_k_slice=local_k_slice,
|
||||
causal=True,
|
||||
group=process_group,
|
||||
heads_k_stride=heads_k_stride,
|
||||
)
|
||||
if isinstance(out, tuple):
|
||||
out = out[0]
|
||||
out = out.contiguous()
|
||||
attn_output = out.view(1, out.shape[0], -1)
|
||||
attn_weights = None
|
||||
|
||||
attn_output = self.o_proj(attn_output)
|
||||
return attn_output, attn_weights
|
||||
|
||||
FlashAttention.forward = RingFlashAttention.forward
|
||||
AfmoeFlashAttention._compute_attention = _ring_compute_attention
|
||||
|
||||
@@ -15,6 +15,7 @@ def _fa3_varlen_forward(
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
from flash_attn_interface import _flash_attn_forward
|
||||
|
||||
@@ -32,6 +33,8 @@ def _fa3_varlen_forward(
|
||||
"causal": causal,
|
||||
}
|
||||
)
|
||||
if "window_size" in params:
|
||||
params["window_size"] = window_size
|
||||
out, lse, _, _ = _flash_attn_forward(**params)
|
||||
return out, lse
|
||||
|
||||
@@ -52,6 +55,7 @@ def _fa3_varlen_backward(
|
||||
dv: torch.Tensor,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
) -> None:
|
||||
from flash_attn_interface import _flash_attn_backward
|
||||
|
||||
@@ -75,6 +79,8 @@ def _fa3_varlen_backward(
|
||||
"causal": causal,
|
||||
}
|
||||
)
|
||||
if "window_size" in params:
|
||||
params["window_size"] = window_size
|
||||
_flash_attn_backward(**params)
|
||||
|
||||
|
||||
@@ -100,6 +106,8 @@ class _RingFA3Varlen(torch.autograd.Function):
|
||||
heads_k_stride: int,
|
||||
causal: bool,
|
||||
group_name: str,
|
||||
window_size_left: int = -1,
|
||||
window_size_right: int = -1,
|
||||
) -> torch.Tensor:
|
||||
group = dist.group.WORLD
|
||||
for pg in dist.distributed_c10d._world.pg_map:
|
||||
@@ -108,6 +116,7 @@ class _RingFA3Varlen(torch.autograd.Function):
|
||||
break
|
||||
|
||||
local_k_slice = slice(local_k_slice_start, local_k_slice_stop)
|
||||
window_size = (window_size_left, window_size_right)
|
||||
softmax_scale = q.shape[-1] ** (-0.5)
|
||||
out_list = []
|
||||
lse_list = []
|
||||
@@ -146,6 +155,7 @@ class _RingFA3Varlen(torch.autograd.Function):
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=causal,
|
||||
window_size=window_size,
|
||||
)
|
||||
out_list.append(out_i)
|
||||
lse_list.append(lse_i)
|
||||
@@ -161,6 +171,7 @@ class _RingFA3Varlen(torch.autograd.Function):
|
||||
ctx.heads_k_stride = heads_k_stride
|
||||
ctx.causal = causal
|
||||
ctx.group_name = group_name
|
||||
ctx.window_size = window_size
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
@@ -234,6 +245,7 @@ class _RingFA3Varlen(torch.autograd.Function):
|
||||
dv=dv_i,
|
||||
softmax_scale=ctx.softmax_scale,
|
||||
causal=causal,
|
||||
window_size=ctx.window_size,
|
||||
)
|
||||
|
||||
if heads_k_stride != nheads_k:
|
||||
@@ -250,8 +262,9 @@ class _RingFA3Varlen(torch.autograd.Function):
|
||||
dv[:, i : i + heads_k_stride] = dv_i
|
||||
|
||||
# Grads for: q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k,
|
||||
# local_k_slice_start, local_k_slice_stop, heads_k_stride, causal, group_name
|
||||
return dq, dk, dv, None, None, None, None, None, None, None, None, None
|
||||
# local_k_slice_start, local_k_slice_stop, heads_k_stride, causal, group_name,
|
||||
# window_size_left, window_size_right
|
||||
return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None
|
||||
|
||||
|
||||
def ring_fa3_varlen_func(
|
||||
@@ -266,6 +279,7 @@ def ring_fa3_varlen_func(
|
||||
causal: bool,
|
||||
heads_k_stride: int,
|
||||
group: dist.ProcessGroup,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
) -> torch.Tensor:
|
||||
return _RingFA3Varlen.apply(
|
||||
q,
|
||||
@@ -280,4 +294,6 @@ def ring_fa3_varlen_func(
|
||||
heads_k_stride,
|
||||
causal,
|
||||
group.group_name,
|
||||
window_size[0],
|
||||
window_size[1],
|
||||
)
|
||||
|
||||
@@ -5,7 +5,7 @@ from datetime import timedelta
|
||||
# Import environment before any other imports
|
||||
# ruff: noqa: I001
|
||||
|
||||
from prime_rl.trainer.models.layers.attn import substitute_prime_rl_flash_attn
|
||||
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
|
||||
from prime_rl.trainer.rl.broadcast import setup_weight_broadcast
|
||||
from prime_rl.utils.act_offloading import maybe_activation_offloading
|
||||
import torch
|
||||
@@ -172,7 +172,7 @@ def train(config: RLTrainerConfig):
|
||||
|
||||
if parallel_dims.cp_enabled:
|
||||
substitute_hf_flash_attn(parallel_dims.world_mesh["cp"].get_group(), heads_k_stride=1)
|
||||
substitute_prime_rl_flash_attn(
|
||||
substitute_ring_attn(
|
||||
parallel_dims.world_mesh["cp"].get_group(),
|
||||
heads_k_stride=1,
|
||||
attn_impl=config.model.attn,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from prime_rl.trainer.config import (
|
||||
AdamWConfig,
|
||||
@@ -11,6 +11,7 @@ from prime_rl.trainer.config import (
|
||||
ModelConfig,
|
||||
OptimizerConfigType,
|
||||
SchedulerConfigType,
|
||||
SlurmConfig,
|
||||
TokenizerConfig,
|
||||
)
|
||||
from prime_rl.utils.config import HeartbeatConfig, LogConfig, WandbConfig
|
||||
@@ -104,9 +105,59 @@ class SFTDataConfig(BaseDataConfig):
|
||||
DataConfigType: TypeAlias = FakeDataConfig | SFTDataConfig
|
||||
|
||||
|
||||
class BaseDeploymentConfig(BaseModel):
|
||||
"""Base deployment config for SFT."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
|
||||
|
||||
|
||||
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
"""Configures a single-node SFT deployment."""
|
||||
|
||||
type: Literal["single_node"] = "single_node"
|
||||
|
||||
num_gpus: Annotated[int, Field(description="Number of GPUs.")] = 1
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_gpu_count(self):
|
||||
if self.num_gpus > self.gpus_per_node:
|
||||
raise ValueError(f"num_gpus ({self.num_gpus}) exceeds gpus_per_node ({self.gpus_per_node}).")
|
||||
return self
|
||||
|
||||
|
||||
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
"""Configures a multi-node SFT deployment."""
|
||||
|
||||
type: Literal["multi_node"] = "multi_node"
|
||||
|
||||
num_nodes: Annotated[int, Field(description="Number of training nodes.")] = 2
|
||||
|
||||
nodes_per_fsdp_group: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="Number of nodes per FSDP island. Auto-sets model.dp_replicate = num_nodes / nodes_per_fsdp_group."
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
SFTDeploymentConfigType: TypeAlias = SingleNodeDeploymentConfig | MultiNodeDeploymentConfig
|
||||
|
||||
|
||||
class SFTTrainerConfig(BaseSettings):
|
||||
"""Configures the SFT trainer"""
|
||||
|
||||
slurm: Annotated[
|
||||
SlurmConfig | None,
|
||||
Field(
|
||||
description="SLURM configuration. If set, the run will be submitted as a SLURM job instead of running locally.",
|
||||
exclude=True,
|
||||
),
|
||||
] = None
|
||||
|
||||
deployment: Annotated[SFTDeploymentConfigType, Field(discriminator="type")] = SingleNodeDeploymentConfig()
|
||||
|
||||
# The model configuration
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
@@ -169,12 +220,36 @@ class SFTTrainerConfig(BaseSettings):
|
||||
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
|
||||
] = None
|
||||
|
||||
### Pre-validation normalization
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def normalize_deployment(cls, data):
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
deployment = data.get("deployment")
|
||||
if isinstance(deployment, dict) and deployment.get("type") == "multi_node":
|
||||
for key in ("num_gpus",):
|
||||
deployment.pop(key, None)
|
||||
return data
|
||||
|
||||
### Validate configs (e.g. raise for unsupported (combinations of) configs)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench is not None:
|
||||
self.max_steps = 4 # 1 Warmup + 3 Benchmark
|
||||
if self.ckpt: # Do not checkpoint
|
||||
self.ckpt = None
|
||||
def validate_deployment(self):
|
||||
if self.deployment.type == "multi_node" and self.slurm is None:
|
||||
raise ValueError("Must use SLURM for multi-node deployment.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_slurm_output_dir(self):
|
||||
if self.slurm is None:
|
||||
return self
|
||||
if self.output_dir == Path("outputs"):
|
||||
raise ValueError(
|
||||
"output_dir must be explicitly set when using SLURM (not the default 'outputs'). "
|
||||
"Set output_dir to a unique experiment path, e.g. '/shared/experiments/my-sft-run'."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -230,14 +305,6 @@ class SFTTrainerConfig(BaseSettings):
|
||||
raise ValueError("Muon optimizer does not support FSDP CPU offload")
|
||||
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 validate_and_disable_chunked_loss(self):
|
||||
if isinstance(self.model.fused_lm_head_chunk_size, int):
|
||||
@@ -254,3 +321,45 @@ class SFTTrainerConfig(BaseSettings):
|
||||
raise ValueError("EP is only supported with the custom implementation or auto mode")
|
||||
|
||||
return self
|
||||
|
||||
### Auto-setup and validate shared configs
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench is not None:
|
||||
self.max_steps = 4 # 1 Warmup + 3 Benchmark
|
||||
if self.ckpt: # Do not checkpoint
|
||||
self.ckpt = None
|
||||
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_deployment(self):
|
||||
if self.deployment.type == "multi_node":
|
||||
if self.deployment.nodes_per_fsdp_group is not None:
|
||||
if self.deployment.num_nodes % self.deployment.nodes_per_fsdp_group != 0:
|
||||
raise ValueError(
|
||||
f"deployment.num_nodes ({self.deployment.num_nodes}) must be divisible by "
|
||||
f"deployment.nodes_per_fsdp_group ({self.deployment.nodes_per_fsdp_group})"
|
||||
)
|
||||
self.model.dp_replicate = self.deployment.num_nodes // self.deployment.nodes_per_fsdp_group
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_slurm_template(self):
|
||||
if self.slurm is not None and self.slurm.template_path is None:
|
||||
import prime_rl
|
||||
|
||||
templates_dir = Path(prime_rl.__file__).parent / "templates"
|
||||
if self.deployment.type == "single_node":
|
||||
self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2"
|
||||
else:
|
||||
self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2"
|
||||
return self
|
||||
|
||||
@@ -8,7 +8,7 @@ from torch.nn import CrossEntropyLoss
|
||||
# Import environment before any other imports
|
||||
# ruff: noqa: I001
|
||||
|
||||
from prime_rl.trainer.models.layers.attn import substitute_prime_rl_flash_attn
|
||||
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
|
||||
from prime_rl.utils.act_offloading import maybe_activation_offloading
|
||||
import torch
|
||||
from torch.profiler import profile, ProfilerActivity, record_function
|
||||
@@ -94,7 +94,7 @@ def train(config: SFTTrainerConfig):
|
||||
if parallel_dims.cp_enabled:
|
||||
assert config.data.seq_len % parallel_dims.cp == 0, "Sequence length must be divisible by CP degree"
|
||||
substitute_hf_flash_attn(parallel_dims.world_mesh["cp"].get_group(), heads_k_stride=1)
|
||||
substitute_prime_rl_flash_attn(
|
||||
substitute_ring_attn(
|
||||
parallel_dims.world_mesh["cp"].get_group(),
|
||||
heads_k_stride=1,
|
||||
attn_impl=config.model.attn,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import subprocess
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
|
||||
|
||||
def cleanup_threads(threads: list[Thread]):
|
||||
"""Cleanup a list of threads"""
|
||||
for thread in threads:
|
||||
thread.join(timeout=5)
|
||||
|
||||
|
||||
def cleanup_processes(processes: list[Popen]):
|
||||
"""Cleanup a list of subprocesses"""
|
||||
for process in processes:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=60)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
|
||||
|
||||
def monitor_process(process: Popen, stop_event: Event, error_queue: list, process_name: str):
|
||||
"""Monitor a subprocess and signal errors via shared queue."""
|
||||
process.wait()
|
||||
|
||||
if process.returncode != 0:
|
||||
err_msg = f"{process_name.capitalize()} failed with exit code {process.returncode}"
|
||||
if process.stderr:
|
||||
err_msg += f"\n{process.stderr.read().decode('utf-8')}"
|
||||
error_queue.append(RuntimeError(err_msg))
|
||||
stop_event.set()
|
||||
@@ -6,9 +6,7 @@ from pydantic import ValidationError
|
||||
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
from prime_rl.rl import RLConfig
|
||||
from prime_rl.slurm.rl import RLSLURMConfig
|
||||
from prime_rl.slurm.sft import SFTSLURMConfig
|
||||
from prime_rl.rl_config import RLConfig
|
||||
from prime_rl.trainer.rl.config import RLTrainerConfig
|
||||
from prime_rl.trainer.sft.config import SFTTrainerConfig
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
@@ -20,8 +18,6 @@ CONFIG_CLASSES = [
|
||||
SFTTrainerConfig,
|
||||
OrchestratorConfig,
|
||||
InferenceConfig,
|
||||
RLSLURMConfig,
|
||||
SFTSLURMConfig,
|
||||
]
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user