Compare commits
146
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b92c2128dd | ||
|
|
c2b99e69ce | ||
|
|
ecd0809280 | ||
|
|
381733e0cf | ||
|
|
27c35b1ce1 | ||
|
|
b7afd84024 | ||
|
|
e7adec38f0 | ||
|
|
4f612601f6 | ||
|
|
a25b3e7a18 | ||
|
|
692dfc8a4b | ||
|
|
2ddb1c8199 | ||
|
|
53a8b45660 | ||
|
|
c2dfc338c3 | ||
|
|
f414d9ae49 | ||
|
|
60f01a0468 | ||
|
|
d803065204 | ||
|
|
19511dc2b0 | ||
|
|
7ef29a7660 | ||
|
|
7e853195ea | ||
|
|
9c25ce2ca1 | ||
|
|
3dd48be5bf | ||
|
|
40da51a235 | ||
|
|
bb4c23b122 | ||
|
|
1bc1021a0f | ||
|
|
4875c101c2 | ||
|
|
fc6fd48fae | ||
|
|
d5c7240676 | ||
|
|
3dcff28e02 | ||
|
|
58f4b37d5b | ||
|
|
47f6bb8307 | ||
|
|
1f6de8fff4 | ||
|
|
c1bbbf9231 | ||
|
|
f399e2664c | ||
|
|
0f236d322c | ||
|
|
f7192e15f3 | ||
|
|
bd110a10e9 | ||
|
|
d1c36af4b3 | ||
|
|
eba667d9c0 | ||
|
|
7e06730200 | ||
|
|
6c55a9aab2 | ||
|
|
33d266b41f | ||
|
|
8fa0dde0be | ||
|
|
76946689cf | ||
|
|
67de232773 | ||
|
|
cab621fc5d | ||
|
|
275914349a | ||
|
|
9b2fb9afbe | ||
|
|
be9f9f8d83 | ||
|
|
51fcbae998 | ||
|
|
74a13f0ee2 | ||
|
|
051c8bac23 | ||
|
|
a7db21723e | ||
|
|
00a4752a49 | ||
|
|
fa95af173c | ||
|
|
51bd1ad5d4 | ||
|
|
93cd1fa37f | ||
|
|
00778b5a22 | ||
|
|
447cafedea | ||
|
|
aa432f2c1f | ||
|
|
7994d6c1aa | ||
|
|
3639f0ab4f | ||
|
|
8eecadc943 | ||
|
|
bcb504bd4f | ||
|
|
2041d93132 | ||
|
|
46f26ce195 | ||
|
|
e113981a4e | ||
|
|
deecddc4af | ||
|
|
26fd0e34be | ||
|
|
710c9b32e9 | ||
|
|
4d91edc9e6 | ||
|
|
2c5c69da8b | ||
|
|
5f0dcc8a1b | ||
|
|
8ea7bd4834 | ||
|
|
302ef6d084 | ||
|
|
89a5343780 | ||
|
|
22f0ae7640 | ||
|
|
f0746566e9 | ||
|
|
99c02bba6c | ||
|
|
ebb5a1cac2 | ||
|
|
d19ce7919f | ||
|
|
e2175c11ae | ||
|
|
d4bfa08977 | ||
|
|
599cea81c1 | ||
|
|
c344a8a3c6 | ||
|
|
892c895b83 | ||
|
|
94984b9790 | ||
|
|
15fc324d1b | ||
|
|
868ba03d9b | ||
|
|
aa33d910a4 | ||
|
|
ac7ac62115 | ||
|
|
99058e9e37 | ||
|
|
fe32efbee1 | ||
|
|
6a97762b5c | ||
|
|
8451067db7 | ||
|
|
ea161dd743 | ||
|
|
9104df43c6 | ||
|
|
02bdca2e41 | ||
|
|
bf71516c91 | ||
|
|
aacc466401 | ||
|
|
68e443b833 | ||
|
|
6f6fa002a5 | ||
|
|
732cbde83c | ||
|
|
09a6875f11 | ||
|
|
f00925c006 | ||
|
|
5a6ab4a968 | ||
|
|
5ae5079478 | ||
|
|
753a728e8a | ||
|
|
df50bd2eb1 | ||
|
|
982a7756ec | ||
|
|
35671879fb | ||
|
|
1ea7a8d3b5 | ||
|
|
f655f71c33 | ||
|
|
bc77fa0692 | ||
|
|
7104dbdb5d | ||
|
|
3d9aa90a24 | ||
|
|
2da1e4ac5a | ||
|
|
7d8da4cbcc | ||
|
|
7036a15119 | ||
|
|
aef4a600f9 | ||
|
|
a3a307e70c | ||
|
|
83c21ddac5 | ||
|
|
5f2dc0fe42 | ||
|
|
5b15e54e88 | ||
|
|
4825d76e75 | ||
|
|
668579aaf0 | ||
|
|
ce55c150e7 | ||
|
|
75355f497b | ||
|
|
1c559feb25 | ||
|
|
cae5532f5d | ||
|
|
8136f13c55 | ||
|
|
cc59d7bedf | ||
|
|
cfed378624 | ||
|
|
f9b7856eec | ||
|
|
82652c7393 | ||
|
|
4b0ecdb223 | ||
|
|
1826b18927 | ||
|
|
db5092914d | ||
|
|
5bd9809399 | ||
|
|
448f8c09ad | ||
|
|
4076a0e457 | ||
|
|
ad8d775fc3 | ||
|
|
c2027a79d0 | ||
|
|
944163ac68 | ||
|
|
1e7561668d | ||
|
|
fd78f21f79 | ||
|
|
7eade4f7e1 |
@@ -12,6 +12,39 @@ jobs:
|
||||
trigger-docs-sync:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Validate mint.json pages exist
|
||||
run: |
|
||||
missing=()
|
||||
pages=$(python3 -c "
|
||||
import json, sys
|
||||
data = json.load(open('docs/mint.json'))
|
||||
pages = []
|
||||
def collect(obj):
|
||||
if isinstance(obj, list):
|
||||
for item in obj: collect(item)
|
||||
elif isinstance(obj, dict):
|
||||
if 'pages' in obj: collect(obj['pages'])
|
||||
if 'groups' in obj: collect(obj['groups'])
|
||||
elif isinstance(obj, str):
|
||||
pages.append(obj)
|
||||
collect(data.get('navigation', []))
|
||||
print('\n'.join(pages))
|
||||
")
|
||||
while IFS= read -r page; do
|
||||
[ -z "$page" ] && continue
|
||||
if [ ! -f "docs/${page}.md" ] && [ ! -f "docs/${page}.mdx" ]; then
|
||||
missing+=("${page}")
|
||||
fi
|
||||
done <<< "$pages"
|
||||
if [ ${#missing[@]} -gt 0 ]; then
|
||||
echo "ERROR: The following pages listed in mint.json do not exist in docs/:"
|
||||
printf ' - %s\n' "${missing[@]}"
|
||||
exit 1
|
||||
fi
|
||||
echo "All mint.json pages verified."
|
||||
|
||||
- name: Trigger public-docs workflow
|
||||
uses: peter-evans/repository-dispatch@v3
|
||||
with:
|
||||
|
||||
+56
-1
@@ -2,6 +2,18 @@
|
||||
|
||||
Documenting changes which affect configuration usage patterns (added/moved/removed/renamed fields, notable logic changes).
|
||||
|
||||
- **`[model.vlm]` (NEW — replaces auto-detection)**: VLM mode is now opt-in via a `[model.vlm]` sub-config with required `vision_encoder_attr` and `language_model_attr` fields. There is no auto-detection — if you train a VLM, you must add `[model.vlm]`. Existing multimodal configs need the new section. See `docs/multimodal.md` for the table of known model attrs. (2026-03-24)
|
||||
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models, RL only)**: VLM dtype validation now only applies to RL training (`TrainerConfig`), not SFT. VLM models used with `sft` no longer require `optimization_dtype='bfloat16'` / `reduce_dtype='bfloat16'`. RL training still enforces both to match vLLM inference. (2026-03-24)
|
||||
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models)**: Added validation that VLM models must use `optimization_dtype='bfloat16'` and `reduce_dtype='bfloat16'` to match vLLM inference. Previously valid configs with `float32` (the default) are now rejected for VLM model names. Set both fields to `"bfloat16"` when training VLMs. (2026-03-21)
|
||||
- **`orchestrator.advantage.length_weighted_mean`**: Removed. The default advantage now always uses the plain per-problem mean baseline unless `orchestrator.advantage.length_shaping_alpha` is set. Existing configs must delete this field. (2026-03-19)
|
||||
- **`orchestrator.advantage.length_shaping_alpha`**: Added Group Relative Reward Rescaling coefficient to the default advantage config. When set, applies length-based GR3 shaping during advantage computation and requires `orchestrator.buffer.online_difficulty_filtering = true` (default: `None`) (2026-03-18)
|
||||
- **`prime_monitor.log_extras.sample_ratio`**: Added ratio-based rollout sampling (0.0–1.0, default: None). When set, caps the number of rollouts logged per step to `len(rollouts) * sample_ratio`. `None` preserves current behavior (log all rollouts). Interacts with existing `interval` gate which still runs first. (2026-03-12)
|
||||
- **`client.connect_timeout`**: Added configurable TCP connect timeout for inference API requests (default: 30.0s). Previously hardcoded to 5.0s. Helps with vLLM or cluster flakiness (2026-03-11)
|
||||
- **`model.fused_lm_head_token_chunk_size`**: Added as the fused LM-head chunking field for the token-chunked implementation. Unlike the removed `model.fused_lm_head_chunk_size`, this chunks over flattened sequence tokens rather than vocabulary rows. `model.fused_lm_head_chunk_size` is no longer accepted; switch configs to `model.fused_lm_head_token_chunk_size` explicitly. (2026-03-09)
|
||||
- **`slurm.pre_run_command`**: Added optional shell command to run on the head node before starting the job. Useful for cleanup routines (e.g. killing stale processes, removing lock files). For all-nodes execution, wrap with `srun` in the command string (default: None) (2026-03-08)
|
||||
- **`slurm.nodelist`**, **`slurm.exclude`**, **`slurm.account`**, **`slurm.time`**: Added common SLURM scheduling options (all default: None) (2026-03-08)
|
||||
- **`orchestrator.verification.enabled`**: Added top-level rollout verification switch. `orchestrator.buffer.skip_verification` has been removed; use `verification.enabled = false` instead. When disabled, rewards are always 0 and reward-dependent buffer features (`online_difficulty_filtering`, `easy_threshold`, `hard_threshold`) must be unset (2026-03-03)
|
||||
- **`client.dp_rank_count`**: Added configuration for data-parallel inference routing. When > 1, each `client.base_url` is expanded into `dp_rank_count` logical clients and pinned via `X-data-parallel-rank` to keep multi-turn rollouts on a consistent DP rank (default: 1) (2026-03-03)
|
||||
- **`model.lora`**: Moved from `model.experimental.lora` to `model.lora` (no longer experimental) (#1440, 2025-12-16)
|
||||
- Auto-set `api_server_count=1` on inference when LoRA is enabled, because vLLM doesn't support hotloading for multiple API servers (#1422, 2025-12-17)
|
||||
- **`inference.model.rope_scaling`**: Added RoPE scaling configuration passthrough to vLLM (#1447 2025-12-17)
|
||||
@@ -61,4 +73,47 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`orchestrator.filters`**: Added orchestrator-side rollout filters for detecting degenerate generations. Supports `[[filters]] type = "gibberish"` (rare tokens at high entropy) and `[[filters]] type = "repetition"` (high-confidence token streaks). Detected rollouts get reward zeroed and completion mask cleared (2026-02-13)
|
||||
- **`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)
|
||||
- **`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)
|
||||
- **`orchestrator.token_batch_size`** and **`orchestrator.max_inflight_rollouts`**: Added token-based batching via `token_batch_size` and explicit in-flight rollout control via `max_inflight_rollouts` (2026-02-23)
|
||||
- **`orchestrator.batch_size`**: Now optional and mutually exclusive with `token_batch_size`. If neither is set, defaults to rollout mode with `batch_size=128` (2026-02-23)
|
||||
- **`inference.enable_expert_parallel`**, **`inference.all2all_backend`**, and **`inference.enable_eplb`**: Added expert-parallel inference controls passed to vLLM as `--enable-expert-parallel`, `--all2all-backend`, and `--enable-eplb` (defaults: `False`, `"allgather_reducescatter"`, `False`) (2026-02-23)
|
||||
- **`rl_slurm` / `sft_slurm` entrypoints**: Removed. SLURM submission is now handled by the unified `rl` and `sft` entrypoints. Add a `[slurm]` section to your config to submit via SLURM instead of running locally (2026-02-23)
|
||||
- **`inference_gpu_ids` / `trainer_gpu_ids` / `teacher_gpu_ids`**: Removed from `RLConfig`. Replaced by `[deployment]` section with `type = "single_node"` (fields: `num_train_gpus`, `num_infer_gpus`, `num_teacher_gpus`) or `type = "multi_node"` (fields: `num_train_nodes`, `num_infer_nodes`, `num_teacher_nodes`, `nodes_per_fsdp_group`). Default is `single_node` with 1 train GPU and 1 infer GPU (2026-02-23)
|
||||
- **`RLSLURMConfig`**: Removed. Fields `job_name`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in the unified `RLConfig` (2026-02-23)
|
||||
- **`SFTSLURMConfig`**: Removed. Fields `job_name`, `num_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in `SFTConfig` (2026-02-23)
|
||||
- **`[deployment]` (RL)**: Added deployment configuration. `type = "single_node"` auto-derives contiguous GPU assignments from `num_infer_gpus`, `num_train_gpus`, `num_teacher_gpus`. `type = "multi_node"` requires `[slurm]` and uses `num_train_nodes`, `num_infer_nodes` (2026-02-23)
|
||||
- **`[deployment]` (SFT)**: Added deployment configuration. `type = "single_node"` with `num_gpus` (default: 1). `type = "multi_node"` with `num_nodes`, `nodes_per_fsdp_group`, `hf_hub_offline` (2026-02-23)
|
||||
- **`[slurm]` (RL)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run rl` generates and submits an sbatch script instead of running locally. Template is auto-selected based on deployment type (2026-02-23)
|
||||
- **`[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)
|
||||
- **`output_dir` (RL)**: Changed from `Path | None` (default `None`) to `Path` (default `Path("outputs")`). The SLURM-specific validation that rejected the default has been removed — `output_dir` now works the same for local and SLURM runs (2026-02-24)
|
||||
- **`clean_output_dir`**: Added to `RLConfig` and `SFTConfig` (default: `False`). Training now raises `FileExistsError` when `output_dir` contains checkpoints from a previous run and not resuming. Set `clean_output_dir=true` to delete and start fresh, or set `ckpt.resume_step` to resume (2026-02-24)
|
||||
- **`clean`**: Removed from `RLConfig`. The old `clean` flag (default: `True`) silently deleted logs, rollouts, and broadcasts on every local RL run. Superseded by the explicit `clean_output_dir` flag (2026-02-24)
|
||||
- **Config consolidation**: All config modules moved into `prime_rl.configs` subpackage. `utils/config.py` + `transport/config.py` → `configs/shared.py`; `trainer/config.py` + `trainer/rl/config.py` → `configs/trainer.py`; `trainer/sft/config.py` → `configs/sft.py`; `orchestrator/config.py` → `configs/orchestrator.py`; `inference/config.py` → `configs/inference.py`; `rl_config.py` → `configs/rl.py`. Class renames: `SFTTrainerConfig` → `SFTConfig`, `RLTrainerConfig` → `TrainerConfig`. Component prefixes dropped from orchestrator and inference config classes (e.g. `OrchestratorCheckpointConfig` → `CheckpointConfig`). TypeAlias renames: dropped `Type` suffix (e.g. `LossConfigType` → `LossConfig`, `TransportConfigType` → `TransportConfig`), renamed `LossConfig` class → `DefaultLossConfig`. No TOML key changes. (2026-02-24)
|
||||
- **`trainer.enable_router_replay`**: Added flag to enable router replay. If True, will return routed experts in the batch. This is only supported if `enable_return_routed_experts=True` in the inference config or pass `--enable-return-routed-experts` to vLLM server. This is only supported for custom models. (2026-02-22)
|
||||
- **`inference.enable_return_routed_experts`**: Added flag to enable return routed experts. Passed to vLLM as `--enable-return-routed-experts` (2026-02-22)
|
||||
- **`orchestrator.oversampling_factor`**: Added rollout-only over-sampling config that resolves `max_inflight_rollouts = int(batch_size * oversampling_factor)` when `max_inflight_rollouts` is unset. Cannot be used with `token_batch_size` or together with explicit `max_inflight_rollouts` (2026-02-25)
|
||||
- **`sft.val`**: Added optional periodic SFT validation with `val/loss` and `val/num_tokens` logging. Configure via `sft.val.data` (validation dataset) and `sft.val.interval` (every N steps, default 50). Runs the full validation dataset each pass. (2026-02-26)
|
||||
- **`model.fused_lm_head_chunk_size`**: Changed default value from 2048 to 8192 for RL training (2026-02-26)
|
||||
- **`inference.data_parallel_size_local`** and **`inference.data_parallel_rpc_port`**: Added data-parallel node-local controls for vLLM, passed as `--data-parallel-size-local` and `--data-parallel-rpc-port` (defaults: `None`, `13345`) (2026-02-26)
|
||||
- **`dump_config`**: Removed from `RLConfig`. Replaced by `dry_run` (see below) (2026-02-26)
|
||||
- **`slurm.dry_run`**: Removed from `SlurmConfig`. Replaced by top-level `dry_run` (see below) (2026-02-26)
|
||||
- **`dry_run`**: Added to `RLConfig` and `SFTConfig` (default: `False`). When set, validates the config, writes resolved subconfigs to `output_dir/configs/`, and exits without starting any processes. Works the same for both local and SLURM runs (2026-02-26)
|
||||
- **Config output location**: Resolved subconfigs are now always written to `output_dir/configs/` instead of `.pydantic_config/<uuid>/`. This applies to both local and SLURM entrypoints, and for both single-node and multi-node deployments (2026-02-26)
|
||||
- **SFT config filename**: The resolved SFT trainer config is now written as `sft.toml` instead of `trainer.toml` (2026-02-26)
|
||||
- **Inference entrypoint**: Moved from `prime_rl.inference.server` to `prime_rl.entrypoints.inference`. No change to CLI usage (`uv run inference`) (2026-02-26)
|
||||
- **`[slurm]` (inference)**: Added SLURM configuration to `InferenceConfig`. When present, `uv run inference` generates and submits an sbatch script instead of running locally. Each SLURM node runs an independent vLLM replica (no cross-node parallelism) (2026-02-26)
|
||||
- **`[deployment]` (inference)**: Added deployment configuration. `type = "single_node"` (default) with `gpus_per_node`. `type = "multi_node"` with `num_nodes` and `gpus_per_node` — requires `[slurm]` (2026-02-26)
|
||||
- **`inference.output_dir`**: Added directory for SLURM logs and generated scripts (default: `"outputs"`) (2026-02-26)
|
||||
- **`inference.dry_run`**: Added flag (default: `False`). When set, validates config, writes resolved config to `output_dir/configs/`, and exits without starting inference or submitting SLURM jobs (2026-02-26)
|
||||
- **`orchestrator.teacher_rollout_model`**: Added optional external rollout model configuration. When set, rollouts are generated from this endpoint/model instead of the student inference server. Accepts a `TeacherRolloutModelConfig` with `client` and `model` sub-fields, or `None` (default: `None`) (2026-02-26)
|
||||
- **`trainer.loss.type = "sft"`**: Added SFT loss variant. Set `trainer.loss.type = "sft"` to use masked negative log-likelihood loss instead of the default RL loss (2026-02-26)
|
||||
- **`trainer.loss.type = "custom"`**: Added custom loss variant. Set `trainer.loss.type = "custom"` with `import_path` (e.g. `"my_module.my_loss"`) and optional `kwargs` to use an external loss function (2026-02-26)
|
||||
- **`trainer.loss` (default loss)**: Made IPO (DPPO-Binary TV variant ([arxiv](https://arxiv.org/pdf/2602.04879)) + Kimi-K2.5 KL ([Kimi-K2.5](https://arxiv.org/pdf/2602.02276))) the default loss. Removed `ratio_type`, `token_mask_low`, `token_mask_high`, `sequence_clip_high`, `geo_mask_low`, `geo_mask_high`, `sequence_mask_low`, `sequence_mask_high`. Added `ipo_mask_low` (default: 0.2) and `ipo_mask_high` (default: 0.2) for token-level probability-difference masking. Changed `kl_tau` default from `0.0` to `1e-3`. (2026-03-02)
|
||||
- **Metrics logging overhaul**: All orchestrator metrics now follow a `{metric}/{scope}/{stat}` naming convention where scope is `all` (global) or an env name. Per-env breakdowns are always logged (previously only when >1 env). Key renames: `reward/mean` → `reward/all/mean`, `batch/solve_none` → `solve_none/all`, `val_reward/` → `val/reward/`, `metrics/{name}` → `metrics/{env}/{name}`, `stop_condition/{sc}` → `stop_condition/all/{sc}`, `error/mean` → `error/all/mean`. New per-env metrics: `solve_none/{env}`, `solve_all/{env}`, `effective_batch_size/{env}`, `stop_condition/{env}/generation_truncated`, `stop_condition/{env}/{sc}`, `error/{env}/mean`, plus per-env breakdowns for `seq_len`, `prefill_len`, `decode_len`, `is_truncated`, `samples_per_rollout`, `num_turns`, `generation_ms`, `scoring_ms`. Removed: `reward/std`, `reward/median`, per-error-type breakdown (`error/{error_type}`). Env name `"all"` is reserved and rejected at config validation. Env name validation now strips `@version` suffixes to match runtime behavior (e.g. `math@1.0` and `math@2.0` correctly detected as duplicates). Solve stats now use `example_id` grouping instead of index arithmetic (pre-existing bug fix). (2026-03-08)
|
||||
- **`wandb.shared`** (experimental): Added shared W&B mode that logs trainer and orchestrator metrics to a single W&B run instead of two separate runs. Uses `wandb.Settings(mode="shared")` (requires wandb SDK >= 0.19.9). Enabled by default on the RL entrypoint. Disable with `--wandb.shared False`. Run ID is communicated via `WANDB_SHARED_RUN_ID` env var; process role via `WANDB_SHARED_LABEL`. Non-primary processes retry `wandb.init` up to 30 times waiting for the primary to create the run. Works with multi-node SLURM. (2026-03-18)
|
||||
- **`wandb.id`**: Removed from `WandbConfig`. Run IDs are now managed internally via env vars for shared mode. (2026-03-18)
|
||||
- **`trainer.ckpt.skip_optimizer`**: Added flag to skip loading optimizer states when resuming training. When set, only the model weights are loaded from the checkpoint. (2026-03-24)
|
||||
|
||||
+19
-4
@@ -1,7 +1,7 @@
|
||||
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
|
||||
|
||||
# Build stage
|
||||
FROM pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel AS builder
|
||||
# Build stage - multi-arch base (supports amd64 + arm64)
|
||||
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu22.04 AS builder
|
||||
LABEL maintainer="prime intellect"
|
||||
LABEL repository="prime-rl"
|
||||
|
||||
@@ -12,12 +12,22 @@ RUN echo "LC_ALL=en_US.UTF-8" >> /etc/environment
|
||||
ENV CUDA_HOME=/usr/local/cuda
|
||||
ENV PATH=$PATH:/usr/local/cuda/bin
|
||||
|
||||
# Install packages
|
||||
# Install packages (including Python 3.12 and ninja for fast CUDA kernel compilation)
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
ENV TZ=Etc/UTC
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends --force-yes \
|
||||
build-essential \
|
||||
curl \
|
||||
sudo \
|
||||
git \
|
||||
ninja-build \
|
||||
software-properties-common \
|
||||
&& add-apt-repository ppa:deadsnakes/ppa \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends python3.12 python3.12-dev python3.12-venv \
|
||||
&& ln -sf /usr/bin/python3.12 /usr/bin/python3 \
|
||||
&& ln -sf /usr/bin/python3.12 /usr/bin/python \
|
||||
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
|
||||
# Download the latest installer
|
||||
@@ -43,7 +53,12 @@ COPY examples /app/examples
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
|
||||
RUN --mount=type=cache,target=/app/.cache/uv \
|
||||
uv sync --all-extras --locked --no-dev
|
||||
uv sync --all-extras --group mamba-ssm --locked --no-dev
|
||||
|
||||
# arm64: build flash-attn from source, fix namespace conflicts, apply workarounds
|
||||
ARG TARGETARCH
|
||||
COPY scripts/docker-arm64-post-install.sh /app/scripts/docker-arm64-post-install.sh
|
||||
RUN if [ "$TARGETARCH" = "arm64" ]; then /app/scripts/docker-arm64-post-install.sh; fi
|
||||
|
||||
FROM python:3.12-slim
|
||||
|
||||
|
||||
@@ -164,8 +164,9 @@ We provide end-to-end training examples in the [`examples`](examples) directory
|
||||
2. [**Wordle**](examples/wordle/README.md): Train `Qwen3-1.7B` to play Wordle. A fun example of multi-turn SFT and RL training. Can be trained on a 2-4 H100 GPUs in a few hours. Ideal for exploring the multi-turn training capabilities of the framework.
|
||||
3. [**Alphabet Sort**](examples/alphabet_sort/README.md): Train `Qwen3-4B-Instruct-2507` to sort names alphabetically. Demonstrates multi-turn RL training via LoRA without SFT warmup. Can be trained on a single H100 GPU in just over an hour. Ideal for exploring LoRA-based training.
|
||||
4. [**Wiki Search**](examples/wiki_search/README.md): Train `Qwen3-4B-Instruct-2507` to answer trivia questions by searching through a Wikipedia. Demonstrates multi-turn with web search tool use.
|
||||
5. [**Hendrycks Sanity**](examples/hendrycks_sanity/README.md): Run a sanity check experiment on `DeepSeek-R1-Distill-Qwen-1.5B` using a filtered subset of MATH where the model already partially solves 20-80% of problems. Useful for algorithm ablations.
|
||||
|
||||
4. *More to come...*
|
||||
*More to come...*
|
||||
|
||||
## Docs
|
||||
|
||||
|
||||
+16
-16
@@ -15,34 +15,34 @@
|
||||
"cp": 1,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "a76eec30",
|
||||
"timestamp": "2026-02-01T00:37:17.504432+00:00",
|
||||
"commit_sha": "83c21ddac",
|
||||
"timestamp": "2026-02-26T02:07:06+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 276.12556480802596
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 17.08174826544651,
|
||||
"std": 0.00860887294908562,
|
||||
"min": 17.07595532741123,
|
||||
"max": 17.091640740120457
|
||||
"mean": 16.41977165630161,
|
||||
"std": 0.010586646038388221,
|
||||
"min": 16.407648988464405,
|
||||
"max": 16.42719598975201
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 2040.0423352992304,
|
||||
"std": 1.0281421434405753,
|
||||
"min": 2039.3504951752516,
|
||||
"max": 2041.2237756777045
|
||||
"mean": 1960.9836648020673,
|
||||
"std": 1.2643440104327244,
|
||||
"min": 1959.5358764831926,
|
||||
"max": 1961.8703395331793
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 63.29752009687945,
|
||||
"std": 0.1304965028229097,
|
||||
"min": 63.170207182411104,
|
||||
"max": 63.430982740130275
|
||||
"mean": 65.87,
|
||||
"std": 0.13,
|
||||
"min": 65.74,
|
||||
"max": 66.0
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 22.685546875,
|
||||
"pct": 47.72
|
||||
"gib": 31.806640625,
|
||||
"pct": 67.03
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-17
@@ -13,36 +13,36 @@
|
||||
"micro_batches": 2,
|
||||
"ep": 1,
|
||||
"cp": 1,
|
||||
"docker_image": "primeintellect/prime-rl@sha256:d3e9636af265f5ba2e56cd2555534489f5ff64e04a3f645059ca7989508de419",
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "a76eec30",
|
||||
"timestamp": "2026-01-31T01:13:40.536972+00:00",
|
||||
"commit_sha": "83c21ddac",
|
||||
"timestamp": "2026-02-26T02:07:06+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 291.91085167229176
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 16.165875888064594,
|
||||
"std": 0.010063094728313886,
|
||||
"min": 16.154265967508614,
|
||||
"max": 16.172097002189034
|
||||
"mean": 15.634260517326164,
|
||||
"std": 0.009817863071768202,
|
||||
"min": 15.622927380137481,
|
||||
"max": 15.640172924064188
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 7722.645407567771,
|
||||
"std": 4.80726889329249,
|
||||
"min": 7717.099200218126,
|
||||
"max": 7725.61731325081
|
||||
"mean": 7468.685954343421,
|
||||
"std": 4.690118598479809,
|
||||
"min": 7463.271969943842,
|
||||
"max": 7471.510386564679
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 66.21160964062437,
|
||||
"std": 0.11667723461510121,
|
||||
"min": 66.1170196281746,
|
||||
"max": 66.34198968904093
|
||||
"mean": 68.34095695288852,
|
||||
"std": 0.16054587555887065,
|
||||
"min": 68.16114284005016,
|
||||
"max": 68.46991707291454
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 14.1328125,
|
||||
"pct": 29.74
|
||||
"gib": 23.25390625,
|
||||
"pct": 49.05701678145735
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ from typing import Annotated
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from prime_rl.utils.pydantic_config import BaseSettings, parse_argv
|
||||
from prime_rl.utils.config import BaseConfig, cli
|
||||
|
||||
SHORTENED_ATTN_MAPPING = {
|
||||
"flash_attention_2": "FA2",
|
||||
@@ -23,7 +23,7 @@ SHORTENED_ATTN_MAPPING = {
|
||||
DEVICE_NAME_STRIP_WORDS = ["NVIDIA", "RTX", "80GB", "40GB"]
|
||||
|
||||
|
||||
class AggregateConfig(BaseSettings):
|
||||
class AggregateConfig(BaseConfig):
|
||||
"""Configuration for aggregating benchmark results."""
|
||||
|
||||
artifacts_dir: Annotated[Path, Field(description="Directory containing benchmark JSON artifacts")]
|
||||
@@ -197,7 +197,7 @@ def generate_markdown(
|
||||
|
||||
|
||||
def main():
|
||||
config = parse_argv(AggregateConfig)
|
||||
config = cli(AggregateConfig)
|
||||
|
||||
results = load_json_dir(config.artifacts_dir)
|
||||
print(f"Loaded {len(results)} benchmark results", file=sys.stderr)
|
||||
|
||||
@@ -19,7 +19,7 @@ from typing import Annotated, Literal
|
||||
import torch
|
||||
from pydantic import Field
|
||||
|
||||
from prime_rl.utils.pydantic_config import BaseSettings, parse_argv
|
||||
from prime_rl.utils.config import BaseConfig, cli
|
||||
|
||||
MAX_LORAS = 4
|
||||
|
||||
@@ -46,7 +46,7 @@ def extract_oom_error_reason(output: str) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
class BenchmarkConfig(BaseSettings):
|
||||
class BenchmarkConfig(BaseConfig):
|
||||
"""Configuration for running a single benchmark."""
|
||||
|
||||
type: Annotated[
|
||||
@@ -83,6 +83,11 @@ class BenchmarkConfig(BaseSettings):
|
||||
|
||||
cp: Annotated[int, Field(ge=1, description="Context parallelism size (1 = no CP)")] = 1
|
||||
|
||||
fused_lm_head_token_chunk_size: Annotated[
|
||||
int | None,
|
||||
Field(description="Fused LM head token chunk size (None uses trainer default)"),
|
||||
] = None
|
||||
|
||||
docker_image: Annotated[str | None, Field(description="Docker image used for the benchmark")] = None
|
||||
|
||||
# Metadata set by the script
|
||||
@@ -152,6 +157,10 @@ def build_command(config: BenchmarkConfig) -> list[str]:
|
||||
if config.cp > 1:
|
||||
cmd.extend(["--model.cp", str(config.cp)])
|
||||
|
||||
# Fused LM head chunk size
|
||||
if config.fused_lm_head_token_chunk_size is not None:
|
||||
cmd.extend(["--model.fused-lm-head-token-chunk-size", str(config.fused_lm_head_token_chunk_size)])
|
||||
|
||||
# Data configuration differs between RL and SFT
|
||||
if config.type.startswith("rl"):
|
||||
cmd.extend(["--data.fake.batch-size", str(config.micro_batches * config.num_gpus)])
|
||||
@@ -239,7 +248,7 @@ def run_benchmark(config: BenchmarkConfig) -> None:
|
||||
|
||||
|
||||
def main():
|
||||
config = parse_argv(BenchmarkConfig)
|
||||
config = cli(BenchmarkConfig)
|
||||
run_benchmark(config)
|
||||
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ rollouts_per_example = 16
|
||||
max_tokens = 512
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
id = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2 }
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
@@ -20,7 +17,7 @@ rollouts_per_example = 8
|
||||
max_tokens = 384
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
id = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
type = "single_node"
|
||||
num_infer_gpus = 1
|
||||
num_train_gpus = 1
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 1024
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
|
||||
|
||||
[inference]
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ max_async_level = 5
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
seq_len = 65536
|
||||
fused_lm_head_token_chunk_size = 8192
|
||||
|
||||
[model.lora]
|
||||
rank = 8
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
max_steps = 20
|
||||
|
||||
[ckpt]
|
||||
resume_step = 10
|
||||
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
|
||||
[model.lora]
|
||||
rank = 8
|
||||
target_modules = [
|
||||
"q_proj",
|
||||
"k_proj",
|
||||
"v_proj",
|
||||
"o_proj",
|
||||
"gate_proj",
|
||||
"up_proj",
|
||||
"down_proj",
|
||||
]
|
||||
|
||||
[data]
|
||||
name = "PrimeIntellect/Reverse-Text-SFT"
|
||||
batch_size = 4
|
||||
seq_len = 1024
|
||||
|
||||
[optim]
|
||||
lr = 1.5e-5
|
||||
@@ -0,0 +1,29 @@
|
||||
max_steps = 10
|
||||
|
||||
[ckpt]
|
||||
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
|
||||
[model.lora]
|
||||
rank = 8
|
||||
target_modules = [
|
||||
"q_proj",
|
||||
"k_proj",
|
||||
"v_proj",
|
||||
"o_proj",
|
||||
"gate_proj",
|
||||
"up_proj",
|
||||
"down_proj",
|
||||
]
|
||||
|
||||
[data]
|
||||
name = "PrimeIntellect/Reverse-Text-SFT"
|
||||
batch_size = 4
|
||||
seq_len = 1024
|
||||
|
||||
[optim]
|
||||
lr = 1.5e-5
|
||||
@@ -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"
|
||||
|
||||
@@ -21,7 +22,7 @@ temperature = 0.6
|
||||
max_tokens = 8192
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/math-env"
|
||||
id = "math-env"
|
||||
name = "acereason-math"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
inference_gpu_ids = [0,1,2,3]
|
||||
trainer_gpu_ids = [4,5,6,7]
|
||||
|
||||
max_steps = 300
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/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_fraction = 0.0
|
||||
hard_fraction = 0.0
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
|
||||
[orchestrator.val]
|
||||
interval = 5
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_tokens = 2048
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "primeintellect/math500"
|
||||
name = "math500"
|
||||
num_examples = 30
|
||||
rollouts_per_example = 4
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
[inference]
|
||||
@@ -1,13 +1,18 @@
|
||||
# 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"
|
||||
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
@@ -16,7 +21,7 @@ rollouts_per_example = 16
|
||||
max_tokens = 64
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/color-codeword"
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
|
||||
|
||||
[orchestrator.val]
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -41,6 +41,6 @@ port = 8000
|
||||
sync_interval = 5.0
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
id = "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"
|
||||
@@ -47,6 +48,5 @@ api_server_count = 8
|
||||
gpu_memory_utilization = 0.8
|
||||
|
||||
[inference.model]
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "hermes"
|
||||
max_model_len = 8192
|
||||
@@ -0,0 +1,19 @@
|
||||
enable_expert_parallel = true
|
||||
enable_eplb = false
|
||||
use_deep_gemm = true
|
||||
gpu_memory_utilization = 0.85
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-5-FP8"
|
||||
tool_call_parser = "auto"
|
||||
reasoning_parser = "glm45"
|
||||
|
||||
[deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 4
|
||||
num_decode_nodes = 2
|
||||
gpus_per_node = 8
|
||||
|
||||
[slurm]
|
||||
job_name = "glm5"
|
||||
partition = "cluster"
|
||||
@@ -1,6 +1,3 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 100
|
||||
seq_len = 2048
|
||||
|
||||
@@ -19,7 +16,7 @@ rollouts_per_example = 16
|
||||
max_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/math-env"
|
||||
id = "math-env"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
trainer_gpu_ids = [0]
|
||||
inference_gpu_ids = [1]
|
||||
|
||||
max_steps = 500
|
||||
seq_len = 2048
|
||||
|
||||
@@ -19,7 +16,7 @@ rollouts_per_example = 16
|
||||
max_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/math-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 }
|
||||
|
||||
@@ -38,7 +35,7 @@ interval = 10
|
||||
max_tokens = 2048
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "primeintellect/math500"
|
||||
id = "math500"
|
||||
num_examples = 30
|
||||
rollouts_per_example = 4
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 3000
|
||||
seq_len = 8192
|
||||
|
||||
@@ -16,7 +13,7 @@ batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/math-env"
|
||||
id = "math-env"
|
||||
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
name = "hendrycks-math"
|
||||
|
||||
@@ -24,7 +21,7 @@ name = "hendrycks-math"
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "primeintellect/aime2024"
|
||||
id = "aime2024"
|
||||
name = "aime2024"
|
||||
rollouts_per_example = 16
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
trainer_gpu_ids = [0]
|
||||
inference_gpu_ids = [1]
|
||||
|
||||
max_steps = 500
|
||||
|
||||
[wandb]
|
||||
@@ -16,12 +13,12 @@ rollouts_per_example = 16
|
||||
oversampling_factor = 1.5
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/math-env"
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/math-env"
|
||||
id = "math-env"
|
||||
name = "acereason-math"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem" }
|
||||
|
||||
@@ -37,7 +34,7 @@ num_examples = 128
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "primeintellect/aime2024"
|
||||
id = "aime2024"
|
||||
name = "aime2024"
|
||||
num_examples = 30
|
||||
rollouts_per_example = 4
|
||||
|
||||
@@ -25,6 +25,5 @@ args = { sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox
|
||||
api_server_count = 4
|
||||
|
||||
[inference.model]
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "hermes"
|
||||
max_model_len = 4096
|
||||
@@ -1,12 +1,13 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 15
|
||||
seq_len = 4096
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-VL-4B-Instruct"
|
||||
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
@@ -16,7 +17,7 @@ rollouts_per_example = 16
|
||||
max_tokens = 64
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/color-codeword"
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
|
||||
|
||||
[orchestrator.val]
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
max_steps = 3
|
||||
seq_len = 2048
|
||||
output_dir = "outputs/rl_color_codeword_test"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-VL-4B-Instruct"
|
||||
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 16
|
||||
rollouts_per_example = 2
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 32
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 2, num_examples = 100, seed = 42 }
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
optimization_dtype = "bfloat16"
|
||||
reduce_dtype = "bfloat16"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 1
|
||||
@@ -0,0 +1,80 @@
|
||||
output_dir = "/data/sami_debug/nemotron-debug"
|
||||
clean_output_dir = true
|
||||
max_steps = 5
|
||||
seq_len = 2048
|
||||
|
||||
[slurm]
|
||||
job_name = "nemotron-4node"
|
||||
pre_run_command = "uv sync --all-extras --group mamba-ssm"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 4
|
||||
num_infer_nodes = 4
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
[wandb]
|
||||
project = "sami_debug_nemotron"
|
||||
name = "nemotron-120b-math"
|
||||
shared = true
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[model]
|
||||
name = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 1800
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2"
|
||||
optim_cpu_offload = true
|
||||
ep = 8
|
||||
fused_lm_head_token_chunk_size = 8192
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 8
|
||||
|
||||
[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
|
||||
|
||||
[orchestrator.val]
|
||||
interval = 5
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_tokens = 2048
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
num_examples = 30
|
||||
rollouts_per_example = 4
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
dp = 1
|
||||
@@ -0,0 +1,79 @@
|
||||
output_dir = "outputs/rl-nemotron-debug"
|
||||
clean_output_dir = true
|
||||
max_steps = 500
|
||||
seq_len = 4096
|
||||
|
||||
[slurm]
|
||||
job_name = "nemotron-sami-debug"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 2
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
[wandb]
|
||||
project = "nemotron_sami_debug"
|
||||
name = "nemotron-120b-math"
|
||||
shared = true
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[model]
|
||||
name = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2"
|
||||
optim_cpu_offload = true
|
||||
fused_lm_head_token_chunk_size = 8192
|
||||
|
||||
[trainer.model.debug]
|
||||
random_init = true
|
||||
num_layers = 8
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 4096
|
||||
|
||||
[[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
|
||||
|
||||
[orchestrator.val]
|
||||
interval = 5
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_tokens = 4096
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
num_examples = 30
|
||||
rollouts_per_example = 4
|
||||
|
||||
[inference.parallel]
|
||||
tp = 4
|
||||
dp = 4
|
||||
@@ -1,6 +1,3 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 500
|
||||
seq_len = 4096
|
||||
|
||||
@@ -40,8 +37,7 @@ max_tokens = 512
|
||||
online_difficulty_filtering = true
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/wiki-search"
|
||||
id = "wiki-search"
|
||||
|
||||
[inference.model]
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "hermes"
|
||||
|
||||
+3
-1
@@ -87,7 +87,9 @@ See the dedicated [SLURM guide](slurm.md).
|
||||
|
||||
## Inference
|
||||
|
||||
We rely on vLLMs multi-node deployment primitives and load balancing for multi-node deployments. Currently, vLLM supports multi-node data parallel deployment ([docs](https://docs.vllm.ai/en/v0.10.0/serving/data_parallel_deployment.html)).
|
||||
For SLURM-based inference deployment, see the [SLURM guide](slurm.md#inference-examples). Each node runs an independent vLLM replica — no manual coordination needed.
|
||||
|
||||
For manual multi-node deployment without SLURM, we rely on vLLM's multi-node data parallel deployment primitives ([docs](https://docs.vllm.ai/en/v0.10.0/serving/data_parallel_deployment.html)).
|
||||
|
||||
First, decide which node will be your head node and find a reachable private IP address for it. If your nodes are not colocated, you will likely need to setup VPN (e.g. [Tailscale](https://tailscale.com)) for the nodes to reach each other.
|
||||
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# Disaggregated Prefill/Decode Inference
|
||||
|
||||
Run MoE models with separate prefill and decode node groups for higher throughput.
|
||||
|
||||
## Quick Start
|
||||
|
||||
See [`configs/glm5_disagg_inference/inference.toml`](../configs/glm5_disagg_inference/inference.toml) for an example config.
|
||||
|
||||
```bash
|
||||
uv run inference @ configs/glm5_disagg_inference/inference.toml --output-dir /data/$USER/outputs
|
||||
```
|
||||
|
||||
## Prefill/Decode Ratio
|
||||
|
||||
| Workload | Recommended ratio (P:D) | Why |
|
||||
|---|---|---|
|
||||
| Agentic (SWE, Lean) | **3:1** | Long growing contexts → prefill-heavy |
|
||||
| Non-agentic (math, chat) | **1:2** | Short prompts, long generations → decode-heavy |
|
||||
|
||||
Monitor live queue depths:
|
||||
```bash
|
||||
curl -s http://<prefill_node>:8100/metrics | grep num_requests_waiting
|
||||
curl -s http://<decode_node>:8200/metrics | grep num_requests_waiting
|
||||
```
|
||||
|
||||
If prefill has queued requests and decode has zero, add more prefill nodes (and vice versa).
|
||||
|
||||
For historical averages (cumulative over the entire run), query the histogram metrics:
|
||||
```bash
|
||||
# Average queue time per request (seconds)
|
||||
curl -s http://<node>:<port>/metrics | awk '
|
||||
/request_queue_time_seconds_sum\{/ { sum += $2 }
|
||||
/request_queue_time_seconds_count\{/ { count += $2 }
|
||||
END { if (count > 0) printf "avg queue: %.2fs (%d requests)\n", sum/count, count }
|
||||
'
|
||||
|
||||
# Average prefill/decode compute time
|
||||
curl -s http://<node>:<port>/metrics | awk '
|
||||
/request_prefill_time_seconds_sum\{/ { ps += $2 }
|
||||
/request_prefill_time_seconds_count\{/ { pc += $2 }
|
||||
/request_decode_time_seconds_sum\{/ { ds += $2 }
|
||||
/request_decode_time_seconds_count\{/ { dc += $2 }
|
||||
END {
|
||||
if (pc > 0) printf "avg prefill: %.2fs\n", ps/pc
|
||||
if (dc > 0) printf "avg decode: %.2fs\n", ds/dc
|
||||
}
|
||||
'
|
||||
```
|
||||
|
||||
Other useful metrics on the `/metrics` endpoint:
|
||||
- `vllm:e2e_request_latency_seconds` — end-to-end latency
|
||||
- `vllm:kv_cache_usage_perc` — KV cache memory pressure
|
||||
- `vllm:nixl_xfer_time_seconds` — NIXL KV transfer duration
|
||||
- `vllm:nixl_bytes_transferred` — bytes per KV transfer
|
||||
|
||||
## UCX 1.19
|
||||
|
||||
NVSHMEM requires UCX >= 1.19 for multi-GPU CUDA support. Most clusters ship UCX 1.17 (via HPC-X), which causes `cuStreamCreate: invalid device context` errors during DeepEP internode dispatch.
|
||||
|
||||
**Check your version:**
|
||||
```bash
|
||||
/opt/hpcx/ucx/bin/ucx_info -v | head -1
|
||||
# If < 1.19, you need to build from source
|
||||
```
|
||||
|
||||
**Build UCX 1.19 (run once on a GPU node):**
|
||||
```bash
|
||||
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
|
||||
```
|
||||
|
||||
This installs UCX 1.19 to `prime-rl/third_party/ucx/`. The sbatch template automatically adds it to `LD_LIBRARY_PATH`, overriding the system version.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### `DeepEP error: timeout (dispatch CPU)`
|
||||
NVSHMEM internode communication failing. Check:
|
||||
1. UCX version >= 1.19? (`third_party/ucx/bin/ucx_info -v`)
|
||||
2. NVSHMEM libs reachable at `/tmp/deepep_build/nvshmem/lib/`? If not:
|
||||
```bash
|
||||
ssh <node> 'mkdir -p /tmp/deepep_build/nvshmem && \
|
||||
ln -sfn <venv>/lib/python3.12/site-packages/nvidia/nvshmem/lib \
|
||||
/tmp/deepep_build/nvshmem/lib'
|
||||
```
|
||||
3. IBGDA driver enabled? `ssh <node> 'cat /proc/driver/nvidia/params | grep EnableStreamMemOPs'` should show `1`.
|
||||
|
||||
### Router healthy but requests hang
|
||||
NIXL side channel not running on prefill. Check:
|
||||
```bash
|
||||
ssh <prefill_node> 'ss -tlnp sport ge :5600 sport le :5608 | grep -c LISTEN'
|
||||
# Should show 8 (one per DP rank). If 0, check logs for UCX/NVSHMEM errors.
|
||||
```
|
||||
+1
-1
@@ -50,7 +50,7 @@ For more details on multi-node deployment options, see the [deployment](deployme
|
||||
|
||||
We provide a fairly straight-forward SFT trainer which is capable of fine-tuning any conversational model on multi-turn conversation with tool calling. It shares a lot of components with the RL trainer, such as the modeling code, parallelism techniques, checkpoint format, logger, etc. which ensures a seemless post-training workflow.
|
||||
|
||||
To start an SFT training, you need to prepare a dataset in [prompt-completion format](https://huggingface.co/docs/trl/en/dataset_formats#prompt-completion) (we do not support any other format). Single-turn fine-tuning should be compatible with the chat templates of most models. However, to properly handle loss masking, we require that the tokenizer's chat template satisfies a prefix property: the tokenization of any conversation prefix must be a prefix of the tokenization of the full conversation. For instance, tokenizing message 1 should yield a token sequence that forms a prefix of tokenizing messages 1 and 2, which in turn should be a prefix of tokenizing messages 1, 2, 3, and so forth. An example of a chat template that *does not* satisfy this property is Qwen3's chat template, as it strips away past think sections.
|
||||
To start an SFT training, you need to prepare a conversational dataset in either [prompt-completion format](https://huggingface.co/docs/trl/en/dataset_formats#prompt-completion) or raw `messages` format. If `messages` is provided, the trainer interprets the full conversation as a single sample with an empty prompt and applies role-based loss masking across the whole chat. If both `messages` and `prompt` / `completion` are present, `messages` takes precedence. Single-turn fine-tuning should be compatible with the chat templates of most models. However, to properly handle loss masking, we require that the tokenizer's chat template satisfies a prefix property: the tokenization of any conversation prefix must be a prefix of the tokenization of the full conversation. For instance, tokenizing message 1 should yield a token sequence that forms a prefix of tokenizing messages 1 and 2, which in turn should be a prefix of tokenizing messages 1, 2, 3, and so forth. An example of a chat template that *does not* satisfy this property is Qwen3's chat template, as it strips away past think sections.
|
||||
|
||||
On a single GPU, start the training with the `sft` entrypoint
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ This directory maintains the documentation for PRIME-RL. It is organized into th
|
||||
- [**Environments**](environments.md) - Installing and using verifiers environments from the Environments Hub
|
||||
- [**Async Training**](async.md) - Understanding asynchronous off-policy training and step semantics
|
||||
- [**Logging**](logging.md) - Logging with loguru, torchrun, and Weights & Biases
|
||||
- [**Platform Monitoring**](platform-monitoring.md) - Register runs on the Prime Intellect platform and stream training metrics
|
||||
- [**MultiRunManager**](multi_run_manager.md) - Multi-run training with the MultiRunManager object for concurrent LoRA adapters
|
||||
- [**Checkpointing**](checkpointing.md) - Saving and resuming training from checkpoints
|
||||
- [**Benchmarking**](benchmarking.md) - Performance benchmarking and throughput measurement
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
"environments",
|
||||
"async",
|
||||
"logging",
|
||||
"runs",
|
||||
"multi_run_manager",
|
||||
"checkpointing",
|
||||
"benchmarking",
|
||||
"deployment",
|
||||
|
||||
+43
-16
@@ -1,35 +1,62 @@
|
||||
# Multimodal (VLM) Support
|
||||
|
||||
Prime-RL has experimental support for training vision-language models (VLMs) like Qwen3-VL.
|
||||
Prime-RL supports training vision-language models (VLMs) like Qwen3-VL.
|
||||
|
||||
## VLM Configuration
|
||||
|
||||
### Supported Models
|
||||
|
||||
The built-in registry supports these model families out of the box:
|
||||
|
||||
| Model Family | model_type | Vision Encoder | Language Model |
|
||||
|-------------|------------|---------------|----------------|
|
||||
| Qwen3-VL | `qwen3_vl` | `model.visual` | `model.language_model` |
|
||||
| Qwen3.5 | `qwen3_5` | `model.visual` | `model.language_model` |
|
||||
| Qwen3.5-MoE | `qwen3_5_moe` | `model.visual` | `model.language_model` |
|
||||
|
||||
Enable VLM mode by adding a `[model.vlm]` section. Both fields are required — they tell prime-rl where the vision encoder and language model live on the model object:
|
||||
|
||||
```toml
|
||||
[model]
|
||||
name = "Qwen/Qwen3-VL-4B-Instruct"
|
||||
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
```
|
||||
|
||||
For the registered models in the table above, use the attrs shown there. For custom VLMs, check your model's structure with `model.named_children()`.
|
||||
|
||||
Both fields are dotted attribute paths resolved on the loaded model. A bad path raises a `ValueError` immediately — there are no silent fallbacks.
|
||||
|
||||
The weight key prefix for NCCL broadcasting is derived automatically as `{language_model_attr}.layers.`.
|
||||
|
||||
To add permanent support for a new model family, add an entry to `VLM_REGISTRY` in `src/prime_rl/utils/vlm.py`.
|
||||
|
||||
## Current Limitations
|
||||
|
||||
- **No SFT support**: Supervised fine-tuning is not yet supported for VLM models. Only RL training is available.
|
||||
|
||||
- **Vision encoder is frozen**: The vision encoder is automatically frozen during training. Only the language model is trained.
|
||||
|
||||
- **No multimodal-safe truncation**: Token sequences are truncated to `seq_len`, but `pixel_values` and `image_grid_thw` are passed through unchanged. If a multimodal sample exceeds `seq_len`, image tokens can be dropped while image tensors still describe the full set of images. Ensure `seq_len` covers your longest VLM samples or avoid overlong rollouts.
|
||||
- **No multimodal-safe truncation**: Token sequences are truncated to `seq_len`, but `pixel_values` and `image_grid_thw` are passed through unchanged. If a multimodal sample exceeds `seq_len`, image tokens can be dropped while image tensors still describe the full set of images. Ensure `seq_len` covers your longest VLM samples.
|
||||
|
||||
- **The images that the VLM sees are not logged**
|
||||
- **Optimization dtype must be bfloat16**: Set `optimization_dtype = "bfloat16"` and `reduce_dtype = "bfloat16"` in your trainer config.
|
||||
|
||||
- **Optimization dtype must be bfloat16**: VLM models must load in bfloat16 to match vLLM inference. If the trainer uses a different dtype, the vision encoder produces different `pixel_values`, causing a mismatch between inference and training. A workaround would be to propagate the `pixel_values` computed by vLLM to the trainer, but this is more involved. For now, set `optimization_dtype = "bfloat16"` and `reduce_dtype = "bfloat16"` in your trainer config.
|
||||
- **Higher KL mismatch with multi-image inputs**: VLM training exhibits higher KL mismatch compared to text-only, especially with multiple images.
|
||||
|
||||
- **Higher KL mismatch with multi-image inputs**: VLM training exhibits higher KL mismatch between inference and trainer logprobs compared to text-only models, especially with multiple images per sample. We are investigating the root cause. The existing importance ratio masking thresholds should handle reasonable mismatches.
|
||||
- **Images are not logged**: The images the VLM sees during training are not logged to monitors.
|
||||
|
||||
## How Multi-Turn VLM Training Works
|
||||
## How Multi-Turn VLM RL Training Works
|
||||
|
||||
VLM training uses the same `interleave_rollout` path as text-only models. Multi-turn trajectory steps are merged into a single training sample wherever the extension property holds (consecutive steps share a token prefix). When extension breaks (e.g., due to context compaction), a new sample is started automatically.
|
||||
VLM training uses the same `interleave_rollout` path as text-only models. Multi-turn trajectory steps are merged into a single training sample wherever the extension property holds.
|
||||
|
||||
Images are handled via a `VLMImageCache` built once per batch:
|
||||
|
||||
1. **Extract**: Base64 images are decoded from trajectory step prompts into PIL images. Since prompts are cumulative, only new images per step are extracted.
|
||||
2. **Preprocess**: All images are processed in a single batched call through the HuggingFace image processor, producing `pixel_values` (patches) and `image_grid_thw` (grid dimensions).
|
||||
3. **Attach**: Each training sample receives the cumulative `pixel_values` up to its last merged step. When steps are merged, the sample's images are updated to include all images seen so far.
|
||||
1. **Extract**: Base64 images are decoded from trajectory step prompts into PIL images.
|
||||
2. **Preprocess**: Images are processed through the HuggingFace image processor, producing `pixel_values` and `image_grid_thw`.
|
||||
3. **Attach**: Each training sample receives the cumulative `pixel_values` up to its last merged step.
|
||||
|
||||
This works correctly for all combinations: images in early turns with text-only follow-ups, images appearing mid-conversation, new images accumulating across turns, and interleaved agents with separate image streams.
|
||||
|
||||
Each multimodal sample becomes its own micro-batch during training (no packing with other samples) since image tensor sizes vary per sample.
|
||||
Each multimodal sample becomes its own micro-batch during training (no packing) since image tensor sizes vary.
|
||||
|
||||
## vLLM Configuration
|
||||
|
||||
`VLLM_WORKER_MULTIPROC_METHOD=spawn` is required for VLM inference. This is set automatically in `src/prime_rl/inference/config.py`, so if you use `uv run rl @ ...` it works out of the box, but if you start the vLLM server yourself, make sure this environment variable is set.
|
||||
`VLLM_WORKER_MULTIPROC_METHOD=spawn` is required for VLM inference. This is set automatically when using `uv run rl @ ...`, but if you start the vLLM server yourself, make sure this environment variable is set.
|
||||
|
||||
@@ -6,10 +6,11 @@ For more details, see [On-Policy Distillation](https://thinkingmachines.ai/blog/
|
||||
|
||||
## Quick Start
|
||||
|
||||
Add `teacher_gpu_ids` and set `teacher_tau > 0`:
|
||||
Add `num_teacher_gpus` to `[deployment]` and set `teacher_tau > 0`:
|
||||
|
||||
```toml
|
||||
teacher_gpu_ids = [2, 3]
|
||||
[deployment]
|
||||
num_teacher_gpus = 2
|
||||
|
||||
[trainer.loss]
|
||||
teacher_tau = 0.5
|
||||
@@ -18,7 +19,8 @@ teacher_tau = 0.5
|
||||
This automatically starts a teacher inference server using the same model as inference. To use a different teacher model:
|
||||
|
||||
```toml
|
||||
teacher_gpu_ids = [2, 3]
|
||||
[deployment]
|
||||
num_teacher_gpus = 2
|
||||
|
||||
[teacher_inference.model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
@@ -47,26 +49,68 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
For agentic environments where verification is expensive (code execution, tool use, multi-turn interactions), you can skip verification entirely and use only the teacher signal:
|
||||
|
||||
```toml
|
||||
teacher_gpu_ids = [2, 3]
|
||||
[deployment]
|
||||
num_teacher_gpus = 2
|
||||
|
||||
[trainer.loss]
|
||||
teacher_tau = 1.0
|
||||
adv_tau = 0.0 # Disable reward-based learning
|
||||
|
||||
[orchestrator.buffer]
|
||||
skip_verification = true # Skip expensive verification
|
||||
[orchestrator.verification]
|
||||
enabled = false # Skip expensive verification
|
||||
```
|
||||
|
||||
This runs pure on-policy distillation: the student learns to match the teacher without needing any reward signal.
|
||||
|
||||
## SFT Distillation ("Hard Distillation") From Teacher Rollouts
|
||||
|
||||
Use this mode when you want to train from teacher-generated completions directly (hard distillation), without teacher token-level logprobs.
|
||||
|
||||
```toml
|
||||
[trainer.loss]
|
||||
type = "sft"
|
||||
|
||||
[orchestrator]
|
||||
use_token_client = false
|
||||
|
||||
[orchestrator.teacher_rollout_model.client]
|
||||
base_url = ["https://your-openai-compatible-endpoint/v1"]
|
||||
skip_model_check = true
|
||||
|
||||
[orchestrator.teacher_rollout_model.model]
|
||||
name = "teacher-model-name"
|
||||
```
|
||||
|
||||
In this mode:
|
||||
- Rollouts are generated from `orchestrator.teacher_rollout_model`
|
||||
- The orchestrator uses text-level reconstruction with the student tokenizer
|
||||
- The RL trainer optimizes masked NLL (`trainer.loss.type = "sft"`)
|
||||
- Omit `[inference]` (no local inference server required)
|
||||
|
||||
### Image Input (VLM) Support
|
||||
|
||||
Yes, image input is supported in SFT/hard-distillation mode when the student model is multimodal (VLM).
|
||||
|
||||
- Prompts can include OpenAI-style image items in `message.content`, e.g. `{"type": "image_url", "image_url": {"url": "data:image/..."}}`
|
||||
- The orchestrator extracts and preprocesses images from trajectory prompts and attaches `pixel_values`/`image_grid_thw` to training samples
|
||||
- No teacher token IDs/logprobs are required; reconstruction still happens from messages
|
||||
|
||||
Notes:
|
||||
- This path currently expects `data:image/...` payloads in message content
|
||||
- The teacher rollout endpoint still needs to be able to handle the same multimodal prompts during generation
|
||||
|
||||
Reference configs:
|
||||
- `configs/alphabet_sort/sft_distill_hard_qwen4b_lora_prime_teacher.toml`
|
||||
- `examples/alphabet_sort/sft_distill_hard.toml`
|
||||
|
||||
## Parameters
|
||||
|
||||
| Parameter | Default | Description |
|
||||
|-----------|---------|-------------|
|
||||
| `teacher_gpu_ids` | `None` | GPUs for teacher server. Auto-starts server when set. |
|
||||
| `deployment.num_teacher_gpus` | `None` | Number of GPUs for teacher server. Auto-starts server when set. |
|
||||
| `trainer.loss.teacher_tau` | `0.0` | Distillation strength. Set `> 0` to enable. |
|
||||
| `trainer.loss.adv_tau` | `1.0` | Weight for RL advantage signal. Set `0` for pure distillation. |
|
||||
| `orchestrator.buffer.skip_verification` | `false` | Skip verification. Use with `adv_tau = 0`. |
|
||||
| `orchestrator.verification.enabled` | `true` | Enable/disable verification. Set to `false` for pure distillation with `adv_tau = 0`. |
|
||||
|
||||
## Monitoring
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# Platform Monitoring
|
||||
|
||||
Use `orchestrator.prime_monitor` to register a run on the Prime Intellect platform and stream training metrics, samples, and distributions.
|
||||
|
||||
> **Internal-only for now:** external run registration is currently only enabled for internal / allowlisted teams.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
You need a Prime API key with `rft:write` scope.
|
||||
|
||||
Use the CLI:
|
||||
|
||||
```bash
|
||||
prime login
|
||||
```
|
||||
|
||||
Or set an environment variable directly:
|
||||
|
||||
```bash
|
||||
export PRIME_API_KEY=pit_...
|
||||
```
|
||||
|
||||
## Minimal config
|
||||
|
||||
```toml
|
||||
[orchestrator.prime_monitor]
|
||||
run_name = "my-experiment"
|
||||
```
|
||||
|
||||
You can also override from the CLI:
|
||||
|
||||
```bash
|
||||
uv run rl @ config.toml --orchestrator.prime_monitor.run_name "my-experiment"
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### `API key not found`
|
||||
|
||||
Set the env var from `api_key_var` or run:
|
||||
|
||||
```bash
|
||||
prime login
|
||||
```
|
||||
|
||||
### `External training runs are not enabled for this team`
|
||||
|
||||
Your team is not allowlisted yet. This feature is currently internal-only.
|
||||
+222
-79
@@ -1,89 +1,124 @@
|
||||
# SLURM
|
||||
|
||||
For 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`.
|
||||
The `rl`, `sft`, and `inference` entrypoints all have built-in SLURM support. Adding a `[slurm]` section to your config switches from local execution to SLURM job submission — no separate entrypoint needed.
|
||||
|
||||
## 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"` |
|
||||
| `nodelist` | Comma-separated list of specific nodes to run on (`--nodelist`) | `None` |
|
||||
| `exclude` | Comma-separated list of nodes to exclude (`--exclude`) | `None` |
|
||||
| `account` | SLURM account to charge (`--account`) | `None` |
|
||||
| `time` | Maximum wall time, e.g. `"24:00:00"` (`--time`) | `None` |
|
||||
| `pre_run_command` | Shell command to run on head node after env setup, before starting the job (e.g. cleanup) | `None` |
|
||||
|
||||
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) |
|
||||
|
||||
**Inference** runs independent vLLM replicas per node:
|
||||
|
||||
| Field | single_node | multi_node |
|
||||
|---|---|---|
|
||||
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
|
||||
| `num_nodes` | — | Number of inference nodes (default: 1) |
|
||||
|
||||
The SLURM template is auto-selected based on `deployment.type`. You can override it with `slurm.template_path`.
|
||||
|
||||
### Constraints
|
||||
|
||||
- `output_dir` should be explicitly set when using SLURM (defaults to `"outputs"`)
|
||||
- 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"
|
||||
|
||||
@@ -118,37 +153,145 @@ tp = 4
|
||||
dp = 2
|
||||
```
|
||||
|
||||
## Custom SLURM Templates
|
||||
See [`examples/hendrycks_math/rl.toml`](../examples/hendrycks_math/rl.toml) for the full example.
|
||||
|
||||
The default 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)
|
||||
|
||||
```toml
|
||||
output_dir = "outputs/sft-moe-math"
|
||||
max_steps = 500
|
||||
|
||||
[slurm]
|
||||
job_name = "sft-moe-math"
|
||||
|
||||
[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
|
||||
```
|
||||
|
||||
See [`examples/hendrycks_math/sft.toml`](../examples/hendrycks_math/sft.toml) for the full example.
|
||||
|
||||
---
|
||||
|
||||
## Inference Examples
|
||||
|
||||
### Single-node SLURM
|
||||
|
||||
Run a vLLM server on a single allocated node:
|
||||
|
||||
```toml
|
||||
output_dir = "/shared/outputs/my-inference"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-8B"
|
||||
|
||||
[parallel]
|
||||
tp = 8
|
||||
|
||||
[slurm]
|
||||
job_name = "my-inference"
|
||||
```
|
||||
|
||||
```bash
|
||||
uv run inference @ inference_slurm.toml
|
||||
```
|
||||
|
||||
### Multi-node SLURM
|
||||
|
||||
Each node runs an independent vLLM replica. TP and DP must fit within a single node — there is no cross-node parallelism.
|
||||
|
||||
```toml
|
||||
output_dir = "/shared/outputs/my-inference"
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/INTELLECT-3-RL-600"
|
||||
|
||||
[parallel]
|
||||
tp = 4
|
||||
dp = 2
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 4
|
||||
|
||||
[slurm]
|
||||
job_name = "my-inference"
|
||||
```
|
||||
|
||||
After submission, the SLURM template prints the inference URLs for all nodes (one per node).
|
||||
|
||||
### Dry run
|
||||
|
||||
Use `dry_run = true` to generate the sbatch script without submitting:
|
||||
|
||||
```bash
|
||||
uv run inference @ config.toml --dry-run true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 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, the logs are available at:
|
||||
After submission, logs are available at:
|
||||
|
||||
```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
|
||||
# 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
|
||||
|
||||
# Inference (single or multi-node)
|
||||
tail -F {output_dir}/slurm/latest_infer_node_rank_0.log
|
||||
```
|
||||
|
||||
For convenience, a tmux launcher is provided that sets up a session with all three log streams:
|
||||
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.
|
||||
|
||||
@@ -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,51 @@
|
||||
max_steps = 24
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
type = "single_node"
|
||||
gpus_per_node = 2
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 0
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[wandb]
|
||||
project = "alphabet-sort-sft-distill"
|
||||
name = "qwen3-4b-hard-distill"
|
||||
|
||||
[ckpt]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[trainer.loss]
|
||||
type = "sft"
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 16
|
||||
alpha = 32
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 4
|
||||
use_token_client = false
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 512
|
||||
temperature = 0.7
|
||||
|
||||
[orchestrator.teacher_rollout_model.client]
|
||||
base_url = ["https://api.pinference.ai/api/v1"]
|
||||
api_key_var = "PRIME_API_KEY"
|
||||
|
||||
[orchestrator.teacher_rollout_model.model]
|
||||
name = "qwen/qwen3-235b-a22b-instruct-2507"
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
|
||||
@@ -0,0 +1,5 @@
|
||||
# Usage: uv run rl @ examples/alphabet_sort/rl.toml @ examples/alphabet_sort/slurm_rl.toml
|
||||
output_dir = "outputs/alphabet-sort"
|
||||
|
||||
[slurm]
|
||||
job_name = "alphabet-sort"
|
||||
@@ -0,0 +1,25 @@
|
||||
# Hendrycks Sanity
|
||||
|
||||
This example runs the Hendrycks Sanity Check experiment proposed in [Defeating the Training-Inference Mismatch](https://arxiv.org/abs/2510.26788). The sanity check tests whether an RL algorithm can reliably improve a model on problems it can *already partially solve*. The dataset is filtered from MATH to only include problems where the base model (`DeepSeek-R1-Distill-Qwen-1.5B`) solves 20-80% of the time across 40 rollouts. A reliable algorithm should push training accuracy on this "perfectible" subset above 95%.
|
||||
|
||||
Because our trainer is asynchronous, we perform only one gradient step per batch (the inference engine generates the next batch while the trainer processes the current one).
|
||||
|
||||
> This example runs on 8 GPUs (4 for inference, 4 for training).
|
||||
|
||||
## Training
|
||||
|
||||
Schedule training locally on a node with 8 GPUs
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/hendrycks_sanity/rl.toml \
|
||||
--wandb.project your-project \
|
||||
--wandb.name your-run
|
||||
```
|
||||
|
||||
Or schedule the same training via SLURM
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/hendrycks_sanity/slurm_rl.toml \
|
||||
--wandb.project your-project \
|
||||
--wandb.name your-run
|
||||
```
|
||||
@@ -0,0 +1,37 @@
|
||||
max_steps = 5000
|
||||
seq_len = 8192
|
||||
|
||||
[wandb]
|
||||
project = "hendrycks-sanity"
|
||||
name = "hendrycks-sanity"
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "math-env" # included in lock file
|
||||
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
name = "hendrycks-math"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "primeintellect/aime2024"
|
||||
name = "aime2024"
|
||||
rollouts_per_example = 32
|
||||
|
||||
[trainer.model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
seq_len = 16384
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 8192
|
||||
@@ -0,0 +1,5 @@
|
||||
# Usage: uv run rl @ examples/hendrycks_sanity/rl.toml @ examples/hendrycks_sanity/slurm_rl.toml
|
||||
output_dir = "outputs/hendrycks-sanity"
|
||||
|
||||
[slurm]
|
||||
job_name = "hendrycks-sanity"
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
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"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
optim_cpu_offload = true
|
||||
|
||||
[model.compile]
|
||||
|
||||
[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
|
||||
@@ -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,5 @@
|
||||
# Usage: uv run rl @ examples/reverse_text/rl.toml @ examples/reverse_text/slurm_rl.toml
|
||||
output_dir = "outputs/reverse-text-rl"
|
||||
|
||||
[slurm]
|
||||
job_name = "reverse-text-rl"
|
||||
@@ -0,0 +1,5 @@
|
||||
# Usage: uv run sft @ examples/reverse_text/sft.toml @ examples/reverse_text/slurm_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"
|
||||
|
||||
@@ -48,5 +49,4 @@ id = "primeintellect/wiki-search"
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference.model]
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "hermes"
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# Usage: uv run rl @ examples/wiki_search/rl.toml @ examples/wiki_search/slurm_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,5 @@
|
||||
# Usage: uv run rl @ examples/wordle/rl.toml @ examples/wordle/slurm_rl.toml
|
||||
output_dir = "outputs/wordle-rl"
|
||||
|
||||
[slurm]
|
||||
job_name = "wordle-rl"
|
||||
@@ -0,0 +1,5 @@
|
||||
# Usage: uv run sft @ examples/wordle/sft.toml @ examples/wordle/slurm_sft.toml
|
||||
output_dir = "outputs/wordle-sft"
|
||||
|
||||
[slurm]
|
||||
job_name = "wordle-sft"
|
||||
+63
-17
@@ -12,20 +12,19 @@ dependencies = [
|
||||
"loguru>=0.7.3",
|
||||
"pyarrow>=21.0.0",
|
||||
"pydantic>=1.10.13",
|
||||
"pydantic-settings>=2.10.1",
|
||||
"pydantic-config",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"numpy>=2.2.6",
|
||||
"torch>=2.9.0",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers",
|
||||
"vllm",
|
||||
"vllm>=0.17.0",
|
||||
"wandb>=0.24.2",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.5.37",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"math-env",
|
||||
"tenacity>=8.2.0",
|
||||
"openai>=1.106.1",
|
||||
"rich>=14.0.0",
|
||||
@@ -33,33 +32,57 @@ dependencies = [
|
||||
"torchtitan",
|
||||
"verifiers",
|
||||
"dion",
|
||||
"reverse-text",
|
||||
"tilelang>=0.1.8",
|
||||
"flash-linear-attention",
|
||||
]
|
||||
|
||||
[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"
|
||||
inference = "prime_rl.entrypoints.inference: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"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
|
||||
|
||||
[project.optional-dependencies]
|
||||
flash-attn = [
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl",
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3+cu128torch2.10-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
|
||||
]
|
||||
flash-attn-3 = [
|
||||
"flash_attn_3 @ https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl",
|
||||
"flash_attn_3 @ https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl ; platform_machine == 'x86_64'",
|
||||
]
|
||||
flash-attn-cute = [
|
||||
"flash-attn-cute",
|
||||
]
|
||||
envs = [
|
||||
"reverse-text",
|
||||
"alphabet-sort",
|
||||
"wiki-search",
|
||||
"math-python",
|
||||
"math-env",
|
||||
"code-env",
|
||||
"science-env",
|
||||
"logic-env",
|
||||
"color-codeword",
|
||||
"math500",
|
||||
"aime2024",
|
||||
"aime2025",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
"deep-gemm ; platform_machine == 'x86_64'",
|
||||
"nixl",
|
||||
"nixl-cu12 ; platform_machine == 'x86_64'",
|
||||
"vllm-router",
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
mamba-ssm = [
|
||||
"mamba-ssm>=2.3.0",
|
||||
]
|
||||
dev = [
|
||||
"ipykernel>=6.29.5",
|
||||
"ipywidgets>=8.1.7",
|
||||
@@ -72,28 +95,49 @@ dev = [
|
||||
[tool.uv]
|
||||
preview = true
|
||||
no-build-isolation-package = ["flash-attn"]
|
||||
prerelease = "allow"
|
||||
environments = [
|
||||
"sys_platform == 'linux' and platform_machine == 'x86_64'",
|
||||
"sys_platform == 'linux' and platform_machine == 'aarch64'",
|
||||
]
|
||||
# Override torch's pinned cuDNN to fix Conv3d performance regression (torch 2.9 + cuDNN 9.8-9.14)
|
||||
# See: https://github.com/pytorch/pytorch/issues/166122
|
||||
override-dependencies = [
|
||||
"nvidia-cudnn-cu12>=9.15",
|
||||
"nvidia-cutlass-dsl>=4.4.1",
|
||||
"transformers>=5.1.0.dev0",
|
||||
"quack-kernels>=0.2.7",
|
||||
]
|
||||
|
||||
[tool.uv.sources]
|
||||
torch = { index = "pytorch-cu128" }
|
||||
math-env = { index = "primeintellect" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "9052ecf" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "f5580acd" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "609e3d5" }
|
||||
vllm = { url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl" }
|
||||
flash-attn-cute = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "main" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "5c1c72b" }
|
||||
flash-attn-cute = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "e2743ab5" }
|
||||
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", branch = "main" }
|
||||
vllm-router = { url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.3/vllm_router-0.1.11-cp38-abi3-linux_x86_64.whl" }
|
||||
reverse-text = { index = "primeintellect" }
|
||||
alphabet-sort = { index = "primeintellect" }
|
||||
wiki-search = { index = "primeintellect" }
|
||||
math-python = { index = "primeintellect" }
|
||||
math-env = { index = "primeintellect" }
|
||||
code-env = { index = "primeintellect" }
|
||||
science-env = { index = "primeintellect" }
|
||||
logic-env = { index = "primeintellect" }
|
||||
color-codeword = { index = "primeintellect" }
|
||||
math500 = { index = "primeintellect" }
|
||||
aime2024 = { index = "primeintellect" }
|
||||
aime2025 = { index = "primeintellect" }
|
||||
deep-ep = { url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.2/deep_ep-1.2.1+73b6ea4-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.2/deep_gemm-2.3.0+477618c-cp312-cp312-linux_x86_64.whl" }
|
||||
nixl-cu12 = { url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.2/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
|
||||
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
|
||||
|
||||
[tool.uv.extra-build-dependencies]
|
||||
flash-attn = [{ requirement = "torch", match-runtime = true }]
|
||||
flash-attn-3 = [{ requirement = "torch", match-runtime = true }]
|
||||
mamba-ssm = [{ requirement = "torch", match-runtime = true }]
|
||||
|
||||
[tool.uv.extra-build-variables]
|
||||
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
|
||||
@@ -101,12 +145,14 @@ flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
|
||||
[[tool.uv.index]]
|
||||
name = "primeintellect"
|
||||
url = "https://hub.primeintellect.ai/primeintellect/simple/"
|
||||
explicit = true
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128"
|
||||
url = "https://download.pytorch.org/whl/test/cu128"
|
||||
url = "https://download.pytorch.org/whl/cu128"
|
||||
explicit = true
|
||||
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["F", "I"]
|
||||
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
|
||||
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/bin/bash
|
||||
# arm64 post-install fixups for Docker builds.
|
||||
set -e
|
||||
|
||||
echo "=== building flash-attn from source (sm_100 / GB200) ==="
|
||||
# Run from /tmp so uv doesn't read pyproject.toml's [tool.uv.extra-build-variables]
|
||||
# which sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and prevents CUDA kernel compilation.
|
||||
export TORCH_CUDA_ARCH_LIST="10.0"
|
||||
export MAX_JOBS=4
|
||||
export FLASH_ATTENTION_FORCE_BUILD=TRUE
|
||||
export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
|
||||
(cd /tmp && uv pip install --python /app/.venv/bin/python \
|
||||
"flash-attn==2.8.3" --no-build-isolation --no-binary flash-attn --no-cache)
|
||||
|
||||
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
|
||||
uv pip install --reinstall --no-deps \
|
||||
"flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
|
||||
|
||||
# TODO: remove once flash-attn gates the ampere_helpers import or cutlass-dsl re-adds it.
|
||||
echo "=== copying ampere_helpers.py from flashinfer vendor ==="
|
||||
SITE_PACKAGES=".venv/lib/python3.12/site-packages"
|
||||
cp "$SITE_PACKAGES/flashinfer/data/cutlass/python/CuTeDSL/cutlass/utils/ampere_helpers.py" \
|
||||
"$SITE_PACKAGES/nvidia_cutlass_dsl/python_packages/cutlass/utils/ampere_helpers.py"
|
||||
@@ -11,7 +11,7 @@
|
||||
set -e
|
||||
|
||||
echo "Reinstalling flash-attn-cute to fix namespace conflict with flash-attn..."
|
||||
uv pip install --reinstall --no-deps "flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@main#subdirectory=flash_attn/cute"
|
||||
uv pip install --reinstall --no-deps "flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
|
||||
|
||||
# Verify installation
|
||||
LINES=$(wc -l < "$(python -c 'import flash_attn.cute.interface as m; print(m.__file__)')")
|
||||
|
||||
Executable
+84
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build and install DeepGEMM from source for FP8 MoE inference.
|
||||
#
|
||||
# Uses the commit recommended by vLLM for compatibility with vLLM 0.17+.
|
||||
# Requires CUDA 12.8+ and a Hopper/Blackwell GPU.
|
||||
#
|
||||
# Usage:
|
||||
# bash scripts/install_deep_gemm.sh
|
||||
#
|
||||
# Options:
|
||||
# --ref REF DeepGEMM commit hash (default: 477618c)
|
||||
# --wheel-dir DIR Output wheel to DIR instead of installing
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||
|
||||
DEEPGEMM_GIT_REPO="https://github.com/deepseek-ai/DeepGEMM.git"
|
||||
DEEPGEMM_GIT_REF="477618cd51baffca09c4b0b87e97c03fe827ef03"
|
||||
WHEEL_DIR=""
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
--ref) DEEPGEMM_GIT_REF="$2"; shift 2 ;;
|
||||
--wheel-dir) WHEEL_DIR="$2"; shift 2 ;;
|
||||
*) echo "Unknown argument: $1" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Skip if already installed at the right version
|
||||
INSTALLED_VER=$(python -c "import deep_gemm; print(deep_gemm.__version__)" 2>/dev/null || echo "")
|
||||
SHORT_REF="${DEEPGEMM_GIT_REF:0:7}"
|
||||
if [[ "$INSTALLED_VER" == *"$SHORT_REF"* ]]; then
|
||||
echo "DeepGEMM ${INSTALLED_VER} already installed, skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Auto-detect CUDA version
|
||||
CUDA_VERSION=$(nvcc --version 2>/dev/null | grep -oP 'release \K[\d.]+' || echo "")
|
||||
if [ -z "$CUDA_VERSION" ]; then
|
||||
echo "ERROR: nvcc not found. CUDA toolkit required." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CUDA_MAJOR="${CUDA_VERSION%%.*}"
|
||||
CUDA_MINOR="${CUDA_VERSION#*.}"
|
||||
CUDA_MINOR="${CUDA_MINOR%%.*}"
|
||||
if [ "$CUDA_MAJOR" -lt 12 ] || { [ "$CUDA_MAJOR" -eq 12 ] && [ "$CUDA_MINOR" -lt 8 ]; }; then
|
||||
echo "Skipping DeepGEMM (requires CUDA 12.8+, got ${CUDA_VERSION})"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "================================================================"
|
||||
echo " Building DeepGEMM (${SHORT_REF})"
|
||||
echo " CUDA: ${CUDA_VERSION}"
|
||||
echo "================================================================"
|
||||
|
||||
TMPDIR=$(mktemp -d)
|
||||
cleanup() { rm -rf "$TMPDIR"; }
|
||||
trap cleanup EXIT
|
||||
|
||||
git clone --recurse-submodules "$DEEPGEMM_GIT_REPO" "$TMPDIR/DeepGEMM" 2>&1
|
||||
cd "$TMPDIR/DeepGEMM"
|
||||
git checkout "$DEEPGEMM_GIT_REF"
|
||||
git submodule update --init --recursive
|
||||
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
if [ -n "$WHEEL_DIR" ]; then
|
||||
mkdir -p "$WHEEL_DIR"
|
||||
uv build --no-build-isolation --wheel --out-dir "$WHEEL_DIR" "$TMPDIR/DeepGEMM"
|
||||
echo ""
|
||||
echo "Wheel built:"
|
||||
ls -lh "$WHEEL_DIR"/deep_gemm*.whl
|
||||
else
|
||||
uv pip install --no-build-isolation --reinstall "$TMPDIR/DeepGEMM"
|
||||
echo ""
|
||||
echo "Installed: $(python -c 'import deep_gemm; print(deep_gemm.__version__)')"
|
||||
fi
|
||||
|
||||
echo "================================================================"
|
||||
echo " DeepGEMM build complete"
|
||||
echo "================================================================"
|
||||
Executable
+170
@@ -0,0 +1,170 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install DeepEP kernels for expert-parallel disaggregated inference.
|
||||
#
|
||||
# Builds NVSHMEM + DeepEP from source and installs into the project venv.
|
||||
# Required for disaggregated prefill/decode deployments with expert parallelism.
|
||||
#
|
||||
# Auto-detects the CUDA toolkit version that matches the installed PyTorch
|
||||
# and looks for it at /usr/local/cuda-X.Y. Fails if not found.
|
||||
#
|
||||
# Prerequisites:
|
||||
# - Matching CUDA toolkit installed (e.g. `sudo apt install cuda-toolkit-12-8`)
|
||||
# - For multi-node: IBGDA driver configured (see --configure-drivers)
|
||||
#
|
||||
# Usage:
|
||||
# bash scripts/install_ep_kernels.sh
|
||||
#
|
||||
# Options:
|
||||
# --workspace DIR Build directory (default: ./ep_kernels_workspace)
|
||||
# --deepep-ref REF DeepEP commit hash (default: 73b6ea4)
|
||||
# --nvshmem-ver VER NVSHMEM version (default: 3.3.24)
|
||||
# --configure-drivers Also configure IBGDA drivers (requires sudo, needs reboot)
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||
|
||||
DEEPEP_COMMIT_HASH="73b6ea4"
|
||||
NVSHMEM_VER="3.3.24"
|
||||
WORKSPACE="$REPO_ROOT/ep_kernels_workspace"
|
||||
CONFIGURE_DRIVERS=0
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
--workspace) WORKSPACE="$2"; shift 2 ;;
|
||||
--deepep-ref) DEEPEP_COMMIT_HASH="$2"; shift 2 ;;
|
||||
--nvshmem-ver) NVSHMEM_VER="$2"; shift 2 ;;
|
||||
--configure-drivers) CONFIGURE_DRIVERS=1; shift ;;
|
||||
*) echo "Unknown argument: $1" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Skip if DeepEP is already installed
|
||||
if python -c "import deep_ep" 2>/dev/null; then
|
||||
echo "DeepEP already installed, skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ── Auto-detect CUDA toolkit matching torch ───────────────────────────────────
|
||||
TORCH_CUDA_VER=$(python -c "import torch; print(torch.version.cuda)")
|
||||
CUDA_MAJOR_MINOR=$(echo "$TORCH_CUDA_VER" | grep -oP '^\d+\.\d+')
|
||||
CUDA_MAJOR=$(echo "$CUDA_MAJOR_MINOR" | cut -d. -f1)
|
||||
|
||||
CUDA_HOME="/usr/local/cuda-${CUDA_MAJOR_MINOR}"
|
||||
if [ ! -x "$CUDA_HOME/bin/nvcc" ]; then
|
||||
echo "ERROR: Could not find CUDA toolkit matching torch (cuda ${TORCH_CUDA_VER}) at ${CUDA_HOME}" >&2
|
||||
echo "Install it with: sudo apt install cuda-toolkit-${CUDA_MAJOR_MINOR//./-}" >&2
|
||||
exit 1
|
||||
fi
|
||||
export CUDA_HOME
|
||||
|
||||
# Verify versions actually match
|
||||
NVCC_VER=$("$CUDA_HOME/bin/nvcc" --version | grep -oP 'release \K[\d.]+')
|
||||
echo "Torch CUDA: ${TORCH_CUDA_VER}, nvcc: ${NVCC_VER} (${CUDA_HOME})"
|
||||
|
||||
# ── Auto-detect GPU architecture ──────────────────────────────────────────────
|
||||
GPU_NAME=$(nvidia-smi --query-gpu=gpu_name --format=csv,noheader,nounits -i 0 2>/dev/null)
|
||||
case "$GPU_NAME" in
|
||||
*H100*|*H200*|*H800*) TORCH_CUDA_ARCH_LIST="9.0" ;;
|
||||
*B100*|*B200*|*GB200*) TORCH_CUDA_ARCH_LIST="10.0" ;;
|
||||
*)
|
||||
echo "Could not auto-detect GPU arch from '$GPU_NAME'. Set TORCH_CUDA_ARCH_LIST manually." >&2
|
||||
echo " Hopper (H100/H200): TORCH_CUDA_ARCH_LIST=9.0" >&2
|
||||
echo " Blackwell (B200): TORCH_CUDA_ARCH_LIST=10.0" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
export TORCH_CUDA_ARCH_LIST
|
||||
|
||||
echo "================================================================"
|
||||
echo " Installing DeepEP kernels"
|
||||
echo " CUDA: ${CUDA_HOME} (${NVCC_VER})"
|
||||
echo " GPU: ${GPU_NAME} (arch ${TORCH_CUDA_ARCH_LIST})"
|
||||
echo " DeepEP: ${DEEPEP_COMMIT_HASH}"
|
||||
echo " NVSHMEM: ${NVSHMEM_VER}"
|
||||
echo " Workspace: ${WORKSPACE}"
|
||||
echo "================================================================"
|
||||
|
||||
mkdir -p "$WORKSPACE"
|
||||
|
||||
# ── Step 1: Install build deps ────────────────────────────────────────────────
|
||||
echo ""
|
||||
echo "--- Installing build dependencies ---"
|
||||
cd "$REPO_ROOT"
|
||||
uv pip install cmake ninja
|
||||
|
||||
# ── Step 2: Download and extract NVSHMEM ──────────────────────────────────────
|
||||
echo ""
|
||||
echo "--- Setting up NVSHMEM ${NVSHMEM_VER} ---"
|
||||
|
||||
ARCH=$(uname -m)
|
||||
case "${ARCH,,}" in
|
||||
x86_64|amd64) NVSHMEM_SUBDIR="linux-x86_64" ;;
|
||||
aarch64|arm64) NVSHMEM_SUBDIR="linux-sbsa" ;;
|
||||
*) echo "Unsupported architecture: ${ARCH}" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
NVSHMEM_DIR="$WORKSPACE/nvshmem"
|
||||
if [ ! -d "$NVSHMEM_DIR/lib" ]; then
|
||||
NVSHMEM_FILE="libnvshmem-${NVSHMEM_SUBDIR}-${NVSHMEM_VER}_cuda${CUDA_MAJOR}-archive.tar.xz"
|
||||
NVSHMEM_URL="https://developer.download.nvidia.com/compute/nvshmem/redist/libnvshmem/${NVSHMEM_SUBDIR}/${NVSHMEM_FILE}"
|
||||
|
||||
echo "Downloading ${NVSHMEM_URL}"
|
||||
curl -fSL "${NVSHMEM_URL}" -o "$WORKSPACE/${NVSHMEM_FILE}"
|
||||
tar -xf "$WORKSPACE/${NVSHMEM_FILE}" -C "$WORKSPACE"
|
||||
mv "$WORKSPACE/${NVSHMEM_FILE%.tar.xz}" "$NVSHMEM_DIR"
|
||||
rm -f "$WORKSPACE/${NVSHMEM_FILE}"
|
||||
rm -rf "$NVSHMEM_DIR/lib/bin" "$NVSHMEM_DIR/lib/share"
|
||||
echo "NVSHMEM extracted to ${NVSHMEM_DIR}"
|
||||
else
|
||||
echo "NVSHMEM already present at ${NVSHMEM_DIR}, skipping download"
|
||||
fi
|
||||
|
||||
export CMAKE_PREFIX_PATH="${NVSHMEM_DIR}/lib/cmake:${CMAKE_PREFIX_PATH:-}"
|
||||
export NVSHMEM_DIR
|
||||
|
||||
# ── Step 3: Build and install DeepEP ──────────────────────────────────────────
|
||||
echo ""
|
||||
echo "--- Building DeepEP (${DEEPEP_COMMIT_HASH}) ---"
|
||||
|
||||
DEEPEP_DIR="$WORKSPACE/DeepEP"
|
||||
if [ ! -d "$DEEPEP_DIR/.git" ]; then
|
||||
git clone https://github.com/deepseek-ai/DeepEP "$DEEPEP_DIR"
|
||||
fi
|
||||
|
||||
cd "$DEEPEP_DIR"
|
||||
git fetch origin
|
||||
git checkout "$DEEPEP_COMMIT_HASH"
|
||||
|
||||
WHEEL_DIR="$REPO_ROOT/deps"
|
||||
mkdir -p "$WHEEL_DIR"
|
||||
python setup.py bdist_wheel --dist-dir "$WHEEL_DIR"
|
||||
|
||||
WHEEL=$(ls "$WHEEL_DIR"/deep_ep*.whl | head -1)
|
||||
echo ""
|
||||
echo "--- DeepEP wheel built at: $WHEEL ---"
|
||||
|
||||
# ── Step 4 (optional): Configure IBGDA drivers ───────────────────────────────
|
||||
if [ "$CONFIGURE_DRIVERS" -eq 1 ]; then
|
||||
echo ""
|
||||
echo "--- Configuring IBGDA drivers (requires sudo) ---"
|
||||
echo 'options nvidia NVreg_EnableStreamMemOPs=1 NVreg_RegistryDwords="PeerMappingOverride=1;"' | sudo tee -a /etc/modprobe.d/nvidia.conf
|
||||
if command -v update-initramfs &> /dev/null; then
|
||||
sudo update-initramfs -u
|
||||
elif command -v dracut &> /dev/null; then
|
||||
sudo dracut --force
|
||||
else
|
||||
echo "No supported initramfs update tool found." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo ""
|
||||
echo "IBGDA configured. Please REBOOT the system to apply changes."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "================================================================"
|
||||
echo " DeepEP installation complete"
|
||||
echo " NVSHMEM: ${NVSHMEM_DIR}"
|
||||
echo " To verify: uv run python -c 'import deep_ep; print(deep_ep.__file__)'"
|
||||
echo "================================================================"
|
||||
Executable
+71
@@ -0,0 +1,71 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
# Build UCX 1.19.x with CUDA + IB support, then build NIXL against it.
|
||||
# Installs the unrepaired wheel (no auditwheel) so NIXL uses the UCX libs
|
||||
# directly from third_party/ucx/ at runtime via LD_LIBRARY_PATH.
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
VENV_BIN="$PROJECT_DIR/.venv/bin"
|
||||
PYTHON="$VENV_BIN/python"
|
||||
|
||||
WORKSPACE="$PROJECT_DIR/nixl_workspace"
|
||||
mkdir -p "$WORKSPACE"
|
||||
UCX_SRC="$WORKSPACE/ucx_source"
|
||||
UCX_INSTALL="$PROJECT_DIR/third_party/ucx"
|
||||
NIXL_SRC="$WORKSPACE/nixl_source"
|
||||
NIXL_VERSION="${NIXL_VERSION:-0.10.1}"
|
||||
CUDA_PATH="${CUDA_HOME:-/usr/local/cuda}"
|
||||
NPROC=$(nproc)
|
||||
|
||||
export PATH="$VENV_BIN:$PATH"
|
||||
|
||||
echo "=== Building UCX 1.19.x with CUDA + IB ==="
|
||||
if [ ! -d "$UCX_SRC" ]; then
|
||||
git clone https://github.com/openucx/ucx.git "$UCX_SRC"
|
||||
fi
|
||||
cd "$UCX_SRC"
|
||||
git checkout v1.19.x
|
||||
|
||||
if [ ! -f "$UCX_INSTALL/lib/libucs.so" ]; then
|
||||
./autogen.sh
|
||||
./configure \
|
||||
--prefix="$UCX_INSTALL" \
|
||||
--enable-shared \
|
||||
--disable-static \
|
||||
--disable-doxygen-doc \
|
||||
--enable-optimizations \
|
||||
--enable-cma \
|
||||
--enable-devel-headers \
|
||||
--enable-mt \
|
||||
--with-verbs \
|
||||
--with-cuda="$CUDA_PATH" \
|
||||
--with-ze=no
|
||||
make -j"$NPROC"
|
||||
make install
|
||||
echo "=== UCX installed to $UCX_INSTALL ==="
|
||||
else
|
||||
echo "=== UCX already built, skipping ==="
|
||||
fi
|
||||
|
||||
echo "=== Building NIXL $NIXL_VERSION ==="
|
||||
if [ ! -d "$NIXL_SRC" ]; then
|
||||
git clone https://github.com/ai-dynamo/nixl.git "$NIXL_SRC"
|
||||
else
|
||||
cd "$NIXL_SRC" && git fetch --tags
|
||||
fi
|
||||
cd "$NIXL_SRC"
|
||||
git checkout "$NIXL_VERSION"
|
||||
|
||||
export PKG_CONFIG_PATH="$UCX_INSTALL/lib/pkgconfig"
|
||||
export LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:-}"
|
||||
|
||||
# Build and install directly (no auditwheel) so NIXL links to our UCX at runtime
|
||||
WHEEL_DIR="$PROJECT_DIR/deps"
|
||||
mkdir -p "$WHEEL_DIR"
|
||||
uv pip install pip 2>/dev/null
|
||||
"$PYTHON" -m pip wheel . --no-deps --wheel-dir="$WHEEL_DIR"
|
||||
|
||||
WHEEL=$(ls "$WHEEL_DIR"/nixl*.whl | head -1)
|
||||
echo "=== NIXL wheel built at: $WHEEL ==="
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/bin/bash
|
||||
# Builds the patched vllm-router wheel (Rust via setuptools-rust) from our fork.
|
||||
# Requires: Rust toolchain (cargo), Python 3.8+, and uv or pip.
|
||||
# Override output dir: VLLM_ROUTER_WHEEL_DIR=/path/to/dir
|
||||
set -euo pipefail
|
||||
|
||||
REPO_URL="https://github.com/S1ro1/router.git"
|
||||
BRANCH="fix/preserve-extra-fields-disagg"
|
||||
BUILD_DIR="/tmp/vllm-router-build"
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
OUTPUT_DIR="${VLLM_ROUTER_WHEEL_DIR:-$SCRIPT_DIR/deps}"
|
||||
|
||||
echo "Cloning $REPO_URL (branch: $BRANCH)..."
|
||||
rm -rf "$BUILD_DIR"
|
||||
git clone --depth 1 --branch "$BRANCH" "$REPO_URL" "$BUILD_DIR"
|
||||
|
||||
echo "Building wheel -> $OUTPUT_DIR ..."
|
||||
mkdir -p "$OUTPUT_DIR"
|
||||
if command -v uv >/dev/null 2>&1; then
|
||||
uv build --wheel --out-dir "$OUTPUT_DIR" "$BUILD_DIR"
|
||||
else
|
||||
(cd "$BUILD_DIR" && python3 -m pip wheel . --no-deps -w "$OUTPUT_DIR")
|
||||
fi
|
||||
|
||||
echo "Cleaning up..."
|
||||
rm -rf "$BUILD_DIR"
|
||||
|
||||
wheel=$(ls -1t "$OUTPUT_DIR"/*.whl 2>/dev/null | head -1)
|
||||
echo "Done. Wheel: $wheel"
|
||||
echo "Install: uv pip install $wheel"
|
||||
+93
-18
@@ -17,17 +17,60 @@ from pathlib import Path
|
||||
import torch
|
||||
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
|
||||
from transformers import Glm4MoeForCausalLM as HFGlm4MoeForCausalLM
|
||||
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
Qwen3_5MoeForConditionalGeneration as HFQwen3_5MoeVLM,
|
||||
)
|
||||
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM as PrimeRLGlm4MoeForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2ForCausalLM as PrimeRLMiniMaxM2ForCausalLM
|
||||
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM as PrimeRLQwen3_5MoeVLM
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
setup_logger("info")
|
||||
|
||||
|
||||
def _qwen3_5_moe_vlm_config():
|
||||
"""Build a tiny composite VLM config for Qwen3.5 MoE."""
|
||||
config = AutoConfig.from_pretrained("Qwen/Qwen3.5-35B-A3B", trust_remote_code=True, attn_implementation="sdpa")
|
||||
config.use_cache = False
|
||||
|
||||
tc = config.text_config
|
||||
tc.vocab_size = 256
|
||||
tc.hidden_size = 256
|
||||
tc.num_hidden_layers = 2
|
||||
tc.num_attention_heads = 4
|
||||
tc.num_key_value_heads = 2
|
||||
tc.head_dim = 64
|
||||
tc.moe_intermediate_size = 128
|
||||
tc.shared_expert_intermediate_size = 128
|
||||
tc.num_experts = 4
|
||||
tc.num_experts_per_tok = 2
|
||||
tc.max_position_embeddings = 512
|
||||
tc.linear_key_head_dim = 32
|
||||
tc.linear_value_head_dim = 32
|
||||
tc.linear_num_key_heads = 4
|
||||
tc.linear_num_value_heads = 8
|
||||
tc.layer_types = ["full_attention", "linear_attention"]
|
||||
tc.use_cache = False
|
||||
|
||||
vc = config.vision_config
|
||||
vc.depth = 2
|
||||
vc.hidden_size = 128
|
||||
vc.intermediate_size = 256
|
||||
vc.num_heads = 4
|
||||
vc.out_hidden_size = tc.hidden_size
|
||||
|
||||
config.image_token_id = 250
|
||||
config.video_token_id = 251
|
||||
config.vision_start_token_id = 252
|
||||
config.vision_end_token_id = 253
|
||||
return config
|
||||
|
||||
|
||||
ARCH_PRESETS = {
|
||||
"glm4_moe": {
|
||||
"config_class": Glm4MoeConfig,
|
||||
@@ -87,6 +130,14 @@ ARCH_PRESETS = {
|
||||
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
|
||||
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
|
||||
},
|
||||
"qwen3_5_moe_vlm": {
|
||||
"config_fn": _qwen3_5_moe_vlm_config,
|
||||
"hf_model_class": HFQwen3_5MoeVLM,
|
||||
"prime_model_class": PrimeRLQwen3_5MoeVLM,
|
||||
"tokenizer_source": "Qwen/Qwen3.5-35B-A3B",
|
||||
"is_vlm": True,
|
||||
},
|
||||
# glm_moe_dsa: HF implementation is incorrect, not supported here
|
||||
}
|
||||
|
||||
|
||||
@@ -114,12 +165,20 @@ def _create_hf_model_from_config(preset, config):
|
||||
return AutoModelForCausalLM.from_config(config, trust_remote_code=True)
|
||||
|
||||
|
||||
def _build_config(preset):
|
||||
"""Build model config from preset (handles both config_class and config_fn styles)."""
|
||||
if "config_fn" in preset:
|
||||
return preset["config_fn"]()
|
||||
return preset["config_class"](**preset["config_kwargs"])
|
||||
|
||||
|
||||
def create(arch: str, output_dir: Path) -> None:
|
||||
preset = ARCH_PRESETS[arch]
|
||||
config = preset["config_class"](**preset["config_kwargs"])
|
||||
config = _build_config(preset)
|
||||
|
||||
text_config = getattr(config, "text_config", config)
|
||||
print(f"Creating mini {arch} model...")
|
||||
print(f" hidden_size={config.hidden_size}, layers={config.num_hidden_layers}")
|
||||
print(f" hidden_size={text_config.hidden_size}, layers={text_config.num_hidden_layers}")
|
||||
|
||||
with torch.device("cpu"):
|
||||
model = _create_hf_model(preset, config)
|
||||
@@ -138,14 +197,20 @@ def create(arch: str, output_dir: Path) -> None:
|
||||
|
||||
def verify(arch: str, model_dir: Path) -> None:
|
||||
preset = ARCH_PRESETS[arch]
|
||||
is_vlm = preset.get("is_vlm", False)
|
||||
print(f"Verifying HF <-> PrimeRL roundtrip for {model_dir}...")
|
||||
|
||||
trust_remote_code = preset["hf_model_class"] is None
|
||||
config = AutoConfig.from_pretrained(str(model_dir), trust_remote_code=trust_remote_code)
|
||||
config._attn_implementation = "sdpa"
|
||||
if hasattr(config, "text_config"):
|
||||
config.text_config._attn_implementation = "sdpa"
|
||||
|
||||
text_config = getattr(config, "text_config", config)
|
||||
vocab_size = text_config.vocab_size
|
||||
|
||||
hf_model = _load_hf_model(preset, model_dir, config).to(device="cuda", dtype=torch.float32)
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_model = _load_hf_model(preset, model_dir, config)
|
||||
prime_model = preset["prime_model_class"]._from_config(config)
|
||||
|
||||
with torch.no_grad():
|
||||
@@ -155,29 +220,39 @@ def verify(arch: str, model_dir: Path) -> None:
|
||||
|
||||
inject_prime_lm_head(prime_model, chunk_size=None)
|
||||
|
||||
# Use tokens in safe range (avoid special VLM token IDs)
|
||||
max_token = min(vocab_size, 200) if is_vlm else vocab_size
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
input_ids = torch.randint(0, config.vocab_size, (1, 64))
|
||||
input_ids = torch.randint(0, max_token, (1, 64))
|
||||
position_ids = torch.arange(1, 65).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids)
|
||||
hf_output = hf_model(input_ids=input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(input_ids, position_ids)
|
||||
|
||||
logits_diff = prime_output["logits"] - hf_output.logits
|
||||
max_diff = logits_diff.abs().max().item()
|
||||
print(f" HF vs PrimeRL max logits diff: {max_diff:.6f}")
|
||||
assert max_diff < 0.1, f"HF vs PrimeRL logits mismatch: max diff {max_diff}"
|
||||
if is_vlm:
|
||||
# HF GatedDeltaNet has a dtype bug in float32 mode; just verify non-NaN output
|
||||
assert not torch.isnan(prime_output["logits"]).any(), "PrimeRL VLM output contains NaN"
|
||||
assert prime_output["logits"].shape == hf_output.logits.shape
|
||||
print(" VLM forward pass verified (shape match, no NaN)")
|
||||
else:
|
||||
logits_diff = prime_output["logits"] - hf_output.logits
|
||||
max_diff = logits_diff.abs().max().item()
|
||||
print(f" HF vs PrimeRL max logits diff: {max_diff:.6f}")
|
||||
assert max_diff < 0.1, f"HF vs PrimeRL logits mismatch: max diff {max_diff}"
|
||||
|
||||
# Roundtrip weight conversion: HF -> PrimeRL -> HF
|
||||
# Normalize both through the same roundtrip to handle expert format differences
|
||||
prime_cls = preset["prime_model_class"]
|
||||
with torch.no_grad():
|
||||
roundtrip_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_roundtrip = _create_hf_model_from_config(preset, config)
|
||||
hf_roundtrip.load_state_dict(roundtrip_state_dict)
|
||||
roundtrip_sd = prime_cls.convert_to_hf(dict(prime_model.state_dict()))
|
||||
orig_sd = dict(hf_model.state_dict())
|
||||
prime_cls.convert_to_prime(orig_sd)
|
||||
prime_cls.convert_to_hf(orig_sd)
|
||||
|
||||
hf_roundtrip_output = hf_roundtrip(input_ids, position_ids)
|
||||
roundtrip_diff = hf_roundtrip_output.logits - hf_output.logits
|
||||
max_roundtrip_diff = roundtrip_diff.abs().max().item()
|
||||
print(f" HF -> PrimeRL -> HF roundtrip max logits diff: {max_roundtrip_diff:.6f}")
|
||||
assert max_roundtrip_diff < 0.1, f"Roundtrip logits mismatch: max diff {max_roundtrip_diff}"
|
||||
for key in orig_sd:
|
||||
assert key in roundtrip_sd, f"Missing key after roundtrip: {key}"
|
||||
assert torch.equal(orig_sd[key], roundtrip_sd[key]), f"Roundtrip mismatch at {key}"
|
||||
print(" HF -> PrimeRL -> HF weight roundtrip verified")
|
||||
|
||||
print(" Verification passed.")
|
||||
|
||||
|
||||
@@ -20,6 +20,64 @@ uv run inference --model.name Qwen/Qwen3-0.6B --model.max_model_len 2048 --model
|
||||
uv run inference @ path/to/config.toml --server.port 8001 --gpu-memory-utilization 0.5
|
||||
```
|
||||
|
||||
## SLURM scheduling
|
||||
|
||||
The inference entrypoint supports optional SLURM scheduling, following the same patterns as SFT and RL.
|
||||
|
||||
### Single-node SLURM
|
||||
|
||||
```toml
|
||||
# inference_slurm.toml
|
||||
output_dir = "/shared/outputs/my-inference"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-8B"
|
||||
|
||||
[parallel]
|
||||
tp = 8
|
||||
|
||||
[slurm]
|
||||
job_name = "my-inference"
|
||||
partition = "cluster"
|
||||
```
|
||||
|
||||
```bash
|
||||
uv run inference @ inference_slurm.toml
|
||||
```
|
||||
|
||||
### Multi-node SLURM (independent vLLM replicas)
|
||||
|
||||
Each node runs an independent vLLM instance. No cross-node parallelism — TP and DP must fit within a single node's GPUs.
|
||||
|
||||
```toml
|
||||
# inference_multinode.toml
|
||||
output_dir = "/shared/outputs/my-inference"
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/INTELLECT-3-RL-600"
|
||||
|
||||
[parallel]
|
||||
tp = 8
|
||||
dp = 1
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 4
|
||||
gpus_per_node = 8
|
||||
|
||||
[slurm]
|
||||
job_name = "my-inference"
|
||||
partition = "cluster"
|
||||
```
|
||||
|
||||
### Dry run
|
||||
|
||||
Add `dry_run = true` to generate the sbatch script without submitting:
|
||||
|
||||
```bash
|
||||
uv run inference @ config.toml --dry-run true
|
||||
```
|
||||
|
||||
## Custom endpoints
|
||||
|
||||
The server extends vLLM with:
|
||||
@@ -43,7 +101,9 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
|
||||
## Key files
|
||||
|
||||
- `src/prime_rl/inference/server.py` — entry point, env var setup
|
||||
- `src/prime_rl/inference/config.py` — `InferenceConfig` and all sub-configs
|
||||
- `src/prime_rl/entrypoints/inference.py` — entrypoint with local/SLURM routing
|
||||
- `src/prime_rl/inference/server.py` — vLLM env setup
|
||||
- `src/prime_rl/configs/inference.py` — `InferenceConfig` and all sub-configs
|
||||
- `src/prime_rl/inference/vllm/server.py` — FastAPI routes and vLLM monkey-patches
|
||||
- `src/prime_rl/templates/inference.sbatch.j2` — SLURM template (handles both single and multi-node)
|
||||
- `configs/debug/infer.toml` — minimal debug config
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
name: installation
|
||||
description: How to install prime-rl and its optional dependencies. Use when setting up the project, installing extras like deep-gemm for FP8 models, or troubleshooting dependency issues.
|
||||
---
|
||||
|
||||
# Installation
|
||||
|
||||
## Basic install
|
||||
|
||||
```bash
|
||||
uv sync
|
||||
```
|
||||
|
||||
This installs all core dependencies defined in `pyproject.toml`.
|
||||
|
||||
## All extras at once
|
||||
|
||||
The recommended way to install for most users:
|
||||
|
||||
```bash
|
||||
uv sync --all-extras
|
||||
```
|
||||
|
||||
This installs all optional extras (flash-attn, flash-attn-cute, etc.) in one go.
|
||||
|
||||
## Mamba-SSM (NemotronH models)
|
||||
|
||||
For NemotronH (hybrid Mamba-Transformer-MoE) models, install `mamba-ssm` for Triton-based SSD kernels that match vLLM's precision:
|
||||
|
||||
```bash
|
||||
CUDA_HOME=/usr/local/cuda uv pip install mamba-ssm
|
||||
```
|
||||
|
||||
Requires `nvcc` (CUDA toolkit). Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch implementation which computes softplus in bf16, causing ~0.4 KL divergence vs vLLM.
|
||||
|
||||
Note: do NOT install `causal-conv1d` unless your GPU architecture matches the compiled CUDA kernels. The code automatically falls back to PyTorch nn.Conv1d when it's absent.
|
||||
|
||||
## FP8 inference with deep-gemm
|
||||
|
||||
For certain models like GLM-5-FP8, you need `deep-gemm`. Install it via the `fp8-inference` dependency group:
|
||||
|
||||
```bash
|
||||
uv sync --group fp8-inference
|
||||
```
|
||||
|
||||
This installs the pre-built `deep-gemm` wheel. No CUDA build step is needed.
|
||||
|
||||
## Dev dependencies
|
||||
|
||||
```bash
|
||||
uv sync --group dev
|
||||
```
|
||||
|
||||
Installs pytest, ruff, pre-commit, and other development tools.
|
||||
|
||||
## Key files
|
||||
|
||||
- `pyproject.toml` — all dependencies, extras, and dependency groups
|
||||
- `uv.lock` — pinned lockfile (update with `uv sync --all-extras`)
|
||||
+99
-20
@@ -5,7 +5,7 @@ description: How to write and use TOML configs in prime-rl. Use when creating co
|
||||
|
||||
# TOML Config
|
||||
|
||||
All prime-rl commands use pydantic-settings with TOML configs and CLI overrides.
|
||||
All prime-rl commands use `pydantic_config` (tyro-backed) with TOML configs and CLI overrides.
|
||||
|
||||
## Running with configs
|
||||
|
||||
@@ -19,11 +19,17 @@ uv run rl @ configs/debug/rl/train.toml
|
||||
uv run inference @ config.toml --model.name Qwen/Qwen3-0.6B --server.port 8001
|
||||
|
||||
# Boolean flags: no value needed
|
||||
uv run inference --model.enforce_eager # sets to true
|
||||
uv run inference --no-model.enforce_eager # sets to false
|
||||
uv run inference --model.enforce-eager # sets to true
|
||||
uv run inference --no-model.enforce-eager # sets to false
|
||||
|
||||
# CLI-only (no TOML file)
|
||||
uv run inference --model.name Qwen/Qwen3-0.6B --model.max_model_len 2048
|
||||
uv run inference --model.name Qwen/Qwen3-0.6B --model.max-model-len 2048
|
||||
|
||||
# Compose multiple config files (later files override earlier ones)
|
||||
uv run rl @ examples/reverse_text/rl.toml @ examples/reverse_text/slurm_rl.toml
|
||||
|
||||
# Nested config files: load a config for a specific section
|
||||
uv run rl --model @ model.toml --data @ data.toml
|
||||
```
|
||||
|
||||
## TOML structure
|
||||
@@ -46,19 +52,6 @@ port = 8000
|
||||
|
||||
Putting a top-level field after a section header nests it inside that section, which causes validation errors.
|
||||
|
||||
## Config inheritance
|
||||
|
||||
Configs can inherit from other TOML files:
|
||||
|
||||
```toml
|
||||
toml_files = ["base.toml"]
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-0.6B" # overrides base
|
||||
```
|
||||
|
||||
Paths in `toml_files` are relative to the file containing the field.
|
||||
|
||||
## Setting None
|
||||
|
||||
Use the string `"None"` in TOML to set a field to None:
|
||||
@@ -67,20 +60,106 @@ 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.
|
||||
|
||||
SLURM configs are composed with the base config via CLI:
|
||||
```bash
|
||||
uv run rl @ examples/reverse_text/rl.toml @ examples/reverse_text/slurm_rl.toml
|
||||
```
|
||||
|
||||
### 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
|
||||
|
||||
## SFT Distillation (Hard Distillation) With Teacher Rollouts
|
||||
|
||||
Use this when the teacher is an external OpenAI-compatible endpoint and you want to train from teacher completions directly (no teacher token logprobs required).
|
||||
|
||||
```toml
|
||||
[trainer.loss]
|
||||
type = "sft"
|
||||
|
||||
[orchestrator]
|
||||
use_token_client = false
|
||||
|
||||
[orchestrator.teacher_rollout_model.client]
|
||||
base_url = ["https://your-openai-compatible-endpoint/v1"]
|
||||
skip_model_check = true
|
||||
|
||||
[orchestrator.teacher_rollout_model.model]
|
||||
name = "teacher-model-name"
|
||||
```
|
||||
|
||||
Notes:
|
||||
- `orchestrator.teacher_rollout_model` switches rollout generation to the external teacher endpoint.
|
||||
- `use_token_client = false` is required when `orchestrator.teacher_rollout_model` is set.
|
||||
- `trainer.loss.type = "sft"` makes the RL trainer optimize masked NLL like SFT.
|
||||
- In this mode, omit `[inference]`.
|
||||
- Image input is supported when using a VLM student model and OpenAI-style image messages (`data:image/...`).
|
||||
|
||||
## 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/utils/config.py` — `BaseConfig`, `cli`, `get_all_fields`
|
||||
- `src/prime_rl/entrypoints/rl.py` — unified RL entrypoint (local + SLURM)
|
||||
- `src/prime_rl/configs/rl.py` — `RLConfig`, `SlurmConfig, DeploymentConfig`
|
||||
- `src/prime_rl/entrypoints/sft.py` — unified SFT entrypoint (local + SLURM)
|
||||
- `src/prime_rl/configs/sft.py` — `SFTConfig`
|
||||
- `configs/` — all config files, organized by task
|
||||
|
||||
@@ -3,12 +3,12 @@ from typing import Annotated
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from prime_rl.orchestrator.config import EnvConfig
|
||||
from prime_rl.utils.config import LogConfig
|
||||
from prime_rl.utils.pydantic_config import BaseSettings
|
||||
from prime_rl.configs.orchestrator import EnvConfig
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class EnvServerConfig(BaseSettings):
|
||||
class EnvServerConfig(BaseConfig):
|
||||
"""Configures an environment server."""
|
||||
|
||||
env: EnvConfig = EnvConfig()
|
||||
@@ -1,92 +1,13 @@
|
||||
from argparse import Namespace
|
||||
from typing import Annotated, Any, Literal
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
from pydantic_config import BaseConfig
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings, get_all_fields
|
||||
from prime_rl.configs.shared import BaseModelConfig, SlurmConfig
|
||||
from prime_rl.utils.utils import rgetattr, rsetattr
|
||||
|
||||
logger = get_logger()
|
||||
|
||||
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
|
||||
# GLM-4.5
|
||||
"zai-org/GLM-4.5": "glm45",
|
||||
"zai-org/GLM-4.5-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Base": "glm45",
|
||||
"zai-org/GLM-4.5-Air": "glm45",
|
||||
"zai-org/GLM-4.5-Air-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Air-Base": "glm45",
|
||||
"zai-org/GLM-4.5V": "glm45",
|
||||
"zai-org/GLM-4.5V-FP8": "glm45",
|
||||
# GLM-4.7
|
||||
"zai-org/GLM-4.7": "glm47",
|
||||
"zai-org/GLM-4.7-FP8": "glm47",
|
||||
"zai-org/GLM-4.7-Flash": "glm47",
|
||||
# MiniMax M2
|
||||
"MiniMaxAI/MiniMax-M2": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.1": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.5": "minimax_m2",
|
||||
# INTELLECT-3
|
||||
"PrimeIntellect/INTELLECT-3": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3-FP8": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3.1": "hermes",
|
||||
# Qwen3 dense
|
||||
"Qwen/Qwen3-0.6B": "hermes",
|
||||
"Qwen/Qwen3-0.6B-Base": "hermes",
|
||||
"Qwen/Qwen3-0.6B-FP8": "hermes",
|
||||
"Qwen/Qwen3-1.7B": "hermes",
|
||||
"Qwen/Qwen3-1.7B-Base": "hermes",
|
||||
"Qwen/Qwen3-1.7B-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B": "hermes",
|
||||
"Qwen/Qwen3-4B-Base": "hermes",
|
||||
"Qwen/Qwen3-4B-FP8": "hermes",
|
||||
"Qwen/Qwen3-8B": "hermes",
|
||||
"Qwen/Qwen3-8B-Base": "hermes",
|
||||
"Qwen/Qwen3-8B-FP8": "hermes",
|
||||
"Qwen/Qwen3-14B": "hermes",
|
||||
"Qwen/Qwen3-14B-Base": "hermes",
|
||||
"Qwen/Qwen3-14B-FP8": "hermes",
|
||||
"Qwen/Qwen3-32B": "hermes",
|
||||
"Qwen/Qwen3-32B-FP8": "hermes",
|
||||
# Qwen3 MoE
|
||||
"Qwen/Qwen3-30B-A3B": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Base": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-FP8": "hermes",
|
||||
# Qwen3 2507
|
||||
"Qwen/Qwen3-4B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507-FP8": "hermes",
|
||||
# Qwen3-Next
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking-FP8": "hermes",
|
||||
# Qwen3-Coder
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8": "hermes",
|
||||
# Qwen3-Coder-Next
|
||||
"Qwen/Qwen3-Coder-Next": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-Base": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-FP8": "hermes",
|
||||
# Qwen3.5
|
||||
"Qwen/Qwen3.5-397B-A17B": "hermes",
|
||||
"Qwen/Qwen3.5-397B-A17B-FP8": "hermes",
|
||||
}
|
||||
|
||||
# TODO: Set thinking/ solution budget
|
||||
|
||||
|
||||
@@ -119,16 +40,9 @@ class ParallelConfig(BaseConfig):
|
||||
return f"tp={self.tp} dp={self.dp}"
|
||||
|
||||
|
||||
class ModelConfig(BaseConfig):
|
||||
class ModelConfig(BaseModelConfig):
|
||||
"""Configures the inference model. Most arguments are passed directly to the vLLM LLM class (https://docs.vllm.ai/en/latest/api/vllm.LLM.html)."""
|
||||
|
||||
name: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="Name or path of the HF model to use.",
|
||||
),
|
||||
] = "Qwen/Qwen3-0.6B"
|
||||
|
||||
dtype: Annotated[
|
||||
Literal["auto", "float16", "bfloat16", "float32"],
|
||||
Field(
|
||||
@@ -157,19 +71,11 @@ class ModelConfig(BaseConfig):
|
||||
),
|
||||
] = False
|
||||
|
||||
enable_auto_tool_choice: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to enable auto tool choice. Passed to vLLM as `--enable-auto-tool-choice`. "
|
||||
"Automatically set to True when tool_call_parser is configured.",
|
||||
),
|
||||
] = False
|
||||
|
||||
tool_call_parser: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
|
||||
"If not set, automatically inferred from the model name.",
|
||||
'Set to "auto" to infer from the model name.',
|
||||
),
|
||||
] = None
|
||||
|
||||
@@ -187,21 +93,8 @@ class ModelConfig(BaseConfig):
|
||||
),
|
||||
] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_tool_call_parser(self):
|
||||
if self.tool_call_parser is None:
|
||||
parser = MODEL_TOOL_CALL_PARSER.get(self.name)
|
||||
if parser is not None:
|
||||
logger.info(f"Auto-detected tool_call_parser='{parser}' for model '{self.name}'")
|
||||
self.tool_call_parser = parser
|
||||
|
||||
if self.tool_call_parser is not None:
|
||||
self.enable_auto_tool_choice = True
|
||||
|
||||
return self
|
||||
|
||||
|
||||
class WeightBroadcastConfig(BaseSettings):
|
||||
class WeightBroadcastConfig(BaseConfig):
|
||||
"""Configures weight broadcast settings."""
|
||||
|
||||
type: Annotated[Literal["nccl", "filesystem"], Field(description="The type of weight broadcast to use.")] = (
|
||||
@@ -213,15 +106,77 @@ class WeightBroadcastConfig(BaseSettings):
|
||||
# TODO: on newer vLLM, can import via `get_args(vllm.config.lora.MaxLoRARanks)`
|
||||
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
|
||||
|
||||
# vLLM all2all backend options for expert-parallel deployments.
|
||||
All2AllBackend = Literal[
|
||||
"allgather_reducescatter",
|
||||
"deepep_high_throughput",
|
||||
"deepep_low_latency",
|
||||
"flashinfer_all2allv",
|
||||
"naive",
|
||||
"pplx",
|
||||
]
|
||||
|
||||
class InferenceConfig(BaseSettings):
|
||||
|
||||
class BaseInferenceDeploymentConfig(BaseModel):
|
||||
"""Base deployment config for inference."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
|
||||
|
||||
|
||||
class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
"""Configures a single-node inference deployment."""
|
||||
|
||||
type: Literal["single_node"] = "single_node"
|
||||
|
||||
|
||||
class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
"""Configures a multi-node inference deployment. Each node runs an independent vLLM replica."""
|
||||
|
||||
type: Literal["multi_node"] = "multi_node"
|
||||
|
||||
num_nodes: Annotated[int, Field(ge=1, description="Number of inference nodes.")] = 2
|
||||
|
||||
router_port: Annotated[int, Field(description="Port for the vllm-router.")] = 8000
|
||||
backend_port: Annotated[int, Field(description="Port for vLLM backend instances.")] = 8100
|
||||
|
||||
|
||||
class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
"""Configures a disaggregated prefill/decode inference deployment.
|
||||
|
||||
Each inference replica is split into separate prefill and decode node groups.
|
||||
Requires NIXL for KV transfer and a vllm-router for request routing.
|
||||
"""
|
||||
|
||||
type: Literal["disaggregated"] = "disaggregated"
|
||||
|
||||
num_prefill_nodes: Annotated[int, Field(ge=1, description="Number of prefill nodes per replica.")] = 1
|
||||
num_decode_nodes: Annotated[int, Field(ge=1, description="Number of decode nodes per replica.")] = 1
|
||||
|
||||
router_port: Annotated[int, Field(description="Port for the vllm-router on each replica.")] = 8000
|
||||
prefill_port: Annotated[int, Field(description="Port for prefill vLLM instances.")] = 8100
|
||||
decode_port: Annotated[int, Field(description="Port for decode vLLM instances.")] = 8200
|
||||
|
||||
@property
|
||||
def num_nodes(self) -> int:
|
||||
return self.num_prefill_nodes + self.num_decode_nodes
|
||||
|
||||
|
||||
InferenceDeploymentConfig: TypeAlias = Annotated[
|
||||
SingleNodeInferenceDeploymentConfig | MultiNodeInferenceDeploymentConfig | DisaggregatedInferenceDeploymentConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class InferenceConfig(BaseConfig):
|
||||
"""Configures inference."""
|
||||
|
||||
# The server configuration
|
||||
server: ServerConfig = ServerConfig()
|
||||
|
||||
# The model configuration
|
||||
model: ModelConfig = ModelConfig()
|
||||
model: ModelConfig = Field(default_factory=ModelConfig)
|
||||
|
||||
# The parallel configuration
|
||||
parallel: ParallelConfig = ParallelConfig()
|
||||
@@ -274,11 +229,28 @@ class InferenceConfig(BaseSettings):
|
||||
api_server_count: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="The number of API servers to use. Passed to vLLM as `--api-server-count`",
|
||||
ge=0,
|
||||
description="The number of API servers to use. Passed to vLLM as `--api-server-count`. Set to 0 for headless mode.",
|
||||
),
|
||||
] = 1
|
||||
|
||||
data_parallel_size_local: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Number of data parallel replicas to run on this node. Passed to vLLM as `--data-parallel-size-local`.",
|
||||
),
|
||||
] = None
|
||||
|
||||
data_parallel_rpc_port: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
le=65535,
|
||||
description="RPC port for data parallel communication. Passed to vLLM as `--data-parallel-rpc-port`.",
|
||||
),
|
||||
] = 13345
|
||||
|
||||
seed: Annotated[
|
||||
int,
|
||||
Field(
|
||||
@@ -286,13 +258,109 @@ class InferenceConfig(BaseSettings):
|
||||
),
|
||||
] = 0
|
||||
|
||||
enable_expert_parallel: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Enable expert parallelism for MoE models. Passed to vLLM as `--enable-expert-parallel`.",
|
||||
),
|
||||
] = False
|
||||
|
||||
all2all_backend: Annotated[
|
||||
All2AllBackend,
|
||||
Field(
|
||||
description="All-to-all backend for expert parallel communication. Passed to vLLM as `--all2all-backend`.",
|
||||
),
|
||||
] = "allgather_reducescatter"
|
||||
|
||||
enable_eplb: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Enable expert parallel load balancer (EPLB). Passed to vLLM as `--enable-eplb`.",
|
||||
),
|
||||
] = False
|
||||
|
||||
use_deep_gemm: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Force DeepGEMM FP8 kernels via VLLM_USE_DEEP_GEMM=1. Only works with per-tensor FP8 quantization (e.g. GLM-5-FP8).",
|
||||
),
|
||||
] = False
|
||||
|
||||
weight_broadcast: Annotated[WeightBroadcastConfig, Field(description="The weight broadcast config.")] = (
|
||||
WeightBroadcastConfig()
|
||||
)
|
||||
|
||||
enable_return_routed_experts: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to enable return routed experts. Passed to vLLM as `--enable-return-routed-experts`",
|
||||
),
|
||||
] = False
|
||||
|
||||
vllm_extra: Annotated[
|
||||
dict[str, Any],
|
||||
Field(
|
||||
description="Extra arguments to pass to vLLM. These are applied as attributes on the vLLM namespace after config translation.",
|
||||
),
|
||||
] = {}
|
||||
|
||||
# Launcher-only fields
|
||||
|
||||
deployment: Annotated[
|
||||
InferenceDeploymentConfig,
|
||||
Field(
|
||||
description="Deployment configuration for inference.",
|
||||
),
|
||||
] = SingleNodeInferenceDeploymentConfig()
|
||||
|
||||
slurm: Annotated[
|
||||
SlurmConfig | None,
|
||||
Field(
|
||||
description="SLURM configuration. If set, the run will be submitted as a SLURM job instead of running locally.",
|
||||
),
|
||||
] = None
|
||||
|
||||
output_dir: Annotated[Path, Field(description="Directory for SLURM logs and generated scripts.")] = Path("outputs")
|
||||
|
||||
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
|
||||
|
||||
@model_validator(mode="after")
|
||||
def round_up_max_lora_rank(self):
|
||||
"""Round up max_lora_rank to the nearest valid vLLM value.
|
||||
def validate_multi_node_requires_slurm(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 auto_setup_disaggregated(self):
|
||||
"""Auto-configure inference for disaggregated P/D: enable EP and compute DP."""
|
||||
if self.deployment.type == "disaggregated":
|
||||
if "enable_expert_parallel" not in self.model_fields_set:
|
||||
self.enable_expert_parallel = True
|
||||
if "enable_eplb" not in self.model_fields_set:
|
||||
self.enable_eplb = False
|
||||
gpus_per_node = self.deployment.gpus_per_node
|
||||
tp = self.parallel.tp
|
||||
dp_per_node = gpus_per_node // tp
|
||||
if self.data_parallel_size_local is None:
|
||||
self.data_parallel_size_local = dp_per_node
|
||||
if self.parallel.dp == 1:
|
||||
self.parallel.dp = dp_per_node
|
||||
if self.api_server_count == 1:
|
||||
self.api_server_count = dp_per_node
|
||||
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"
|
||||
self.slurm.template_path = templates_dir / "inference.sbatch.j2"
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_max_lora_rank(self):
|
||||
"""Auto-setup max_lora_rank by rounding up to the nearest valid vLLM value.
|
||||
|
||||
vLLM only accepts specific values for max_lora_rank: (1, 8, 16, 32, 64, 128, 256, 320, 512).
|
||||
This validator ensures that any configured rank is rounded up to the minimum valid value
|
||||
@@ -315,8 +383,14 @@ class InferenceConfig(BaseSettings):
|
||||
size. Unless LoRA is enabled, in which case only one API server is
|
||||
supported (vLLM limitation).
|
||||
"""
|
||||
if self.api_server_count < self.parallel.dp:
|
||||
self.api_server_count = self.parallel.dp
|
||||
if self.vllm_extra.get("headless", False):
|
||||
self.api_server_count = 0
|
||||
return self
|
||||
|
||||
if "api_server_count" not in self.model_fields_set:
|
||||
min_api_server_count = self.data_parallel_size_local or self.parallel.dp
|
||||
if self.api_server_count < min_api_server_count:
|
||||
self.api_server_count = min_api_server_count
|
||||
|
||||
if self.enable_lora:
|
||||
self.api_server_count = 1 # LoRA requires only one API server
|
||||
@@ -333,12 +407,13 @@ class InferenceConfig(BaseSettings):
|
||||
"model.max_model_len": "max_model_len",
|
||||
"model.enforce_eager": "enforce_eager",
|
||||
"model.trust_remote_code": "trust_remote_code",
|
||||
"model.enable_auto_tool_choice": "enable_auto_tool_choice",
|
||||
"model.tool_call_parser": "tool_call_parser",
|
||||
"model.reasoning_parser": "reasoning_parser",
|
||||
"model.rope_scaling": "rope_scaling",
|
||||
"parallel.tp": "tensor_parallel_size",
|
||||
"parallel.dp": "data_parallel_size",
|
||||
"data_parallel_size_local": "data_parallel_size_local",
|
||||
"data_parallel_rpc_port": "data_parallel_rpc_port",
|
||||
"enable_lora": "enable_lora",
|
||||
"enable_prefix_caching": "enable_prefix_caching",
|
||||
"max_loras": "max_loras",
|
||||
@@ -346,11 +421,16 @@ class InferenceConfig(BaseSettings):
|
||||
"max_lora_rank": "max_lora_rank",
|
||||
"gpu_memory_utilization": "gpu_memory_utilization",
|
||||
"api_server_count": "api_server_count",
|
||||
"enable_return_routed_experts": "enable_return_routed_experts",
|
||||
"enable_expert_parallel": "enable_expert_parallel",
|
||||
"all2all_backend": "all2all_backend",
|
||||
"enable_eplb": "enable_eplb",
|
||||
"seed": "seed",
|
||||
}
|
||||
|
||||
for key in get_all_fields(self):
|
||||
value = rgetattr(self, key.replace("-", "_"))
|
||||
rsetattr(namespace, to_vllm.get(key, key), value)
|
||||
for config_key, vllm_key in to_vllm.items():
|
||||
value = rgetattr(self, config_key.replace("-", "_"))
|
||||
rsetattr(namespace, vllm_key, value)
|
||||
|
||||
# Set `logprobs_mode` to `processed_logprobs` by default
|
||||
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
|
||||
@@ -1,20 +1,19 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import AliasChoices, BaseModel, ConfigDict, Discriminator, Field, Tag, model_validator
|
||||
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfigType
|
||||
from prime_rl.utils.config import (
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
ClientConfig,
|
||||
FileSystemTransportConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
PrimeMonitorConfig,
|
||||
TransportConfig,
|
||||
WandbWithExtrasConfig,
|
||||
)
|
||||
from prime_rl.utils.config import (
|
||||
ModelConfig as BaseModelConfig,
|
||||
)
|
||||
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class OptimizerConfig(BaseConfig):
|
||||
@@ -288,6 +287,25 @@ class EnvConfig(BaseConfig):
|
||||
),
|
||||
),
|
||||
] = {}
|
||||
max_retries: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=0,
|
||||
description="Maximum number of times the environment will retry a failed rollout.",
|
||||
),
|
||||
] = 0
|
||||
|
||||
@property
|
||||
def resolved_name(self) -> str:
|
||||
return self.name or self.id.split("@")[0]
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env_name(self):
|
||||
if self.resolved_name == "all":
|
||||
raise ValueError(
|
||||
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class EvalEnvConfig(EnvConfig):
|
||||
@@ -313,17 +331,6 @@ class EvalEnvConfig(EnvConfig):
|
||||
),
|
||||
] = 0
|
||||
|
||||
# TODO: should live on the EnvConfig and also apply to training envs but
|
||||
# this is hard right now because we use the vf.EnvGroup which treats all
|
||||
# envs as one. for now training envs hardcode no retries, but we should
|
||||
# probably treat them like environment groups long-term
|
||||
max_retries: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Maximum number of times the environment will try to retry running a rollout.",
|
||||
),
|
||||
] = 0
|
||||
|
||||
|
||||
class ValConfig(BaseConfig):
|
||||
"""Configures the validation of the model."""
|
||||
@@ -383,6 +390,14 @@ class EvalConfig(BaseConfig):
|
||||
),
|
||||
] = False
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_env_names(self):
|
||||
env_names = [env.resolved_name for env in self.env]
|
||||
duplicates = [n for n in env_names if env_names.count(n) > 1]
|
||||
if duplicates:
|
||||
raise ValueError(f"Duplicate eval environment names: {set(duplicates)}. Each env must have a unique name.")
|
||||
return self
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
"""Configures checkpointing the orchestrator."""
|
||||
@@ -503,17 +518,6 @@ class BufferConfig(BaseConfig):
|
||||
),
|
||||
] = ["task", "prompt"]
|
||||
|
||||
skip_verification: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"Whether to skip verification of rollouts using the environment's rubric. "
|
||||
"If True, rewards are always set to 0, online_difficulty_filtering is disabled, "
|
||||
"and easy/hard thresholds are not used."
|
||||
),
|
||||
),
|
||||
] = False
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_thresholds(self):
|
||||
if self.easy_threshold is not None and self.hard_threshold is not None:
|
||||
@@ -526,33 +530,31 @@ class BufferConfig(BaseConfig):
|
||||
assert all(ratio > 0 for ratio in self.env_ratios), "All env_ratios must be positive."
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_skip_verification(self):
|
||||
"""Validate that skip_verification is not used with reward-dependent features."""
|
||||
if self.skip_verification:
|
||||
if self.online_difficulty_filtering:
|
||||
raise ValueError(
|
||||
"skip_verification cannot be True when online_difficulty_filtering is True. "
|
||||
"These features depend on rewards which are disabled when skip_verification=True."
|
||||
)
|
||||
if self.easy_threshold is not None:
|
||||
raise ValueError(
|
||||
"skip_verification cannot be True when easy_threshold is set. "
|
||||
"Easy threshold depends on rewards which are disabled when skip_verification=True."
|
||||
)
|
||||
if self.hard_threshold is not None:
|
||||
raise ValueError(
|
||||
"skip_verification cannot be True when hard_threshold is set. "
|
||||
"Hard threshold depends on rewards which are disabled when skip_verification=True."
|
||||
)
|
||||
return self
|
||||
|
||||
class VerificationConfig(BaseConfig):
|
||||
"""Configures rollout verification and rubric scoring."""
|
||||
|
||||
enabled: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"Whether to verify training rollouts using the environment rubric. "
|
||||
"If False, rewards are always set to 0."
|
||||
),
|
||||
),
|
||||
] = True
|
||||
|
||||
|
||||
class AdvantageConfig(BaseConfig):
|
||||
class DefaultAdvantageConfig(BaseModel):
|
||||
"""Config for the default advantage."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["default"] = "default"
|
||||
length_weighted_mean: bool = False
|
||||
length_shaping_alpha: Annotated[
|
||||
float | None,
|
||||
Field(description="Penalty coefficient for Group Relative Reward Rescaling (GR³). Recommended value: 0.33"),
|
||||
] = None
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseModel):
|
||||
@@ -567,15 +569,9 @@ class CustomAdvantageConfig(BaseModel):
|
||||
]
|
||||
|
||||
|
||||
def _advantage_config_discriminator(v: Any) -> str:
|
||||
if isinstance(v, dict):
|
||||
return v.get("type", "default")
|
||||
return getattr(v, "type", "default")
|
||||
|
||||
|
||||
AdvantageConfigType: TypeAlias = Annotated[
|
||||
Annotated[AdvantageConfig, Tag("default")] | Annotated[CustomAdvantageConfig, Tag("custom")],
|
||||
Discriminator(_advantage_config_discriminator),
|
||||
AdvantageConfig: TypeAlias = Annotated[
|
||||
DefaultAdvantageConfig | CustomAdvantageConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
@@ -629,7 +625,7 @@ class RepetitionFilterConfig(BaseModel):
|
||||
] = 0.99
|
||||
|
||||
|
||||
FilterConfigType: TypeAlias = Annotated[
|
||||
FilterConfig: TypeAlias = Annotated[
|
||||
GibberishFilterConfig | RepetitionFilterConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
@@ -649,9 +645,23 @@ class NCCLWeightBroadcastConfig(BaseModel):
|
||||
host: Annotated[str, Field(description="The host to use for the NCCL broadcast.")] = "localhost"
|
||||
port: Annotated[int, Field(description="The port to use for the NCCL broadcast.")] = 29501
|
||||
timeout: Annotated[int, Field(description="The timeout in seconds to use for the NCCL broadcast.")] = 1200
|
||||
quantize_in_weight_transfer: Annotated[
|
||||
bool,
|
||||
Field(description="Use kernel-format FP8 quantized NCCL transfer for weight updates."),
|
||||
] = False
|
||||
|
||||
inference_world_size: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Total number of inference GPUs across all servers. Used by init_nccl_broadcast to compute per-server rank offsets.",
|
||||
),
|
||||
] = 1
|
||||
|
||||
|
||||
WeightBroadcastConfigType: TypeAlias = FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class TeacherModelConfig(BaseConfig):
|
||||
@@ -668,7 +678,21 @@ class TeacherModelConfig(BaseConfig):
|
||||
] = ModelConfig()
|
||||
|
||||
|
||||
class OrchestratorConfig(BaseSettings):
|
||||
class TeacherRolloutModelConfig(BaseConfig):
|
||||
"""Configures an external teacher model used to generate rollout text."""
|
||||
|
||||
client: Annotated[
|
||||
ClientConfig,
|
||||
Field(description="The OAI client configuration for rollout generation."),
|
||||
] = ClientConfig()
|
||||
|
||||
model: Annotated[
|
||||
ModelConfig,
|
||||
Field(description="The model configuration for rollout generation."),
|
||||
] = ModelConfig()
|
||||
|
||||
|
||||
class OrchestratorConfig(BaseConfig):
|
||||
"""Configures the orchestrator for RL training."""
|
||||
|
||||
# The OAI client configuration
|
||||
@@ -690,6 +714,17 @@ class OrchestratorConfig(BaseSettings):
|
||||
),
|
||||
] = None
|
||||
|
||||
# External teacher rollout model configuration (optional)
|
||||
teacher_rollout_model: Annotated[
|
||||
TeacherRolloutModelConfig | None,
|
||||
Field(
|
||||
description=(
|
||||
"Optional external teacher model used for rollout generation. "
|
||||
"When set, rollouts are generated from this endpoint/model instead of the student inference server."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
# The sampling configuration
|
||||
sampling: SamplingConfig = SamplingConfig()
|
||||
|
||||
@@ -702,11 +737,14 @@ class OrchestratorConfig(BaseSettings):
|
||||
# Data buffer configuration
|
||||
buffer: BufferConfig = BufferConfig()
|
||||
|
||||
# Rollout verification configuration
|
||||
verification: VerificationConfig = VerificationConfig()
|
||||
|
||||
# The advantage configuration
|
||||
advantage: AdvantageConfigType | None = AdvantageConfig()
|
||||
advantage: AdvantageConfig | None = DefaultAdvantageConfig()
|
||||
|
||||
# Rollout filters (monitor by default, enforce optionally)
|
||||
filters: list[FilterConfigType] = [GibberishFilterConfig(), RepetitionFilterConfig()]
|
||||
filters: list[FilterConfig] = [GibberishFilterConfig(), RepetitionFilterConfig()]
|
||||
|
||||
# The logging configuration
|
||||
log: LogConfig = LogConfig()
|
||||
@@ -723,11 +761,9 @@ class OrchestratorConfig(BaseSettings):
|
||||
# The validation configuration
|
||||
val: ValConfig | None = None
|
||||
|
||||
weight_broadcast: Annotated[WeightBroadcastConfigType, Field(discriminator="type")] = (
|
||||
FileSystemWeightBroadcastConfig()
|
||||
)
|
||||
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
|
||||
|
||||
rollout_transport: Annotated[TransportConfigType, Field(discriminator="type")] = FileSystemTransportConfig()
|
||||
rollout_transport: TransportConfig = FileSystemTransportConfig()
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
@@ -751,15 +787,44 @@ class OrchestratorConfig(BaseSettings):
|
||||
),
|
||||
] = None
|
||||
|
||||
batch_size: Annotated[int, Field(ge=1, description="Number of samples to train on per step.")] = 128
|
||||
|
||||
oversampling_factor: Annotated[
|
||||
float,
|
||||
batch_size: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Factor by which to oversample the batch. Will lead to more in-flight group rollout requests at the same time.",
|
||||
description="Number of samples to train on per step (rollout-based batching). Set this OR token_batch_size.",
|
||||
),
|
||||
] = 1.0
|
||||
] = None
|
||||
|
||||
token_batch_size: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Number of tokens to train on per step (token-based batching). Set this OR batch_size.",
|
||||
),
|
||||
] = None
|
||||
|
||||
oversampling_factor: Annotated[
|
||||
float | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description=(
|
||||
"Rollout-mode batching only. Multiplier used to derive max_inflight_rollouts from batch_size "
|
||||
"when max_inflight_rollouts is unset."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
max_inflight_rollouts: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description=(
|
||||
"Maximum number of rollouts to keep in-flight. Required for token-based batching. "
|
||||
"If batch_size is set and this is unset, defaults to batch_size * oversampling_factor "
|
||||
"(or batch_size when oversampling_factor is unset)."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
rollouts_per_example: Annotated[
|
||||
int,
|
||||
@@ -825,6 +890,13 @@ class OrchestratorConfig(BaseSettings):
|
||||
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
|
||||
] = None
|
||||
|
||||
use_token_client: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to use the token-in-token-out (TITO) client for training across all environments. WARNING: Only use this if your environment has a linear history and the chat template has the extension property (i.e. no tokens are ever removed or inserted by the chat template)"
|
||||
),
|
||||
] = True
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_filter_types(self):
|
||||
types = [f.type for f in self.filters]
|
||||
@@ -846,9 +918,43 @@ class OrchestratorConfig(BaseSettings):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_batch_size(self):
|
||||
if self.batch_size % self.rollouts_per_example != 0:
|
||||
raise ValueError("Batch size must be divisible by the number of samples per problem")
|
||||
def resolve_batching(self):
|
||||
has_rollout_batch = self.batch_size is not None
|
||||
has_token_batch = self.token_batch_size is not None
|
||||
|
||||
if has_rollout_batch and has_token_batch:
|
||||
raise ValueError("Set exactly one of batch_size or token_batch_size")
|
||||
|
||||
if not has_rollout_batch and not has_token_batch:
|
||||
self.batch_size = 128
|
||||
|
||||
if has_token_batch:
|
||||
if self.oversampling_factor is not None:
|
||||
raise ValueError("oversampling_factor can only be set when batch_size is set")
|
||||
if self.max_inflight_rollouts is None:
|
||||
raise ValueError("max_inflight_rollouts must be set when token_batch_size is set")
|
||||
else:
|
||||
assert self.batch_size is not None
|
||||
if self.batch_size % self.rollouts_per_example != 0:
|
||||
raise ValueError("Batch size must be divisible by the number of samples per problem")
|
||||
if self.max_inflight_rollouts is not None and self.oversampling_factor is not None:
|
||||
expected_max_inflight_rollouts = int(self.batch_size * self.oversampling_factor)
|
||||
if self.max_inflight_rollouts != expected_max_inflight_rollouts:
|
||||
raise ValueError("max_inflight_rollouts conflicts with oversampling_factor * batch_size")
|
||||
if self.max_inflight_rollouts is None:
|
||||
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
|
||||
self.max_inflight_rollouts = int(self.batch_size * oversampling_factor)
|
||||
|
||||
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.rollouts_per_example:
|
||||
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_env_names(self):
|
||||
env_names = [env.resolved_name for env in self.env]
|
||||
duplicates = [n for n in env_names if env_names.count(n) > 1]
|
||||
if duplicates:
|
||||
raise ValueError(f"Duplicate environment names: {set(duplicates)}. Each env must have a unique name.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -857,6 +963,35 @@ class OrchestratorConfig(BaseSettings):
|
||||
assert len(self.buffer.env_ratios) == len(self.env), "env_ratios length must match number of environments"
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_verification_config(self):
|
||||
if self.verification.enabled:
|
||||
return self
|
||||
|
||||
if self.buffer.online_difficulty_filtering:
|
||||
raise ValueError(
|
||||
"verification.enabled cannot be False when buffer.online_difficulty_filtering is True. "
|
||||
"These features depend on rewards which are disabled when verification.enabled=False."
|
||||
)
|
||||
if self.buffer.easy_threshold is not None:
|
||||
raise ValueError(
|
||||
"verification.enabled cannot be False when buffer.easy_threshold is set. "
|
||||
"Easy threshold depends on rewards which are disabled when verification.enabled=False."
|
||||
)
|
||||
if self.buffer.hard_threshold is not None:
|
||||
raise ValueError(
|
||||
"verification.enabled cannot be False when buffer.hard_threshold is set. "
|
||||
"Hard threshold depends on rewards which are disabled when verification.enabled=False."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_length_shaping_requires_online_difficulty_filtering(self):
|
||||
if isinstance(self.advantage, DefaultAdvantageConfig) and self.advantage.length_shaping_alpha is not None:
|
||||
if not self.buffer.online_difficulty_filtering:
|
||||
raise ValueError("Group Relative Reward (GR³) scaling requires online difficulty filtering")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench:
|
||||
@@ -875,8 +1010,8 @@ class OrchestratorConfig(BaseSettings):
|
||||
@model_validator(mode="after")
|
||||
def resolve_extra_env_kwargs(self):
|
||||
train_extra_env_kwargs = dict(
|
||||
seq_len=self.seq_len,
|
||||
score_rollouts=not self.buffer.skip_verification,
|
||||
max_seq_len=self.seq_len,
|
||||
score_rollouts=self.verification.enabled,
|
||||
)
|
||||
for env in self.env:
|
||||
# extra_env_kwargs is not meant to be used by the user, we shamelessly override here
|
||||
@@ -0,0 +1,882 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.configs.orchestrator import (
|
||||
CheckpointConfig as OrchestratorCheckpointConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
OrchestratorConfig,
|
||||
)
|
||||
from prime_rl.configs.shared import (
|
||||
SlurmConfig,
|
||||
VLMConfig,
|
||||
WandbConfig,
|
||||
WandbWithExtrasConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
BenchConfig,
|
||||
FakeDataLoaderConfig,
|
||||
TrainerConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
CheckpointConfig as TrainerCheckpointConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.validation import (
|
||||
validate_shared_ckpt_config,
|
||||
validate_shared_max_async_level,
|
||||
validate_shared_max_steps,
|
||||
validate_shared_model_name,
|
||||
validate_shared_output_dir,
|
||||
validate_shared_wandb_config,
|
||||
validate_shared_weight_broadcast,
|
||||
)
|
||||
|
||||
|
||||
class SharedLogConfig(BaseConfig):
|
||||
"""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(BaseConfig):
|
||||
"""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
|
||||
|
||||
shared: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Use shared W&B mode to log trainer and orchestrator metrics to a single run. "
|
||||
"Requires wandb SDK >= 0.19.9. Incompatible with offline mode.",
|
||||
),
|
||||
] = True
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_shared_not_offline(self):
|
||||
if self.shared and self.offline:
|
||||
raise ValueError("W&B shared mode requires server connectivity and is incompatible with offline mode")
|
||||
return self
|
||||
|
||||
|
||||
class SharedCheckpointConfig(BaseConfig):
|
||||
"""Configures shared checkpoint configs."""
|
||||
|
||||
output_dir: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer output_dir.",
|
||||
),
|
||||
] = None
|
||||
|
||||
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(BaseConfig):
|
||||
"""Configures shared model settings."""
|
||||
|
||||
name: Annotated[
|
||||
str,
|
||||
Field(description="The name of the model to use."),
|
||||
] = "Qwen/Qwen3-0.6B"
|
||||
|
||||
vlm: Annotated[
|
||||
"VLMConfig | None",
|
||||
Field(description="VLM configuration. Set to enable vision-language model support."),
|
||||
] = None
|
||||
|
||||
|
||||
class SharedWeightBroadcastConfig(BaseConfig):
|
||||
"""Configures shared weight broadcast settings."""
|
||||
|
||||
type: Annotated[Literal["nccl", "filesystem"], Field(description="The type of weight broadcast to use.")] = (
|
||||
"filesystem"
|
||||
)
|
||||
|
||||
port: Annotated[int, Field(description="The port to use for NCCL weight broadcast.")] = 29501
|
||||
timeout: Annotated[int, Field(description="The timeout in seconds for NCCL weight broadcast.")] = 1200
|
||||
quantize_in_weight_transfer: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"Use kernel-format FP8 quantized NCCL transfer for weight updates. "
|
||||
"When disabled, uses default HF checkpoint-format transfer."
|
||||
),
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class BaseDeploymentConfig(BaseModel):
|
||||
"""Configures a base deployment."""
|
||||
|
||||
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 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(
|
||||
ge=0,
|
||||
description="Number of inference nodes per replica. Set to 0 to skip inference and orchestrator (requires fake data).",
|
||||
),
|
||||
]
|
||||
num_infer_replicas: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Number of independent inference replicas. Total inference nodes = num_infer_nodes * num_infer_replicas.",
|
||||
),
|
||||
] = 1
|
||||
num_teacher_nodes: Annotated[int | None, Field(description="Number of teacher inference nodes.")] = None
|
||||
|
||||
nodes_per_fsdp_group: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="Number of training nodes per FSDP island. Auto-sets trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group."
|
||||
),
|
||||
] = None
|
||||
|
||||
@property
|
||||
def total_infer_nodes(self) -> int:
|
||||
return self.num_infer_nodes * self.num_infer_replicas
|
||||
|
||||
@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
|
||||
|
||||
|
||||
DeploymentConfig: TypeAlias = Annotated[
|
||||
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class RLConfig(BaseConfig):
|
||||
"""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,
|
||||
Field(
|
||||
description="The directory to store the outputs. Should be set to a unique directory identifying the experiment."
|
||||
),
|
||||
] = Path("outputs")
|
||||
|
||||
clean_output_dir: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If true, delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming.",
|
||||
),
|
||||
] = False
|
||||
|
||||
### Shared configurations
|
||||
|
||||
log: Annotated[
|
||||
SharedLogConfig,
|
||||
Field(
|
||||
description="Shared log configs. If None, will fallback to the log configs specified on submodule configs."
|
||||
),
|
||||
] = SharedLogConfig()
|
||||
|
||||
ckpt: Annotated[
|
||||
SharedCheckpointConfig | None,
|
||||
Field(
|
||||
description="Shared checkpoint configs. If None, will fallback to the checkpoint configs specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
|
||||
wandb: Annotated[
|
||||
SharedWandbConfig | None,
|
||||
Field(
|
||||
description="Shared W&B configs. If None, will fallback to the W&B configs specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
|
||||
model: Annotated[
|
||||
SharedModelConfig | None,
|
||||
Field(
|
||||
description="Shared model configs. If None, will fallback to the model configs specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
|
||||
max_steps: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="The maximum number of steps to train for. If None, will fallback to the max steps specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
|
||||
max_model_len: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="The maximum model length to use. If None, will fallback to the max model length specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
|
||||
seq_len: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="Shared sequence length. Propagates to trainer.model.seq_len and orchestrator.seq_len, "
|
||||
"but only for those not explicitly set in the config. "
|
||||
"Explicitly set per-component values always take precedence."
|
||||
),
|
||||
] = None
|
||||
|
||||
max_async_level: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="The async level to use. If None, will fallback to the async level specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
|
||||
weight_broadcast: Annotated[
|
||||
SharedWeightBroadcastConfig | None, Field(description="The weight broadcast config.")
|
||||
] = None
|
||||
|
||||
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
|
||||
|
||||
deployment: DeploymentConfig = SingleNodeDeploymentConfig()
|
||||
|
||||
slurm: Annotated[SlurmConfig | None, Field(description="SLURM configuration. If None, will run locally.")] = None
|
||||
|
||||
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
|
||||
|
||||
### 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 self.deployment.num_infer_nodes > 0 and not self.inference:
|
||||
raise ValueError("Must configure inference when using multi-node deployment with inference nodes.")
|
||||
if self.deployment.num_infer_nodes == 0 and self.inference:
|
||||
raise ValueError(
|
||||
"Cannot configure inference with num_infer_nodes = 0. "
|
||||
"Either set num_infer_nodes > 0 or remove the inference config."
|
||||
)
|
||||
if self.deployment.num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
|
||||
raise ValueError(
|
||||
"Must use fake data (trainer.data.fake or bench = true) when num_infer_nodes = 0, "
|
||||
"since no orchestrator or inference server will be running."
|
||||
)
|
||||
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_quantize_in_weight_transfer(self):
|
||||
if self.weight_broadcast is None or not self.weight_broadcast.quantize_in_weight_transfer:
|
||||
return self
|
||||
|
||||
if self.weight_broadcast.type != "nccl":
|
||||
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires weight_broadcast.type = 'nccl'.")
|
||||
|
||||
if self.inference is None:
|
||||
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires an inference config.")
|
||||
|
||||
if self.trainer.model.impl != "custom":
|
||||
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires trainer.model.impl = 'custom'.")
|
||||
|
||||
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
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_external_rollout_mode(self):
|
||||
if self.orchestrator.teacher_rollout_model is None:
|
||||
return self
|
||||
|
||||
if self.trainer.loss.type != "sft":
|
||||
raise ValueError('orchestrator.teacher_rollout_model is only supported when trainer.loss.type = "sft".')
|
||||
|
||||
if self.inference is not None:
|
||||
raise ValueError(
|
||||
"inference must be omitted when orchestrator.teacher_rollout_model is configured. "
|
||||
"External rollout mode does not use the local inference server."
|
||||
)
|
||||
|
||||
if self.orchestrator.use_token_client:
|
||||
raise ValueError(
|
||||
"orchestrator.use_token_client must be false when orchestrator.teacher_rollout_model is configured."
|
||||
)
|
||||
|
||||
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."""
|
||||
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
|
||||
self.orchestrator.log.level = self.log.level
|
||||
if self.log.file is not None:
|
||||
self.trainer.log.file = self.log.file
|
||||
self.orchestrator.log.file = self.log.file
|
||||
self.trainer.log.json_logging = self.log.json_logging
|
||||
self.orchestrator.log.json_logging = self.log.json_logging
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_ckpt(self):
|
||||
"""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:
|
||||
self.trainer.ckpt = TrainerCheckpointConfig()
|
||||
if self.orchestrator.ckpt is None:
|
||||
self.orchestrator.ckpt = OrchestratorCheckpointConfig()
|
||||
|
||||
# If specified, override checkpoint output directory
|
||||
if self.ckpt.output_dir is not None:
|
||||
self.trainer.ckpt.output_dir = self.ckpt.output_dir
|
||||
|
||||
# If specified, use the same ckpt interval
|
||||
if self.ckpt.interval is not None:
|
||||
self.trainer.ckpt.interval = self.ckpt.interval
|
||||
self.orchestrator.ckpt.interval = self.ckpt.interval
|
||||
|
||||
# If resuming training, ensure orchestrator resume from the same step
|
||||
if self.ckpt.resume_step is not None:
|
||||
self.trainer.ckpt.resume_step = self.ckpt.resume_step
|
||||
self.orchestrator.ckpt.resume_step = self.ckpt.resume_step
|
||||
|
||||
# If specified, propagate keep policy
|
||||
if self.ckpt.keep_last is not None:
|
||||
self.trainer.ckpt.keep_last = self.ckpt.keep_last
|
||||
self.orchestrator.ckpt.keep_last = self.ckpt.keep_last
|
||||
|
||||
if self.ckpt.keep_interval is not None:
|
||||
self.trainer.ckpt.keep_interval = self.ckpt.keep_interval
|
||||
self.orchestrator.ckpt.keep_interval = self.ckpt.keep_interval
|
||||
|
||||
validate_shared_ckpt_config(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_wandb(self):
|
||||
"""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()
|
||||
if not self.orchestrator.wandb:
|
||||
self.orchestrator.wandb = WandbWithExtrasConfig()
|
||||
|
||||
if self.wandb.project:
|
||||
self.trainer.wandb.project = self.wandb.project
|
||||
self.orchestrator.wandb.project = self.wandb.project
|
||||
|
||||
if self.wandb.shared:
|
||||
if self.wandb.name:
|
||||
self.trainer.wandb.name = self.wandb.name
|
||||
self.orchestrator.wandb.name = self.wandb.name
|
||||
else:
|
||||
if self.wandb.name:
|
||||
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
|
||||
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
|
||||
|
||||
if self.wandb.offline:
|
||||
self.trainer.wandb.offline = self.wandb.offline
|
||||
self.orchestrator.wandb.offline = self.wandb.offline
|
||||
|
||||
validate_shared_wandb_config(self.trainer, self.orchestrator)
|
||||
|
||||
if self.orchestrator.prime_monitor is not None and self.orchestrator.prime_monitor.run_name is None:
|
||||
if self.wandb and self.wandb.name:
|
||||
self.orchestrator.prime_monitor.run_name = self.wandb.name
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_model(self):
|
||||
"""Auto-setup shared model config for trainer, orchestrator, and inference."""
|
||||
if self.model is not None:
|
||||
self.trainer.model.name = self.model.name
|
||||
if self.inference is not None:
|
||||
inference_model_explicitly_set = "name" in self.inference.model.model_fields_set
|
||||
if not inference_model_explicitly_set:
|
||||
self.inference.model.name = self.model.name
|
||||
self.orchestrator.model.name = self.inference.model.name
|
||||
else:
|
||||
self.orchestrator.model.name = self.model.name
|
||||
|
||||
if self.model.vlm is not None:
|
||||
self.trainer.model.vlm = self.model.vlm
|
||||
self.orchestrator.model.vlm = self.model.vlm
|
||||
if self.inference is not None:
|
||||
self.inference.model.vlm = self.model.vlm
|
||||
|
||||
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_max_steps(self):
|
||||
"""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
|
||||
|
||||
validate_shared_max_steps(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_async_level(self):
|
||||
"""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
|
||||
|
||||
validate_shared_max_async_level(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_seq_len(self):
|
||||
"""Auto-setup shared seq_len for trainer and orchestrator.
|
||||
|
||||
Only propagates to components that weren't explicitly set in the config.
|
||||
Uses model_fields_set to detect explicit assignment.
|
||||
"""
|
||||
if self.seq_len is not None:
|
||||
if "seq_len" not in self.trainer.model.model_fields_set:
|
||||
self.trainer.model.seq_len = self.seq_len
|
||||
if "seq_len" not in self.orchestrator.model_fields_set:
|
||||
self.orchestrator.seq_len = self.seq_len
|
||||
|
||||
if self.trainer.model.seq_len < self.orchestrator.seq_len:
|
||||
raise ValueError(
|
||||
f"Trainer model seq_len ({self.trainer.model.seq_len}) must be >= orchestrator seq_len ({self.orchestrator.seq_len}). "
|
||||
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@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
|
||||
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
inference_world_size=inference_world_size,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
inference_world_size=inference_world_size,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
elif self.weight_broadcast.type == "filesystem":
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
|
||||
if self.inference is not None:
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
|
||||
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
|
||||
|
||||
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 or 32,
|
||||
)
|
||||
|
||||
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.configs.orchestrator 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:
|
||||
get_logger().warning(
|
||||
"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_session_headers(self):
|
||||
"""Auto-configure X-Session-ID header for sticky routing at the inference router."""
|
||||
if "extra_headers_from_state" not in self.orchestrator.client.model_fields_set:
|
||||
self.orchestrator.client.extra_headers_from_state = {"X-Session-ID": "example_id"}
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_router_replay(self):
|
||||
if self.trainer.enable_router_replay:
|
||||
if self.inference is not None:
|
||||
if self.inference.enable_return_routed_experts is False:
|
||||
get_logger().warning(
|
||||
"Router replay is enabled, but inference.enable_return_routed_experts is False. Setting to True."
|
||||
)
|
||||
self.inference.enable_return_routed_experts = True
|
||||
else:
|
||||
get_logger().warning(
|
||||
"Router replay is enabled, but inference is not configured. When manually starting the inference server, make sure to pass `--enable-return-routed-experts` to the vLLM server."
|
||||
)
|
||||
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.inference is not None
|
||||
and self.inference.enable_expert_parallel
|
||||
and self.inference.deployment.type != "disaggregated"
|
||||
):
|
||||
inference_tp = self.inference.parallel.tp
|
||||
if self.deployment.gpus_per_node % inference_tp != 0:
|
||||
raise ValueError(
|
||||
"deployment.gpus_per_node must be divisible by inference.parallel.tp "
|
||||
"when inference.enable_expert_parallel is enabled in multi-node deployment."
|
||||
)
|
||||
|
||||
inferred_dp_local = self.deployment.gpus_per_node // inference_tp
|
||||
total_infer_gpus = self.deployment.num_infer_nodes * self.deployment.gpus_per_node
|
||||
expected_global_world_size = self.inference.parallel.dp * inference_tp
|
||||
if expected_global_world_size != total_infer_gpus:
|
||||
raise ValueError(
|
||||
"For multi-node expert parallel inference, inference.parallel.dp * inference.parallel.tp "
|
||||
f"must match total inference GPUs ({total_infer_gpus}), got {expected_global_world_size}."
|
||||
)
|
||||
|
||||
if self.inference.data_parallel_size_local is None:
|
||||
self.inference.data_parallel_size_local = inferred_dp_local
|
||||
elif self.inference.data_parallel_size_local != inferred_dp_local:
|
||||
raise ValueError(
|
||||
"inference.data_parallel_size_local must equal deployment.gpus_per_node / inference.parallel.tp "
|
||||
f"({inferred_dp_local}) when inference.enable_expert_parallel is enabled in multi-node deployment."
|
||||
)
|
||||
|
||||
if not self.inference.enable_lora and self.inference.api_server_count == self.inference.parallel.dp:
|
||||
self.inference.api_server_count = inferred_dp_local
|
||||
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
|
||||
total_infer_gpus = self.deployment.gpus_per_node * self.deployment.total_infer_nodes
|
||||
assert self.trainer.weight_broadcast.type == "nccl"
|
||||
self.trainer.weight_broadcast.host = "0.0.0.0"
|
||||
self.trainer.weight_broadcast.inference_world_size = total_infer_gpus
|
||||
assert self.orchestrator.weight_broadcast.type == "nccl"
|
||||
self.orchestrator.weight_broadcast.inference_world_size = total_infer_gpus
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_disaggregated_inference(self):
|
||||
"""Auto-setup for disaggregated P/D inference within a multi-node deployment."""
|
||||
if self.inference is None or self.inference.deployment.type != "disaggregated":
|
||||
return self
|
||||
if self.deployment.type != "multi_node":
|
||||
return self
|
||||
|
||||
infer_deploy = self.inference.deployment
|
||||
expected_infer_nodes = infer_deploy.num_prefill_nodes + infer_deploy.num_decode_nodes
|
||||
if self.deployment.num_infer_nodes != expected_infer_nodes:
|
||||
raise ValueError(
|
||||
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
|
||||
f"inference.deployment.num_prefill_nodes ({infer_deploy.num_prefill_nodes}) + "
|
||||
f"inference.deployment.num_decode_nodes ({infer_deploy.num_decode_nodes}) = {expected_infer_nodes}"
|
||||
)
|
||||
|
||||
total_infer_gpus = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
|
||||
assert self.trainer.weight_broadcast.type == "nccl"
|
||||
self.trainer.weight_broadcast.inference_world_size = total_infer_gpus
|
||||
assert self.orchestrator.weight_broadcast.type == "nccl"
|
||||
self.orchestrator.weight_broadcast.inference_world_size = total_infer_gpus
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_dp_rank_count(self):
|
||||
"""Auto-set orchestrator client dp_rank_count from inference DP size.
|
||||
|
||||
Uses data_parallel_size_local (per-node DP) when set, since each base URL
|
||||
points to a single node whose API server only knows about its local ranks.
|
||||
Falls back to the global parallel.dp for single-node setups.
|
||||
"""
|
||||
if self.inference is not None and "dp_rank_count" not in self.orchestrator.client.model_fields_set:
|
||||
self.orchestrator.client.dp_rank_count = (
|
||||
self.inference.data_parallel_size_local or self.inference.parallel.dp
|
||||
)
|
||||
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.configs.orchestrator 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
|
||||
@@ -1,20 +1,25 @@
|
||||
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 (
|
||||
from prime_rl.configs.shared import (
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
SlurmConfig,
|
||||
WandbConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
AdamWConfig,
|
||||
BenchConfig,
|
||||
CheckpointConfig,
|
||||
ConstantSchedulerConfig,
|
||||
ModelConfig,
|
||||
OptimizerConfigType,
|
||||
SchedulerConfigType,
|
||||
OptimizerConfig,
|
||||
SchedulerConfig,
|
||||
TokenizerConfig,
|
||||
)
|
||||
from prime_rl.utils.config import HeartbeatConfig, LogConfig, WandbConfig
|
||||
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class BaseDataConfig(BaseModel):
|
||||
@@ -101,10 +106,58 @@ class SFTDataConfig(BaseDataConfig):
|
||||
return self
|
||||
|
||||
|
||||
DataConfigType: TypeAlias = FakeDataConfig | SFTDataConfig
|
||||
class SFTValConfig(BaseConfig):
|
||||
interval: Annotated[int, Field(ge=1, description="Run validation every N training steps.")] = 50
|
||||
eval_on_start: Annotated[bool, Field(description="Run validation before the first training step.")] = False
|
||||
data: SFTDataConfig
|
||||
|
||||
|
||||
class SFTTrainerConfig(BaseSettings):
|
||||
DataConfig: TypeAlias = Annotated[FakeDataConfig | SFTDataConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
SFTDeploymentConfig: TypeAlias = Annotated[
|
||||
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class SFTConfig(BaseConfig):
|
||||
"""Configures the SFT trainer"""
|
||||
|
||||
# The model configuration
|
||||
@@ -114,13 +167,16 @@ class SFTTrainerConfig(BaseSettings):
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
# The data configuration
|
||||
data: Annotated[DataConfigType, Field(discriminator="type")] = SFTDataConfig()
|
||||
data: DataConfig = SFTDataConfig()
|
||||
|
||||
# Optional validation configuration
|
||||
val: SFTValConfig | None = None
|
||||
|
||||
# The optimizer configuration
|
||||
optim: Annotated[OptimizerConfigType, Field(discriminator="type")] = AdamWConfig()
|
||||
optim: OptimizerConfig = AdamWConfig()
|
||||
|
||||
# The learning rate scheduler configuration
|
||||
scheduler: Annotated[SchedulerConfigType, Field(discriminator="type")] = ConstantSchedulerConfig()
|
||||
scheduler: SchedulerConfig = ConstantSchedulerConfig()
|
||||
|
||||
# The checkpoint configuration
|
||||
ckpt: CheckpointConfig | None = None
|
||||
@@ -138,6 +194,13 @@ class SFTTrainerConfig(BaseSettings):
|
||||
),
|
||||
] = Path("outputs")
|
||||
|
||||
clean_output_dir: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If true, delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming.",
|
||||
),
|
||||
] = False
|
||||
|
||||
max_steps: Annotated[
|
||||
int | None,
|
||||
Field(description="Maximum number of steps to run training for. If None, will run indefinitely."),
|
||||
@@ -162,44 +225,82 @@ class SFTTrainerConfig(BaseSettings):
|
||||
] = 600
|
||||
|
||||
loss_impl: Annotated[
|
||||
Literal["liger", "torch"], Field(description="Implementation of the cross entropy loss function to use.")
|
||||
Literal["liger", "torch", "liger_fused"],
|
||||
Field(
|
||||
description="Implementation of the cross entropy loss function to use. "
|
||||
"'liger_fused' fuses the lm_head projection with the CE loss to avoid materializing full logits."
|
||||
),
|
||||
] = "torch"
|
||||
|
||||
heartbeat: Annotated[
|
||||
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
|
||||
] = None
|
||||
|
||||
deployment: SFTDeploymentConfig = SingleNodeDeploymentConfig()
|
||||
|
||||
slurm: Annotated[
|
||||
SlurmConfig | None,
|
||||
Field(
|
||||
description="SLURM configuration. If set, the run will be submitted as a SLURM job instead of running locally.",
|
||||
),
|
||||
] = None
|
||||
|
||||
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
|
||||
|
||||
### 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_pack_function(self):
|
||||
if self.model.cp > 1 and self.data.pack_function != "cat":
|
||||
raise ValueError("Packing function must be 'cat' when CP is enabled")
|
||||
if self.model.cp > 1:
|
||||
if self.data.pack_function != "cat":
|
||||
raise ValueError("Packing function must be 'cat' when CP is enabled")
|
||||
if self.val is not None and self.val.data.pack_function != "cat":
|
||||
raise ValueError("Validation packing function must be 'cat' when CP is enabled")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_cp_seq_len(self):
|
||||
if self.model.cp > 1 and self.data.seq_len % self.model.cp != 0:
|
||||
raise ValueError("Sequence length must be divisible by CP degree")
|
||||
if self.model.cp > 1:
|
||||
if self.data.seq_len % self.model.cp != 0:
|
||||
raise ValueError("Sequence length must be divisible by CP degree")
|
||||
if self.val is not None and self.val.data.seq_len % self.model.cp != 0:
|
||||
raise ValueError("Validation sequence length must be divisible by CP degree")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_cp_micro_batch_size(self):
|
||||
if self.model.cp > 1 and self.data.micro_batch_size != 1:
|
||||
raise ValueError("Micro batch size must be 1 when CP is enabled")
|
||||
if self.model.cp > 1:
|
||||
if self.data.micro_batch_size != 1:
|
||||
raise ValueError("Micro batch size must be 1 when CP is enabled")
|
||||
if self.val is not None and self.val.data.micro_batch_size != 1:
|
||||
raise ValueError("Validation micro batch size must be 1 when CP is enabled")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_seq_len(self):
|
||||
if self.data.pack_function == "stack":
|
||||
if self.data.seq_len % 256 != 0:
|
||||
raise ValueError("The sequence length must be divisible by 256 when using pack function stack")
|
||||
if self.data.pack_function == "stack" and self.data.seq_len % 256 != 0:
|
||||
raise ValueError("The sequence length must be divisible by 256 when using pack function stack")
|
||||
if self.val is not None and self.val.data.pack_function == "stack" and self.val.data.seq_len % 256 != 0:
|
||||
raise ValueError("The validation sequence length must be divisible by 256 when using pack function stack")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -230,22 +331,15 @@ 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):
|
||||
if isinstance(self.model.fused_lm_head_token_chunk_size, int):
|
||||
raise ValueError(
|
||||
"Chunked loss is not supported for SFT training yet, please set `model.fused_lm_head_chunk_size` to 'disabled'"
|
||||
"Chunked loss is not supported for SFT training yet, please set "
|
||||
"`model.fused_lm_head_token_chunk_size` to 'disabled'"
|
||||
)
|
||||
|
||||
self.model.fused_lm_head_chunk_size = "disabled"
|
||||
self.model.fused_lm_head_token_chunk_size = "disabled"
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -254,3 +348,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
|
||||
@@ -0,0 +1,461 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class SlurmConfig(BaseConfig):
|
||||
"""Configures SLURM scheduling."""
|
||||
|
||||
job_name: Annotated[str, Field(description="The SLURM job name.")] = "prime-rl"
|
||||
|
||||
project_dir: Annotated[
|
||||
Path,
|
||||
Field(description="Path to the project root. Used to source .env, activate .venv, and run uv sync."),
|
||||
] = Path(".")
|
||||
|
||||
template_path: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="The path to the SLURM template file. If None, will use the default single-node/multi-node template."
|
||||
),
|
||||
] = None
|
||||
|
||||
partition: Annotated[
|
||||
str, Field(description="The SLURM partition to use. Will be passed as #SBATCH --partition.")
|
||||
] = "cluster"
|
||||
|
||||
nodelist: Annotated[
|
||||
str | None,
|
||||
Field(description="Comma-separated list of specific nodes to run on. Passed as #SBATCH --nodelist."),
|
||||
] = None
|
||||
|
||||
exclude: Annotated[
|
||||
str | None,
|
||||
Field(description="Comma-separated list of nodes to exclude. Passed as #SBATCH --exclude."),
|
||||
] = None
|
||||
|
||||
account: Annotated[
|
||||
str | None,
|
||||
Field(description="SLURM account to charge. Passed as #SBATCH --account."),
|
||||
] = None
|
||||
|
||||
time: Annotated[
|
||||
str | None,
|
||||
Field(description="Maximum wall time (e.g. '24:00:00', '7-00:00:00'). Passed as #SBATCH --time."),
|
||||
] = None
|
||||
|
||||
pre_run_command: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="Shell command to run on the head node before starting the job. "
|
||||
"Runs after cd into project dir, .env sourcing, and venv activation. "
|
||||
"Useful for cleanup routines like 'sudo pkill -f vllm'. "
|
||||
"To run on all nodes, wrap with srun: 'srun bash -c \"pkill -f vllm || true\"'.",
|
||||
),
|
||||
] = None
|
||||
|
||||
@property
|
||||
def template_vars(self) -> dict:
|
||||
"""Common template variables for all SLURM templates."""
|
||||
return {
|
||||
"job_name": self.job_name,
|
||||
"project_dir": self.project_dir,
|
||||
"partition": self.partition,
|
||||
"nodelist": self.nodelist,
|
||||
"exclude": self.exclude,
|
||||
"account": self.account,
|
||||
"time": self.time,
|
||||
"pre_run_command": self.pre_run_command,
|
||||
}
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_project_dir(self):
|
||||
self.project_dir = self.project_dir.resolve()
|
||||
return self
|
||||
|
||||
|
||||
ServerType = Literal["vllm", "openai"]
|
||||
|
||||
|
||||
class VLMConfig(BaseConfig):
|
||||
"""Configures vision-language model support.
|
||||
|
||||
Presence of this config enables VLM mode. You must specify where the
|
||||
vision encoder and language model live on the model object.
|
||||
|
||||
Usage:
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
"""
|
||||
|
||||
vision_encoder_attr: Annotated[
|
||||
str,
|
||||
Field(description="Dotted attribute path to the vision encoder module (e.g. 'model.visual')."),
|
||||
]
|
||||
|
||||
language_model_attr: Annotated[
|
||||
str,
|
||||
Field(description="Dotted attribute path to the language model module (e.g. 'model.language_model')."),
|
||||
]
|
||||
|
||||
|
||||
class BaseModelConfig(BaseConfig):
|
||||
"""Configures the model."""
|
||||
|
||||
name: Annotated[str, Field(description="Name or path of the HF model to use.")] = "Qwen/Qwen3-0.6B"
|
||||
|
||||
trust_remote_code: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to trust remote code for tokenizer initialization.",
|
||||
),
|
||||
] = False
|
||||
|
||||
vlm: Annotated[
|
||||
"VLMConfig | None",
|
||||
Field(
|
||||
description="VLM configuration. Set this to enable vision-language model support.",
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class ElasticConfig(BaseConfig):
|
||||
"""Configures elastic inference pool with DNS-based service discovery.
|
||||
|
||||
Works with any DNS hostname that resolves to multiple IP addresses.
|
||||
"""
|
||||
|
||||
hostname: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="DNS hostname that resolves to inference server IPs.",
|
||||
),
|
||||
]
|
||||
|
||||
port: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Port that inference servers listen on.",
|
||||
),
|
||||
] = 8000
|
||||
|
||||
sync_interval: Annotated[
|
||||
float,
|
||||
Field(
|
||||
description="Interval in seconds between server discovery checks.",
|
||||
),
|
||||
] = 5.0
|
||||
|
||||
|
||||
class ClientConfig(BaseConfig):
|
||||
"""Configures the OAI client.
|
||||
|
||||
Supports two modes:
|
||||
- Static mode (default): Uses fixed base_url list
|
||||
- Elastic mode: Uses DNS-based service discovery via hostname
|
||||
|
||||
If elastic config is provided, base_url is ignored and servers are discovered dynamically.
|
||||
"""
|
||||
|
||||
timeout: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Timeout in seconds. By default, it is set to 1200 seconds.",
|
||||
),
|
||||
] = 1200
|
||||
|
||||
connect_timeout: Annotated[
|
||||
float,
|
||||
Field(
|
||||
description="TCP connect timeout in seconds for inference API requests.",
|
||||
),
|
||||
] = 30.0
|
||||
|
||||
base_url: Annotated[
|
||||
list[str],
|
||||
Field(
|
||||
description="Base URLs to use for the OpenAI API. By default, it is set to a single server on localhost at port 8000 which matches the default local vLLM server configuration. If you specify more than one URL, the client will round-robin (chat) completion requests across all servers. Ignored if elastic config is provided.",
|
||||
),
|
||||
] = ["http://localhost:8000/v1"]
|
||||
|
||||
api_key_var: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="Name of environment variable containing the API key to use for the inference API. Will parse using `os.getenv(client_config.api_key_var)`. Can be set to an arbitrary string if the inference server is not protected by an API key. If multiple URLs are specified, the same API key will be used for all servers.",
|
||||
),
|
||||
] = "VLLM_API_KEY"
|
||||
|
||||
headers: Annotated[
|
||||
dict[str, str],
|
||||
Field(
|
||||
description="Headers to use for the OpenAI API. By default, it is set to an empty dictionary.",
|
||||
),
|
||||
] = {}
|
||||
|
||||
extra_headers_from_state: Annotated[
|
||||
dict[str, str],
|
||||
Field(
|
||||
description="Maps HTTP header names to state field names. For each inference request, "
|
||||
"the header value is dynamically read from the rollout state dict. "
|
||||
'e.g. {"X-Session-ID": "example_id"} enables sticky routing at the inference router.',
|
||||
),
|
||||
] = {}
|
||||
|
||||
skip_model_check: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to skip checking if the model is available in the inference pool. Useful for external APIs or API Keys that don't support the /models endpoint.",
|
||||
),
|
||||
] = False
|
||||
|
||||
dp_rank_count: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description=(
|
||||
"Number of data-parallel ranks behind each base URL. When > 1, "
|
||||
"each URL is expanded into dp_rank_count logical clients, each "
|
||||
"pinned to a specific DP rank via the X-data-parallel-rank header. "
|
||||
"This ensures all requests within a multi-turn rollout hit the same "
|
||||
"DP engine, maximizing KV cache reuse. Auto-set from "
|
||||
"inference.data_parallel_size_local (or inference.parallel.dp) "
|
||||
"when using the RL entrypoint."
|
||||
),
|
||||
),
|
||||
] = 1
|
||||
|
||||
admin_base_url: Annotated[
|
||||
list[str] | None,
|
||||
Field(
|
||||
description="Separate base URLs for admin operations (weight updates, health checks). "
|
||||
"When set, admin clients use these URLs instead of base_url, allowing weight "
|
||||
"updates to bypass routers and hit each server directly. Used in disaggregated "
|
||||
"P/D deployments where the inference router should not handle admin traffic.",
|
||||
),
|
||||
] = None
|
||||
|
||||
elastic: Annotated[
|
||||
ElasticConfig | None,
|
||||
Field(
|
||||
description="Elastic inference pool configuration for DNS-based service discovery. If provided, base_url is ignored and inference servers are discovered dynamically via DNS.",
|
||||
),
|
||||
] = None
|
||||
|
||||
router_url: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="URL of a vllm-router for load-aware inference routing. When set with elastic mode, inference requests go through the router while admin operations (weight updates, LoRA loading) still go directly to discovered pods.",
|
||||
),
|
||||
] = None
|
||||
|
||||
@property
|
||||
def is_elastic(self) -> bool:
|
||||
"""Check if elastic mode is enabled."""
|
||||
return self.elastic is not None
|
||||
|
||||
|
||||
class LogConfig(BaseConfig):
|
||||
"""Configures the logger."""
|
||||
|
||||
level: Annotated[
|
||||
str,
|
||||
Field(description="Logging level for the process. Will determine the logging verbosity and format."),
|
||||
] = "info"
|
||||
|
||||
vf_level: Annotated[
|
||||
str,
|
||||
Field(description="Logging level for the verifiers package. Will determine the logging verbosity and format."),
|
||||
] = "info"
|
||||
|
||||
file: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to log to a file. If True, will log to a file in the output directory.",
|
||||
),
|
||||
] = True
|
||||
|
||||
env_worker_logs: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether env workers log to files. If True, workers write to logs/env_workers/{env_name}.log.",
|
||||
),
|
||||
] = False
|
||||
|
||||
log_data: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to log the first data sample to the logger.",
|
||||
),
|
||||
] = False
|
||||
|
||||
json_logging: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Emit JSON logs (newline-delimited) for log aggregation (Loki, Grafana, etc.).",
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class LogExtrasConfig(BaseConfig):
|
||||
"""Configures extra logging for monitoring platforms."""
|
||||
|
||||
samples: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to log prompt/response samples.",
|
||||
),
|
||||
] = True
|
||||
|
||||
distributions: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to log distributions (like rewards, advantages, etc.).",
|
||||
),
|
||||
] = True
|
||||
|
||||
interval: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Step interval at which to log extras.",
|
||||
),
|
||||
] = 10
|
||||
|
||||
sample_ratio: Annotated[
|
||||
float | None,
|
||||
Field(
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Fraction of rollouts to log per step (0.0–1.0). "
|
||||
"When set, the effective sample cap is len(rollouts) * sample_ratio. "
|
||||
"1.0 = all rollouts, 0.5 = half, 0.0 = none. "
|
||||
"None (default)",
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class WandbConfig(BaseConfig):
|
||||
"""Configures logging to Weights and Biases."""
|
||||
|
||||
# Shared configs (May be overwritten by WandbConfig from `rl.py`)
|
||||
project: Annotated[str, Field(description="The W&B project to log to.")] = "prime-rl"
|
||||
|
||||
name: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The W&B name to to use for logging.",
|
||||
),
|
||||
] = None
|
||||
|
||||
offline: Annotated[bool, Field(description="Whether to run W&B in offline mode.")] = False
|
||||
|
||||
|
||||
class WandbWithExtrasConfig(WandbConfig):
|
||||
"""Configures logging to Weights and Biases with extras."""
|
||||
|
||||
log_extras: Annotated[
|
||||
LogExtrasConfig | None,
|
||||
Field(
|
||||
description="Configuration for logging extras. If None, no extras are logged.",
|
||||
),
|
||||
] = LogExtrasConfig()
|
||||
|
||||
|
||||
class PrimeMonitorConfig(BaseConfig):
|
||||
"""Configures logging to Prime Intellect API."""
|
||||
|
||||
base_url: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="The base URL for Prime Intellect monitoring API.",
|
||||
),
|
||||
] = "https://api.primeintellect.ai/api/v1/rft"
|
||||
|
||||
api_key_var: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="Name of environment variable containing the API key for Prime Intellect API. Will parse using `os.getenv(config.api_key_var)`.",
|
||||
),
|
||||
] = "PRIME_API_KEY"
|
||||
|
||||
log_extras: Annotated[
|
||||
LogExtrasConfig | None,
|
||||
Field(
|
||||
description="Configuration for logging extras. If None, no extras are logged.",
|
||||
),
|
||||
] = LogExtrasConfig()
|
||||
|
||||
run_name: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="Name for the run shown on the platform. Defaults to the W&B run name if set, otherwise auto-generated by the platform.",
|
||||
),
|
||||
] = None
|
||||
|
||||
team_id: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="Team ID to associate the run with.",
|
||||
),
|
||||
] = None
|
||||
|
||||
frontend_url: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="Frontend base URL used for the dashboard link shown after registration. Defaults to the Prime CLI frontend URL when unset.",
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class HeartbeatConfig(BaseConfig):
|
||||
"""Configures the heartbeat for BetterStack."""
|
||||
|
||||
url: Annotated[str, Field(description="The URL to send the heartbeat to.")]
|
||||
|
||||
|
||||
class MetricsServerConfig(BaseConfig):
|
||||
"""Configures the Prometheus metrics server for trainer observability."""
|
||||
|
||||
port: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
le=65535,
|
||||
description="Port to expose metrics and health endpoints. Defaults to 8000.",
|
||||
),
|
||||
] = 8000
|
||||
|
||||
host: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="Host to bind the server to. Defaults to 0.0.0.0.",
|
||||
),
|
||||
] = "0.0.0.0"
|
||||
|
||||
|
||||
class BaseTransportConfig(BaseModel):
|
||||
"""Base configuration for transport."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class FileSystemTransportConfig(BaseTransportConfig):
|
||||
"""Configures filesystem-based transport for training examples."""
|
||||
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
|
||||
class ZMQTransportConfig(BaseTransportConfig):
|
||||
"""Configures ZMQ-based transport for training examples."""
|
||||
|
||||
type: Literal["zmq"] = "zmq"
|
||||
host: Annotated[str, Field(description="The host address for ZMQ transport.")] = "localhost"
|
||||
port: Annotated[int, Field(description="The base port for ZMQ transport.")] = 5555
|
||||
hwm: Annotated[int, Field(description="High water mark (max messages in queue) for ZMQ sockets.")] = 10
|
||||
|
||||
|
||||
TransportConfig: TypeAlias = Annotated[FileSystemTransportConfig | ZMQTransportConfig, Field(discriminator="type")]
|
||||
@@ -1,9 +1,20 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from prime_rl.utils.pydantic_config import BaseConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
FileSystemTransportConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
MetricsServerConfig,
|
||||
TransportConfig,
|
||||
WandbConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
# -- Shared trainer configs (used by both SFT and RL trainers) --
|
||||
|
||||
AttnImplementation: TypeAlias = Literal["sdpa", "flash_attention_2", "flash_attention_3", "fa4"]
|
||||
|
||||
@@ -58,22 +69,6 @@ class BenchConfig(BaseConfig):
|
||||
] = None
|
||||
|
||||
|
||||
class DebugModelConfig(BaseConfig):
|
||||
"""Debugging feature around model and distributed training."""
|
||||
|
||||
num_layers: Annotated[
|
||||
int | None,
|
||||
Field(description="The number of layers in the model."),
|
||||
] = None
|
||||
|
||||
random_init: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to random initialize the model.",
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class LoRAConfig(BaseConfig):
|
||||
"""Configuration for LoRA (Low-Rank Adaptation)."""
|
||||
|
||||
@@ -126,15 +121,24 @@ class LoRAConfig(BaseConfig):
|
||||
] = []
|
||||
|
||||
|
||||
class ModelConfig(BaseConfig):
|
||||
"""Configures the model for training."""
|
||||
class DebugModelConfig(BaseConfig):
|
||||
"""Debugging feature around model and distributed training."""
|
||||
|
||||
name: Annotated[
|
||||
str,
|
||||
num_layers: Annotated[
|
||||
int | None,
|
||||
Field(description="The number of layers in the model."),
|
||||
] = None
|
||||
|
||||
random_init: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Name or path of the HF model to use.",
|
||||
description="Whether to random initialize the model.",
|
||||
),
|
||||
] = "Qwen/Qwen3-0.6B"
|
||||
] = False
|
||||
|
||||
|
||||
class ModelConfig(BaseModelConfig):
|
||||
"""Configures the model for training."""
|
||||
|
||||
seq_len: Annotated[int, Field(description="The sequence length to use for the model.")] = 2048
|
||||
|
||||
@@ -184,13 +188,6 @@ class ModelConfig(BaseConfig):
|
||||
bool, Field(description="Whether to reshard the model after each forward pass.")
|
||||
] = True
|
||||
|
||||
trust_remote_code: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to trust remote code for model and tokenizer initialization.",
|
||||
),
|
||||
] = False
|
||||
|
||||
dp_replicate: Annotated[
|
||||
int,
|
||||
Field(
|
||||
@@ -271,19 +268,19 @@ class ModelConfig(BaseConfig):
|
||||
),
|
||||
] = DebugModelConfig()
|
||||
|
||||
fused_lm_head_chunk_size: Annotated[
|
||||
fused_lm_head_token_chunk_size: Annotated[
|
||||
int | Literal["auto", "disabled"],
|
||||
Field(
|
||||
description=(
|
||||
"The chunk size to use for the fused LM head. "
|
||||
"The flattened token chunk size to use for the fused LM head. "
|
||||
"Three behaviors: "
|
||||
"(1) int >= 512: explicitly set chunk size for fused LM head; "
|
||||
"(2) 'auto': auto-enable (RL training auto-sets to 2048); "
|
||||
"(1) int >= 1: explicitly set the number of tokens per LM-head chunk; "
|
||||
"(2) 'auto': auto-enable (RL training auto-sets to 8192); "
|
||||
"(3) 'disabled': explicitly disable fused LM head (use vanilla). "
|
||||
"Explicitly setting an integer value for this feature isn't supported for SFT training."
|
||||
),
|
||||
),
|
||||
] = "auto"
|
||||
] = "disabled"
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
@@ -325,16 +322,6 @@ class ModelConfig(BaseConfig):
|
||||
raise ValueError("Cannot enable both fsdp_cpu_offload and optim_cpu_offload. Use one or the other.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def fused_lm_head_chunk_size_is_valid(self):
|
||||
if isinstance(self.fused_lm_head_chunk_size, int):
|
||||
low = 512
|
||||
if self.fused_lm_head_chunk_size < low:
|
||||
raise ValueError(
|
||||
f"Fused LM head chunk size must be at least {low}, got {self.fused_lm_head_chunk_size}"
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def flash_attention_4_only_with_custom_impl(self):
|
||||
if self.attn == "fa4" and self.impl != "custom":
|
||||
@@ -403,7 +390,9 @@ class CosineSchedulerConfig(BaseModel):
|
||||
min_lr: Annotated[float, Field(ge=0, description="Minimum learning rate to converge to.")] = 0.0
|
||||
|
||||
|
||||
SchedulerConfigType: TypeAlias = ConstantSchedulerConfig | LinearSchedulerConfig | CosineSchedulerConfig
|
||||
SchedulerConfig: TypeAlias = Annotated[
|
||||
ConstantSchedulerConfig | LinearSchedulerConfig | CosineSchedulerConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class BaseOptimizerConfig(BaseModel):
|
||||
@@ -437,7 +426,7 @@ class MuonConfig(BaseOptimizerConfig):
|
||||
] = 0.95
|
||||
|
||||
|
||||
OptimizerConfigType: TypeAlias = SGDConfig | AdamWConfig | MuonConfig
|
||||
OptimizerConfig: TypeAlias = Annotated[SGDConfig | AdamWConfig | MuonConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class WeightCheckpointConfig(BaseConfig):
|
||||
@@ -468,6 +457,13 @@ class WeightCheckpointConfig(BaseConfig):
|
||||
class CheckpointConfig(BaseConfig):
|
||||
"""Configures checkpointing the full model, optimizer and training state for resuming training."""
|
||||
|
||||
output_dir: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer output_dir. Useful for writing large checkpoints to a separate storage volume.",
|
||||
),
|
||||
] = None
|
||||
|
||||
interval: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
@@ -478,6 +474,20 @@ class CheckpointConfig(BaseConfig):
|
||||
|
||||
weights: WeightCheckpointConfig | None = WeightCheckpointConfig()
|
||||
|
||||
skip_gather_master_weights: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="When true, skip gathering and saving HF-compatible weight checkpoints. Useful for large models where the gather is expensive and only DCP checkpoints are needed.",
|
||||
),
|
||||
] = False
|
||||
|
||||
weights_only: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="When true, only save weight checkpoints (no optimizer/scheduler state). Much faster and smaller than full checkpoints, but cannot resume training.",
|
||||
),
|
||||
] = False
|
||||
|
||||
resume_step: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
@@ -522,3 +532,291 @@ class CheckpointConfig(BaseConfig):
|
||||
description="Whether to skip loading the dataloader from checkpoint.",
|
||||
),
|
||||
] = False
|
||||
|
||||
skip_optimizer: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to skip loading the optimizer state from checkpoint.",
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class DefaultLossConfig(BaseModel):
|
||||
"""Config for the default loss."""
|
||||
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
ipo_mask_low: Annotated[float, Field(ge=0, description="The low threshold for masking tokens.")] = 0.2
|
||||
ipo_mask_high: Annotated[float, Field(ge=0, description="The high threshold for masking tokens.")] = 0.2
|
||||
adv_tau: Annotated[float, Field(ge=0, description="The tau for advantages.")] = 1.0
|
||||
teacher_tau: Annotated[float, Field(ge=0, description="The tau for teacher logprobs.")] = 0.0
|
||||
kl_tau: Annotated[float, Field(ge=0, description="The tau for KL divergence.")] = 1e-3
|
||||
|
||||
|
||||
class SFTLossConfig(BaseModel):
|
||||
"""Config for SFT-style masked negative log-likelihood loss."""
|
||||
|
||||
type: Literal["sft"] = "sft"
|
||||
|
||||
|
||||
class CustomLossConfig(BaseModel):
|
||||
"""Config for a custom external loss function."""
|
||||
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
import_path: Annotated[str, Field(description="Import path to the loss function (e.g., 'my_module.my_loss')")]
|
||||
kwargs: Annotated[dict[str, Any], Field(default_factory=dict, description="Kwargs to pass to the loss function")]
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | SFTLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
"""Configures a fake data loader sampling random micro batches for debugging."""
|
||||
|
||||
batch_size: Annotated[int, Field(ge=1)] = 2
|
||||
generate_samples: Annotated[
|
||||
bool, Field(description="Whether to generate separate samples and pack them into a single micro batch.")
|
||||
] = False
|
||||
|
||||
|
||||
class DataLoaderConfig(BaseConfig):
|
||||
"""Configures the data loader used for training."""
|
||||
|
||||
fake: Annotated[FakeDataLoaderConfig | None, Field(description="Whether to use a fake data loader.")] = None
|
||||
|
||||
|
||||
class BaseWeightBroadcastConfig(BaseModel):
|
||||
"""Configures the base weight broadcast."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
"""Configures the weight broadcast."""
|
||||
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
save_sharded: Annotated[bool, Field(description="Whether to save the weight checkpoint in sharded format.")] = True
|
||||
save_format: Annotated[
|
||||
Literal["safetensors", "torch"], Field(description="The format to save the weight checkpoint in.")
|
||||
] = "safetensors"
|
||||
|
||||
|
||||
class NCCLWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
"""Configures the NCCL broadcast."""
|
||||
|
||||
type: Literal["nccl"] = "nccl"
|
||||
host: Annotated[str, Field(description="The host to use for the NCCL broadcast.")] = "localhost"
|
||||
port: Annotated[int, Field(description="The port to use for the NCCL broadcast.")] = 29501
|
||||
timeout: Annotated[int, Field(description="The timeout in seconds to use for the NCCL broadcast.")] = 1200
|
||||
# TODO: Should not be configurable, but auto-inferred
|
||||
inference_world_size: Annotated[int, Field(description="The number of GPUs used for inference.")] = 1
|
||||
quantize_in_weight_transfer: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"Use kernel-format FP8 quantized NCCL transfer for weight updates. "
|
||||
"When disabled, uses default HF checkpoint-format transfer."
|
||||
),
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class TrainerConfig(BaseConfig):
|
||||
"""Configures the RL trainer"""
|
||||
|
||||
# The model configuration
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
# The tokenizer configuration
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
# The data configuration
|
||||
data: DataLoaderConfig = DataLoaderConfig()
|
||||
|
||||
# The loss configuration
|
||||
loss: LossConfig = DefaultLossConfig()
|
||||
|
||||
# The optimizer configuration
|
||||
optim: OptimizerConfig = AdamWConfig()
|
||||
|
||||
# The learning rate scheduler configuration
|
||||
scheduler: SchedulerConfig = ConstantSchedulerConfig()
|
||||
|
||||
# The checkpoint configuration
|
||||
ckpt: CheckpointConfig | None = None
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
|
||||
|
||||
rollout_transport: TransportConfig = FileSystemTransportConfig()
|
||||
|
||||
# The logging configuration
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
# The wandb configuration
|
||||
wandb: WandbConfig | None = None
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
Field(
|
||||
description="Directory to write outputs to. Will be populated with checkpoints, weights, rollouts and logs as subdirectories. Should be set to a persistent directory with enough disk space. This value should be distinct across experiments running on a single node. See the README for more details."
|
||||
),
|
||||
] = Path("outputs")
|
||||
|
||||
max_steps: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="Maximum number of steps to run training for. If None, will run indefinitely.",
|
||||
),
|
||||
] = None
|
||||
|
||||
max_async_level: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=0,
|
||||
description="Maximum number of steps that inference can be ahead of training. Determines how 'off-policy' the inference engines can be. Higher values yield better throughput through async execution, but may yield lower performance. If 0, will be fully synchronous.",
|
||||
),
|
||||
] = 1
|
||||
|
||||
enable_router_replay: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to enable router replay. If True, will return routed experts in the batch. This is only supported if `enable_return_routed_experts=True` in the inference config or pass `--enable-return-routed-experts` to vLLM server. This is only supported for custom models.",
|
||||
),
|
||||
] = False
|
||||
|
||||
memory_profiler_path: Annotated[Path | None, Field(description="Path to write memory profile to.")] = None
|
||||
|
||||
bench: Annotated[
|
||||
BenchConfig | None,
|
||||
Field(
|
||||
description="Whether to run in benchmark mode. It will automatically set the maximum number of steps to run to 4 and use fake data.",
|
||||
),
|
||||
] = None
|
||||
|
||||
trace_path: Annotated[Path | None, Field(description="Path to write pytorch profiler trace to.")] = None
|
||||
|
||||
dist_timeout_seconds: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Timeout in seconds for torch distributed ops. Defaults to 600 seconds.",
|
||||
),
|
||||
] = 600
|
||||
|
||||
heartbeat: Annotated[
|
||||
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
|
||||
] = None
|
||||
|
||||
metrics_server: Annotated[
|
||||
MetricsServerConfig | None,
|
||||
Field(description="Prometheus metrics server config. If set, exposes /metrics endpoint for scraping."),
|
||||
] = None
|
||||
|
||||
max_concurrent_runs: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="The maximum number of concurrent runs to allow. If 1, then only one run will be allowed at a time.",
|
||||
),
|
||||
] = 1
|
||||
|
||||
@model_validator(mode="after")
|
||||
def vlms_require_bfloat16(self):
|
||||
if self.model.vlm is not None and (
|
||||
self.model.optimization_dtype != "bfloat16" or self.model.reduce_dtype != "bfloat16"
|
||||
):
|
||||
raise ValueError(
|
||||
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench is not None:
|
||||
self.max_steps = 4 # 1 Warmup + 3 Benchmark
|
||||
if not self.data.fake:
|
||||
self.data.fake = FakeDataLoaderConfig()
|
||||
if self.ckpt: # Do not checkpoint
|
||||
self.ckpt = None
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def dont_do_massive_traces(self):
|
||||
if self.trace_path:
|
||||
if self.max_steps is None:
|
||||
raise ValueError("Must specify max_steps when tracing")
|
||||
if self.max_steps >= 10:
|
||||
raise ValueError(
|
||||
"Tracing more than 10 steps is not recommended as your trace will be massive. Remove this line if you really want to trace more steps."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_adapter_saving(self):
|
||||
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
|
||||
lora_enabled = self.model and self.model.lora
|
||||
if not lora_enabled:
|
||||
raise ValueError(
|
||||
"save_adapter_separately=True requires LoRA to be enabled. "
|
||||
"Set model.lora or disable save_adapter_separately."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_weight_broadcast_type(self):
|
||||
if self.weight_broadcast.type == "nccl" and self.max_async_level != 1:
|
||||
raise ValueError("NCCL weight broadcast only works with async level 1")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_opt_and_fsdp_offload(self):
|
||||
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
|
||||
raise ValueError("Muon optimizer does not support FSDP CPU offload")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_optim_cpu_offload_single_run(self):
|
||||
if self.model.optim_cpu_offload and self.max_concurrent_runs > 1:
|
||||
raise ValueError("Optimizer CPU offload is not supported with max_concurrent_runs > 1")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_broadcast(self):
|
||||
if self.model.lora is not None and self.weight_broadcast.type == "nccl":
|
||||
# TODO: Support this
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_tokenizer(self):
|
||||
if self.tokenizer.name is None:
|
||||
self.tokenizer.name = self.model.name
|
||||
if self.tokenizer.trust_remote_code is None:
|
||||
self.tokenizer.trust_remote_code = self.model.trust_remote_code
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_fused_lm_head_token_chunk_size(self):
|
||||
if self.model.fused_lm_head_token_chunk_size == "auto":
|
||||
self.model.fused_lm_head_token_chunk_size = 8192
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def ep_only_with_custom_impl(self):
|
||||
if self.model.ep > 1 and self.model.impl not in ("custom", "auto"):
|
||||
raise ValueError("EP is only supported with the custom implementation or auto mode")
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def router_replay_only_with_custom_impl(self):
|
||||
if self.enable_router_replay and self.model.impl not in ("custom", "auto"):
|
||||
raise ValueError("Router replay is only supported with the custom implementation or auto mode")
|
||||
|
||||
return self
|
||||
@@ -0,0 +1,142 @@
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import get_config_dir
|
||||
|
||||
INFERENCE_TOML = "inference.toml"
|
||||
INFERENCE_SBATCH = "inference.sbatch"
|
||||
|
||||
|
||||
def write_config(config: InferenceConfig, output_dir: Path, exclude: set[str] | None = None) -> Path:
|
||||
"""Write resolved config to disk."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
config_path = output_dir / INFERENCE_TOML
|
||||
with open(config_path, "wb") as f:
|
||||
tomli_w.dump(config.model_dump(exclude=exclude, exclude_none=True, mode="json"), f)
|
||||
return config_path
|
||||
|
||||
|
||||
def write_slurm_script(config: InferenceConfig, config_path: Path, script_path: Path) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
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)
|
||||
|
||||
is_disaggregated = config.deployment.type == "disaggregated"
|
||||
|
||||
template_vars = dict(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.output_dir,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
num_nodes=getattr(config.deployment, "num_nodes", 1),
|
||||
port=config.server.port,
|
||||
disaggregated=is_disaggregated,
|
||||
)
|
||||
|
||||
is_multi_node = config.deployment.type == "multi_node"
|
||||
|
||||
if is_disaggregated:
|
||||
template_vars.update(
|
||||
num_prefill_nodes=config.deployment.num_prefill_nodes,
|
||||
num_decode_nodes=config.deployment.num_decode_nodes,
|
||||
prefill_port=config.deployment.prefill_port,
|
||||
decode_port=config.deployment.decode_port,
|
||||
router_port=config.deployment.router_port,
|
||||
data_parallel_rpc_port=config.data_parallel_rpc_port,
|
||||
use_deep_gemm=config.use_deep_gemm,
|
||||
)
|
||||
elif is_multi_node:
|
||||
template_vars.update(
|
||||
router_port=config.deployment.router_port,
|
||||
backend_port=config.deployment.backend_port,
|
||||
)
|
||||
|
||||
script = template.render(**template_vars)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
def inference_slurm(config: InferenceConfig):
|
||||
"""Run inference via SLURM."""
|
||||
assert config.slurm is not None
|
||||
|
||||
logger = setup_logger("info")
|
||||
|
||||
config_dir = get_config_dir(config.output_dir)
|
||||
exclude = (
|
||||
{"deployment", "slurm", "dry_run"}
|
||||
if config.deployment.type in ("multi_node", "disaggregated")
|
||||
else {"slurm", "dry_run"}
|
||||
)
|
||||
config_path = write_config(config, config_dir, exclude=exclude)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
script_path = config.output_dir / INFERENCE_SBATCH
|
||||
write_slurm_script(config, config_path, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
log_message = (
|
||||
f"Logs:\n"
|
||||
f" Job: tail -F {config.output_dir}/job_*.log\n"
|
||||
f" Inference: tail -F {config.output_dir}/slurm/latest_infer_node_rank_*.log\n"
|
||||
)
|
||||
|
||||
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 inference_local(config: InferenceConfig):
|
||||
"""Run inference locally."""
|
||||
from prime_rl.inference.server import setup_vllm_env
|
||||
|
||||
logger = setup_logger("info")
|
||||
|
||||
if config.dry_run:
|
||||
logger.success("Dry run complete. To start inference locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
host = config.server.host or "0.0.0.0"
|
||||
port = config.server.port
|
||||
logger.info(f"Starting inference on http://{host}:{port}/v1\n")
|
||||
|
||||
setup_vllm_env(config)
|
||||
|
||||
from prime_rl.inference.vllm.server import server # pyright: ignore
|
||||
|
||||
server(config, vllm_extra=config.vllm_extra)
|
||||
|
||||
|
||||
def inference(config: InferenceConfig):
|
||||
if config.slurm is not None:
|
||||
inference_slurm(config)
|
||||
else:
|
||||
inference_local(config)
|
||||
|
||||
|
||||
def main():
|
||||
inference(cli(InferenceConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,523 @@
|
||||
import json
|
||||
import os
|
||||
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.configs.rl import RLConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import validate_output_dir
|
||||
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process
|
||||
from prime_rl.utils.utils import (
|
||||
get_free_port,
|
||||
get_log_dir,
|
||||
)
|
||||
|
||||
RL_TOML = "rl.toml"
|
||||
RL_SBATCH = "rl.sbatch"
|
||||
|
||||
TRAINER_TOML = "trainer.toml"
|
||||
ORCHESTRATOR_TOML = "orchestrator.toml"
|
||||
INFERENCE_TOML = "inference.toml"
|
||||
TEACHER_INFERENCE_TOML = "teacher_inference.toml"
|
||||
|
||||
|
||||
def get_physical_gpu_ids() -> list[int]:
|
||||
"""Return physical GPU IDs visible to the launcher."""
|
||||
raw_visible = os.environ.get("CUDA_VISIBLE_DEVICES")
|
||||
if raw_visible is None:
|
||||
pynvml.nvmlInit()
|
||||
return list(range(pynvml.nvmlDeviceGetCount()))
|
||||
return [int(token.strip()) for token in raw_visible.split(",") if token.strip()]
|
||||
|
||||
|
||||
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
|
||||
"""Write resolved config to disk, excluding launcher-only fields."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
config_dict = config.model_dump(exclude=exclude, exclude_none=True, mode="json")
|
||||
with open(output_dir / RL_TOML, "wb") as f:
|
||||
tomli_w.dump(config_dict, f)
|
||||
|
||||
|
||||
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:
|
||||
# Exclude launcher-only fields that are not needed by the vLLM server
|
||||
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
|
||||
with open(output_dir / INFERENCE_TOML, "wb") as f:
|
||||
tomli_w.dump(config.inference.model_dump(exclude=exclude_inference, 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 rl_local(config: RLConfig):
|
||||
assert config.deployment.type == "single_node"
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
config_dir = config.output_dir / "configs"
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
|
||||
if config.dry_run:
|
||||
logger.success("Dry run complete. To start an RL run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
# Derive launcher-local GPU IDs from deployment config
|
||||
gpu_offset = 0
|
||||
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
|
||||
infer_local_gpu_ids = list(range(gpu_offset, gpu_offset + num_infer_gpus))
|
||||
gpu_offset += num_infer_gpus
|
||||
trainer_local_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_local_gpu_ids = list(range(gpu_offset, gpu_offset + num_teacher_gpus)) if num_teacher_gpus > 0 else []
|
||||
|
||||
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus + num_teacher_gpus
|
||||
physical_gpu_ids = get_physical_gpu_ids()
|
||||
if total_requested_gpus > len(physical_gpu_ids):
|
||||
raise ValueError(
|
||||
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
|
||||
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
|
||||
)
|
||||
physical_gpu_mapping = {local_id: physical_gpu_ids[local_id] for local_id in range(total_requested_gpus)}
|
||||
logger.info(f"Using local->physical GPU mapping: {physical_gpu_mapping}")
|
||||
|
||||
infer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in infer_local_gpu_ids]
|
||||
trainer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in trainer_local_gpu_ids]
|
||||
teacher_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in teacher_local_gpu_ids]
|
||||
|
||||
start_command = sys.argv
|
||||
logger.info("Starting RL run")
|
||||
logger.debug(f"RL start command: {' '.join(start_command)}")
|
||||
|
||||
# Build shared W&B env vars for subprocesses
|
||||
wandb_shared_env: dict[str, str] = {}
|
||||
if config.wandb and config.wandb.shared:
|
||||
wandb_shared_env["WANDB_SHARED_MODE"] = "1"
|
||||
wandb_shared_env["WANDB_SHARED_RUN_ID"] = uuid.uuid4().hex
|
||||
|
||||
# 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)
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 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 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:
|
||||
if config.orchestrator.teacher_rollout_model is None:
|
||||
logger.warning(
|
||||
"No inference config specified, skipping starting inference server. Make sure your inference server is running."
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
"No inference config specified, using orchestrator.teacher_rollout_model for rollout generation."
|
||||
)
|
||||
|
||||
# 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,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "orchestrator",
|
||||
"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 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,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "trainer",
|
||||
"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 write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
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":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_dir / RL_TOML,
|
||||
output_dir=config.output_dir,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
elif config.inference is not None and config.inference.deployment.type == "disaggregated":
|
||||
infer_deploy = config.inference.deployment
|
||||
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
is_disaggregated=True,
|
||||
config_dir=config_dir,
|
||||
output_dir=config.output_dir,
|
||||
orchestrator_output_dir=config.orchestrator.output_dir,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=infer_deploy.num_nodes * config.deployment.num_infer_replicas,
|
||||
nodes_per_infer_replica=infer_deploy.num_nodes,
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
num_prefill_nodes=infer_deploy.num_prefill_nodes,
|
||||
num_decode_nodes=infer_deploy.num_decode_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router_port=infer_deploy.router_port,
|
||||
prefill_port=infer_deploy.prefill_port,
|
||||
decode_port=infer_deploy.decode_port,
|
||||
inference_tp=config.inference.parallel.tp,
|
||||
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port,
|
||||
use_deep_gemm=config.inference.use_deep_gemm,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
wandb_shared=config.wandb is not None and config.wandb.shared,
|
||||
)
|
||||
else:
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
is_disaggregated=False,
|
||||
config_dir=config_dir, # TODO: should prob have each subconfig path separately
|
||||
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.total_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.num_infer_nodes,
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
num_teacher_nodes=config.deployment.num_teacher_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router_port=getattr(config.inference.deployment, "router_port", 8000) if config.inference else 8000,
|
||||
backend_port=getattr(config.inference.deployment, "backend_port", 8100) if config.inference else 8100,
|
||||
inference_tp=config.inference.parallel.tp if config.inference else 1,
|
||||
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
|
||||
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
wandb_shared=config.wandb is not None and config.wandb.shared,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
def rl_slurm(config: RLConfig):
|
||||
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 == "single_node":
|
||||
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean_output_dir"})
|
||||
logger.info(f"Wrote config to {config_dir / RL_TOML}")
|
||||
|
||||
log_dir = get_log_dir(config.output_dir)
|
||||
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:
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
|
||||
slurm_log_dir = config.output_dir / "slurm"
|
||||
log_lines = [f" Trainer: tail -F {slurm_log_dir}/latest_train_node_rank_0.log"]
|
||||
if config.deployment.num_infer_nodes > 0:
|
||||
log_lines.append(f" Orchestrator: tail -F {slurm_log_dir}/latest_orchestrator.log")
|
||||
log_lines.append(f" Inference: tail -F {slurm_log_dir}/latest_infer_node_rank_0.log")
|
||||
log_message = "Logs:\n" + "\n".join(log_lines)
|
||||
|
||||
script_path = config.output_dir / RL_SBATCH
|
||||
write_slurm_script(config, config_dir, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
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 rl(config: RLConfig):
|
||||
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
|
||||
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
|
||||
ckpt_output_dir = config.ckpt.output_dir if config.ckpt else None
|
||||
validate_output_dir(config.output_dir, resuming=resuming, clean=clean, ckpt_output_dir=ckpt_output_dir)
|
||||
config.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
if ckpt_output_dir is not None:
|
||||
ckpt_output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if config.slurm is not None:
|
||||
rl_slurm(config)
|
||||
else:
|
||||
rl_local(config)
|
||||
|
||||
|
||||
def main():
|
||||
rl(cli(RLConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,210 @@
|
||||
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.configs.sft import SFTConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import get_config_dir, get_log_dir, validate_output_dir
|
||||
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
SFT_TOML = "sft.toml"
|
||||
SFT_SBATCH = "sft.sbatch"
|
||||
|
||||
|
||||
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
|
||||
"""Write resolved config to disk, excluding launcher-only fields."""
|
||||
config_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
config_dict = config.model_dump(exclude=exclude, exclude_none=True, mode="json")
|
||||
with open(config_path, "wb") as f:
|
||||
tomli_w.dump(config_dict, f)
|
||||
|
||||
|
||||
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
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":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.output_dir,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
else:
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.output_dir,
|
||||
num_nodes=config.deployment.num_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
def sft_slurm(config: SFTConfig):
|
||||
"""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 = get_config_dir(config.output_dir)
|
||||
config_path = config_dir / SFT_TOML
|
||||
exclude = (
|
||||
{"deployment", "slurm", "dry_run", "clean_output_dir"}
|
||||
if config.deployment.type == "multi_node"
|
||||
else {"slurm", "dry_run", "clean_output_dir"}
|
||||
)
|
||||
write_config(config, config_path, exclude=exclude)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
script_path = config.output_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
log_message = f"Logs:\n Trainer: tail -F {get_log_dir(config.output_dir)}/trainer/rank_0.log"
|
||||
else:
|
||||
log_message = f"Logs:\n Trainer: tail -F {config.output_dir}/slurm/latest_train_node_rank_*.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 sft_local(config: SFTConfig):
|
||||
"""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 = get_config_dir(config.output_dir)
|
||||
config_path = config_dir / SFT_TOML
|
||||
write_config(config, config_path)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
if config.dry_run:
|
||||
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
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_dir / SFT_TOML).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: SFTConfig):
|
||||
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
|
||||
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
|
||||
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
|
||||
config.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if config.slurm is not None:
|
||||
sft_slurm(config)
|
||||
else:
|
||||
sft_local(config)
|
||||
|
||||
|
||||
def main():
|
||||
sft(cli(SFTConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -9,6 +9,60 @@ def transformers_v5_compat():
|
||||
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
|
||||
Qwen3VLMoeTextConfig.tie_word_embeddings = False
|
||||
|
||||
_patch_qwen35_lora()
|
||||
monkey_patch_dp_engine_core_pause_resume_deadlock()
|
||||
|
||||
|
||||
def _patch_qwen35_lora():
|
||||
"""Fix Qwen3.5 LoRA: align packed_modules_mapping with output_sizes.
|
||||
|
||||
Qwen3.5's GDN layers use create_qkvz_proj with 4 output_sizes (q, k, v, z)
|
||||
but packed_modules_mapping only lists 2 entries, causing an IndexError
|
||||
during LoRA initialization.
|
||||
|
||||
Also generalizes MergedColumnParallelLinearWithLoRA.can_replace_layer
|
||||
to accept any number of packed modules (not just 2), and generalizes
|
||||
MergedColumnParallelLinearWithShardedLoRA.slice_lora_a to handle N
|
||||
subloras instead of the hardcoded 2 (needed for fully_sharded_loras=True).
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/issues/36372
|
||||
"""
|
||||
from vllm.lora.layers.column_parallel_linear import (
|
||||
MergedColumnParallelLinearWithLoRA,
|
||||
MergedColumnParallelLinearWithShardedLoRA,
|
||||
)
|
||||
from vllm.model_executor.models.qwen3_5 import (
|
||||
Qwen3_5ForCausalLMBase,
|
||||
Qwen3_5ForConditionalGeneration,
|
||||
)
|
||||
|
||||
qkvz_fix = ["in_proj_q", "in_proj_k", "in_proj_v", "in_proj_z"]
|
||||
|
||||
Qwen3_5ForCausalLMBase.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
|
||||
Qwen3_5ForConditionalGeneration.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
|
||||
|
||||
from vllm.lora.layers.utils import _not_fully_sharded_can_replace
|
||||
|
||||
@classmethod
|
||||
@_not_fully_sharded_can_replace
|
||||
def can_replace_layer(cls, source_layer, lora_config, packed_modules_list, model_config=None):
|
||||
from vllm.model_executor.layers.linear import MergedColumnParallelLinear
|
||||
|
||||
return type(source_layer) is MergedColumnParallelLinear and len(packed_modules_list) == len(
|
||||
source_layer.output_sizes
|
||||
)
|
||||
|
||||
MergedColumnParallelLinearWithLoRA.can_replace_layer = can_replace_layer
|
||||
|
||||
def slice_lora_a(self, lora_a):
|
||||
output_shard_size = self.lora_a_stacked[0].shape[2]
|
||||
output_start_idx = self.tp_rank * output_shard_size
|
||||
return [
|
||||
a[output_start_idx : output_start_idx + output_shard_size, :] if a is not None else None for a in lora_a
|
||||
]
|
||||
|
||||
MergedColumnParallelLinearWithShardedLoRA.slice_lora_a = slice_lora_a
|
||||
|
||||
|
||||
# Monkeypatch PrometheusStatLogger to avoid NotImplementedError for LoRA in DP mode
|
||||
def monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode():
|
||||
@@ -201,8 +255,27 @@ def monkey_patch_tokenize_params_validation():
|
||||
)
|
||||
return text
|
||||
|
||||
def _patched_get_encode_kwargs(self):
|
||||
"""Use max_total_tokens (max_model_len) instead of max_input_tokens for HF tokenizer truncation.
|
||||
|
||||
The original uses max_input_tokens (= max_model_len - max_tokens) + 1, which causes HuggingFace's
|
||||
tokenizer.encode() to left-truncate prompts before _token_len_check even runs.
|
||||
"""
|
||||
max_length = self.truncate_prompt_tokens
|
||||
if max_length is not None and max_length < 0:
|
||||
max_length = self.max_total_tokens
|
||||
elif max_length is None and self.max_total_tokens is not None:
|
||||
max_length = self.max_total_tokens + 1
|
||||
|
||||
return dict(
|
||||
truncation=max_length is not None,
|
||||
max_length=max_length,
|
||||
add_special_tokens=self.add_special_tokens,
|
||||
)
|
||||
|
||||
TokenizeParams._token_len_check = _patched_token_len_check
|
||||
TokenizeParams._text_len_check = _patched_text_len_check
|
||||
TokenizeParams.get_encode_kwargs = _patched_get_encode_kwargs
|
||||
|
||||
|
||||
def monkey_patch_hermes_tool_parser_thread_safety():
|
||||
@@ -272,6 +345,42 @@ def monkey_patch_hermes_tool_parser_thread_safety():
|
||||
Hermes2ProToolParser.__init__ = _patched_init
|
||||
|
||||
|
||||
def monkey_patch_tokenizer_thread_safety():
|
||||
"""Patch HuggingFace tokenizer to make _encode_plus thread-safe.
|
||||
|
||||
Under concurrent request load, vLLM's API server calls _encode_plus from
|
||||
multiple async handlers simultaneously. _encode_plus mutates the Rust
|
||||
tokenizer's internal state via set_truncation_and_padding (enable_truncation/
|
||||
enable_padding) and encode_special_tokens. The Rust backend uses RefCell-style
|
||||
borrow tracking (PyO3), and concurrent mutable borrows cause it to panic
|
||||
with ``RuntimeError: Already borrowed``.
|
||||
|
||||
Fix: wrap the entire _encode_plus method in a per-tokenizer threading lock
|
||||
so that state mutation and the subsequent encode call are atomic.
|
||||
"""
|
||||
import threading
|
||||
|
||||
from transformers import PreTrainedTokenizerFast
|
||||
|
||||
_original_encode_plus = PreTrainedTokenizerFast._encode_plus
|
||||
_locks: dict[int, threading.Lock] = {}
|
||||
_meta_lock = threading.Lock()
|
||||
|
||||
def _get_lock(tokenizer_id: int) -> threading.Lock:
|
||||
if tokenizer_id not in _locks:
|
||||
with _meta_lock:
|
||||
if tokenizer_id not in _locks:
|
||||
_locks[tokenizer_id] = threading.Lock()
|
||||
return _locks[tokenizer_id]
|
||||
|
||||
def _patched_encode_plus(self, *args, **kwargs):
|
||||
lock = _get_lock(id(self._tokenizer))
|
||||
with lock:
|
||||
return _original_encode_plus(self, *args, **kwargs)
|
||||
|
||||
PreTrainedTokenizerFast._encode_plus = _patched_encode_plus
|
||||
|
||||
|
||||
def monkey_patch_minimax_m2_for_lora():
|
||||
"""Patch vLLM's MiniMaxM2 model for LoRA compatibility.
|
||||
|
||||
@@ -345,3 +454,294 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
".up_proj.": ".w3.",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def monkey_patch_harmony_stop_token_propagation():
|
||||
"""Fix: vLLM 0.17.0 doesn't merge harmony stop tokens into per-request SamplingParams.
|
||||
|
||||
The harmony mode sets stop_token_ids (including <|call|> and <|return|>) in
|
||||
default_sampling_params at server init, but ChatCompletionRequest.to_sampling_params()
|
||||
ignores them, using only self.stop_token_ids (which defaults to []).
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/issues/22519
|
||||
"""
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
|
||||
|
||||
_original_to_sampling_params = ChatCompletionRequest.to_sampling_params
|
||||
|
||||
def _patched_to_sampling_params(self, max_tokens, default_sampling_params):
|
||||
params = _original_to_sampling_params(self, max_tokens, default_sampling_params)
|
||||
# Merge harmony stop tokens from default_sampling_params
|
||||
default_stop_ids = default_sampling_params.get("stop_token_ids", [])
|
||||
if default_stop_ids:
|
||||
existing = set(params.stop_token_ids or [])
|
||||
merged = list(existing | set(default_stop_ids))
|
||||
params.stop_token_ids = merged
|
||||
return params
|
||||
|
||||
ChatCompletionRequest.to_sampling_params = _patched_to_sampling_params
|
||||
|
||||
|
||||
def monkey_patch_fused_moe_lora_dp():
|
||||
"""Fix: LoRA + MoE + DP>1 produces corrupted output in vLLM 0.17.0.
|
||||
|
||||
Two bugs:
|
||||
1. LoRA injection sets supports_internal_mk=True (via moe_kernel not None),
|
||||
causing the MoE runner to skip DP dispatch/combine. But the LoRA kernel
|
||||
uses NoDPEP and doesn't handle DP internally.
|
||||
2. LoRA decorators capture full-batch tensors but fire per-chunk inside the
|
||||
kernel's chunk loop. At DP>=3, dispatched batch > CHUNK_SIZE causes
|
||||
shape mismatches.
|
||||
|
||||
Fix: Replace _inject_lora_into_fused_moe with a version that:
|
||||
(a) sets moe_kernel=None so the runner correctly dispatches
|
||||
(b) makes decorators chunk-aware by tracking chunk offsets
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/issues/23244
|
||||
"""
|
||||
import types
|
||||
|
||||
from vllm import envs
|
||||
from vllm.distributed.utils import divide
|
||||
from vllm.lora.layers.fused_moe import FusedMoEWithLoRA
|
||||
from vllm.model_executor.layers.fused_moe.config import _get_config_dtype_str
|
||||
from vllm.model_executor.layers.fused_moe.fused_marlin_moe import MarlinExperts
|
||||
from vllm.model_executor.layers.fused_moe.fused_moe import TritonExperts
|
||||
from vllm.model_executor.layers.fused_moe.fused_moe_modular_method import FusedMoEModularMethod
|
||||
from vllm.model_executor.layers.fused_moe.gpt_oss_triton_kernels_moe import UnfusedOAITritonExperts
|
||||
from vllm.model_executor.layers.fused_moe.modular_kernel import FusedMoEKernel
|
||||
from vllm.model_executor.layers.fused_moe.prepare_finalize import MoEPrepareAndFinalizeNoDPEPModular
|
||||
|
||||
def _fixed_inject(self):
|
||||
moe_state_dict = {}
|
||||
top_k = self.base_layer.top_k
|
||||
|
||||
self.base_layer.ensure_moe_quant_config_init()
|
||||
quant_config = self.base_layer.quant_method.moe_quant_config
|
||||
|
||||
if getattr(self.base_layer.quant_method, "supports_internal_mk", False):
|
||||
m_fused_moe_fn = self.base_layer.quant_method.moe_kernel
|
||||
m_fused_moe_fn.shared_experts = None
|
||||
else:
|
||||
prepare_finalize = MoEPrepareAndFinalizeNoDPEPModular()
|
||||
m_fused_moe_fn = FusedMoEKernel(
|
||||
prepare_finalize,
|
||||
self.base_layer.quant_method.select_gemm_impl(prepare_finalize, self.base_layer),
|
||||
)
|
||||
|
||||
if quant_config.use_mxfp4_w4a16:
|
||||
assert isinstance(m_fused_moe_fn.impl.fused_experts, (MarlinExperts, UnfusedOAITritonExperts))
|
||||
else:
|
||||
assert isinstance(m_fused_moe_fn.impl.fused_experts, TritonExperts)
|
||||
|
||||
# --- Decorators (chunk-aware) ---
|
||||
|
||||
def fwd_decorator(layer, func):
|
||||
def wrapper(*args, **kwargs):
|
||||
moe_state_dict["hidden_states"] = kwargs["hidden_states"]
|
||||
moe_state_dict["topk_ids"] = kwargs["topk_ids"]
|
||||
moe_state_dict["topk_weights"] = kwargs["topk_weights"]
|
||||
moe_state_dict["expert_map"] = kwargs["expert_map"]
|
||||
moe_state_dict["apply_router_weight_on_input"] = kwargs["apply_router_weight_on_input"]
|
||||
moe_state_dict["_chunk_offset"] = 0
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
def act_decorator(layer, func):
|
||||
def wrapper(*args, **kwargs):
|
||||
_, output, input = args
|
||||
chunk_M = input.view(-1, top_k, input.shape[-1]).shape[0]
|
||||
chunk_offset = moe_state_dict.get("_chunk_offset", 0)
|
||||
hidden_states = moe_state_dict["hidden_states"][chunk_offset : chunk_offset + chunk_M]
|
||||
topk_weights = moe_state_dict["topk_weights"][chunk_offset : chunk_offset + chunk_M]
|
||||
curr_topk_ids = moe_state_dict["topk_ids"][chunk_offset : chunk_offset + chunk_M]
|
||||
expert_map = moe_state_dict["expert_map"]
|
||||
config_dtype = _get_config_dtype_str(
|
||||
dtype=hidden_states.dtype, use_fp8_w8a8=False, use_int8_w8a16=False, use_int4_w4a16=False
|
||||
)
|
||||
num_tokens = hidden_states.size(0)
|
||||
M = min(num_tokens, envs.VLLM_FUSED_MOE_CHUNK_SIZE)
|
||||
max_lora_rank = self.w13_lora_a_stacked[0].shape[-2]
|
||||
shrink_config, expand_config = self._get_lora_moe_configs(
|
||||
op_prefix="w13",
|
||||
num_loras=self.max_loras,
|
||||
rank=max_lora_rank,
|
||||
num_slices=self._w13_slices,
|
||||
M=M,
|
||||
layer=layer,
|
||||
top_k=top_k,
|
||||
config_dtype=config_dtype,
|
||||
)
|
||||
SPARSITY_FACTOR = 8
|
||||
naive_block_assignment = (
|
||||
expert_map is None
|
||||
and num_tokens * top_k * SPARSITY_FACTOR <= self.base_layer.local_num_experts * self.max_loras
|
||||
)
|
||||
token_lora_mapping, sorted_token_ids_lora, expert_ids_lora, num_tokens_post_padded_lora = (
|
||||
self.punica_wrapper.moe_lora_align_block_size(
|
||||
curr_topk_ids,
|
||||
num_tokens,
|
||||
shrink_config["BLOCK_SIZE_M"],
|
||||
self.base_layer.local_num_experts,
|
||||
self.max_loras,
|
||||
self.adapter_enabled,
|
||||
expert_map,
|
||||
naive_block_assignment=naive_block_assignment,
|
||||
)
|
||||
)
|
||||
moe_state_dict["sorted_token_ids_lora"] = sorted_token_ids_lora
|
||||
moe_state_dict["expert_ids_lora"] = expert_ids_lora
|
||||
moe_state_dict["num_tokens_post_padded_lora"] = num_tokens_post_padded_lora
|
||||
moe_state_dict["token_lora_mapping"] = token_lora_mapping
|
||||
if sorted_token_ids_lora is not None:
|
||||
expert_ids_lora = expert_ids_lora.view(self.max_loras, -1)
|
||||
sorted_token_ids_lora = sorted_token_ids_lora.view(self.max_loras, -1)
|
||||
self.punica_wrapper.add_lora_fused_moe(
|
||||
input.view(-1, top_k, input.shape[-1]),
|
||||
hidden_states,
|
||||
self.w13_lora_a_stacked,
|
||||
self.w13_lora_b_stacked,
|
||||
topk_weights,
|
||||
sorted_token_ids_lora,
|
||||
expert_ids_lora,
|
||||
num_tokens_post_padded_lora,
|
||||
max_lora_rank,
|
||||
top_k,
|
||||
shrink_config,
|
||||
expand_config,
|
||||
self.adapter_enabled,
|
||||
fully_sharded=self.fully_sharded,
|
||||
token_lora_mapping=token_lora_mapping,
|
||||
)
|
||||
result = func(*args, **kwargs)
|
||||
moe_state_dict["intermediate_cache2"] = output
|
||||
moe_state_dict["_chunk_M"] = chunk_M
|
||||
return result
|
||||
|
||||
return wrapper
|
||||
|
||||
def moe_sum_decorator(layer, func):
|
||||
def wrapper(*args, **kwargs):
|
||||
chunk_offset = moe_state_dict.get("_chunk_offset", 0)
|
||||
chunk_M = moe_state_dict.get("_chunk_M", moe_state_dict["hidden_states"].size(0))
|
||||
hidden_states = moe_state_dict["hidden_states"][chunk_offset : chunk_offset + chunk_M]
|
||||
topk_weights = moe_state_dict["topk_weights"][chunk_offset : chunk_offset + chunk_M]
|
||||
config_dtype = _get_config_dtype_str(
|
||||
dtype=hidden_states.dtype, use_fp8_w8a8=False, use_int8_w8a16=False, use_int4_w4a16=False
|
||||
)
|
||||
num_tokens = hidden_states.size(0)
|
||||
M = min(num_tokens, envs.VLLM_FUSED_MOE_CHUNK_SIZE)
|
||||
max_lora_rank = self.w2_lora_a_stacked[0].shape[-2]
|
||||
shrink_config, expand_config = self._get_lora_moe_configs(
|
||||
op_prefix="w2",
|
||||
num_loras=self.max_loras,
|
||||
rank=max_lora_rank,
|
||||
num_slices=1,
|
||||
M=M,
|
||||
layer=layer,
|
||||
top_k=top_k,
|
||||
config_dtype=config_dtype,
|
||||
)
|
||||
sorted_token_ids_lora = moe_state_dict["sorted_token_ids_lora"]
|
||||
expert_ids_lora = moe_state_dict["expert_ids_lora"]
|
||||
num_tokens_post_padded_lora = moe_state_dict["num_tokens_post_padded_lora"]
|
||||
token_lora_mapping = moe_state_dict.get("token_lora_mapping")
|
||||
if sorted_token_ids_lora is not None:
|
||||
expert_ids_lora = expert_ids_lora.view(self.max_loras, -1)
|
||||
sorted_token_ids_lora = sorted_token_ids_lora.view(self.max_loras, -1)
|
||||
intermediate_cache2 = moe_state_dict["intermediate_cache2"]
|
||||
intermediate_cache3 = args[0]
|
||||
shard_size_w2 = divide(self.base_layer.hidden_size, self.tp_size)
|
||||
self.punica_wrapper.add_lora_fused_moe(
|
||||
intermediate_cache3,
|
||||
intermediate_cache2,
|
||||
self.w2_lora_a_stacked,
|
||||
self.w2_lora_b_stacked,
|
||||
topk_weights,
|
||||
sorted_token_ids_lora,
|
||||
expert_ids_lora,
|
||||
num_tokens_post_padded_lora,
|
||||
max_lora_rank,
|
||||
top_k,
|
||||
shrink_config,
|
||||
expand_config,
|
||||
self.adapter_enabled,
|
||||
True,
|
||||
fully_sharded=self.fully_sharded,
|
||||
offset=shard_size_w2 * self.tp_rank if self.fully_sharded else 0,
|
||||
token_lora_mapping=token_lora_mapping,
|
||||
)
|
||||
result = func(*args, **kwargs)
|
||||
moe_state_dict["_chunk_offset"] = chunk_offset + chunk_M
|
||||
return result
|
||||
|
||||
return wrapper
|
||||
|
||||
# --- Install decorators and replace quant method ---
|
||||
|
||||
fused_experts = m_fused_moe_fn.impl.fused_experts
|
||||
m_fused_moe_fn.apply = fwd_decorator(self.base_layer, m_fused_moe_fn.apply)
|
||||
fused_experts.activation = act_decorator(self.base_layer, fused_experts.activation)
|
||||
fused_experts.moe_sum = moe_sum_decorator(self.base_layer, fused_experts.moe_sum)
|
||||
|
||||
new_method = FusedMoEModularMethod(self.base_layer.quant_method, m_fused_moe_fn)
|
||||
|
||||
# Bug 1 fix: NoDPEP kernel makes supports_internal_mk=True, causing the
|
||||
# runner to skip DP dispatch/combine. Set moe_kernel=None and patch apply().
|
||||
if isinstance(m_fused_moe_fn.prepare_finalize, MoEPrepareAndFinalizeNoDPEPModular):
|
||||
saved_kernel = new_method.moe_kernel
|
||||
saved_disable_expert_map = new_method.disable_expert_map
|
||||
new_method.moe_kernel = None
|
||||
|
||||
def _apply_with_saved_kernel(self, layer, x, topk_weights, topk_ids, shared_experts_input):
|
||||
return saved_kernel.apply(
|
||||
hidden_states=x,
|
||||
w1=layer.w13_weight,
|
||||
w2=layer.w2_weight,
|
||||
topk_weights=topk_weights,
|
||||
topk_ids=topk_ids,
|
||||
activation=layer.activation,
|
||||
global_num_experts=layer.global_num_experts,
|
||||
apply_router_weight_on_input=layer.apply_router_weight_on_input,
|
||||
expert_map=None if saved_disable_expert_map else layer.expert_map,
|
||||
shared_experts_input=shared_experts_input,
|
||||
)
|
||||
|
||||
new_method.apply = types.MethodType(_apply_with_saved_kernel, new_method)
|
||||
|
||||
self.base_layer._replace_quant_method(new_method)
|
||||
|
||||
FusedMoEWithLoRA._inject_lora_into_fused_moe = _fixed_inject
|
||||
|
||||
|
||||
def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
"""Fix deadlock with pause/resume and collective_rpc in DP engine core.
|
||||
|
||||
When a request arrives for an already-completed wave while the scheduler is
|
||||
paused, the unpatched code sends a start_wave notification that triggers
|
||||
collective_rpc on other DP engines. But the paused engine can't participate
|
||||
in the collective, causing a deadlock.
|
||||
|
||||
Fix: only send the start_wave notification when the scheduler is unpaused,
|
||||
and explicitly set engines_running=True before notifying.
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/pull/37024
|
||||
"""
|
||||
from vllm.v1.core.sched.interface import PauseState
|
||||
from vllm.v1.engine import EngineCoreOutputs
|
||||
from vllm.v1.engine.core import DPEngineCoreProc, EngineCore
|
||||
from vllm.v1.request import Request
|
||||
|
||||
_base_add_request = EngineCore.add_request
|
||||
|
||||
def _patched_add_request(self, request: Request, request_wave: int = 0):
|
||||
_base_add_request(self, request, request_wave)
|
||||
if self.has_coordinator and request_wave != self.current_wave:
|
||||
if request_wave > self.current_wave:
|
||||
self.current_wave = request_wave
|
||||
elif not self.engines_running and self.scheduler.pause_state == PauseState.UNPAUSED:
|
||||
self.engines_running = True
|
||||
self.output_queue.put_nowait((-1, EngineCoreOutputs(start_wave=self.current_wave)))
|
||||
|
||||
DPEngineCoreProc.add_request = _patched_add_request
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import os
|
||||
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.config import cli
|
||||
|
||||
|
||||
def setup_vllm_env(config: InferenceConfig):
|
||||
@@ -15,13 +15,13 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
|
||||
|
||||
def main():
|
||||
config = parse_argv(InferenceConfig, allow_extras=True)
|
||||
config = cli(InferenceConfig)
|
||||
setup_vllm_env(config)
|
||||
|
||||
# We import here to be able to set environment variables before importing vLLM
|
||||
from prime_rl.inference.vllm.server import server # pyright: ignore
|
||||
|
||||
server(config, vllm_args=config.get_unknown_args())
|
||||
server(config, vllm_extra=config.vllm_extra)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from argparse import Namespace
|
||||
from http import HTTPStatus
|
||||
from typing import Any
|
||||
|
||||
import uvloop
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
@@ -21,18 +22,133 @@ from vllm.entrypoints.utils import load_aware_call, with_cancellation
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
|
||||
# GLM-4.5
|
||||
"zai-org/GLM-4.5": "glm45",
|
||||
"zai-org/GLM-4.5-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Base": "glm45",
|
||||
"zai-org/GLM-4.5-Air": "glm45",
|
||||
"zai-org/GLM-4.5-Air-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Air-Base": "glm45",
|
||||
"zai-org/GLM-4.5V": "glm45",
|
||||
"zai-org/GLM-4.5V-FP8": "glm45",
|
||||
# GLM-4.7
|
||||
"zai-org/GLM-4.7": "glm47",
|
||||
"zai-org/GLM-4.7-FP8": "glm47",
|
||||
"zai-org/GLM-4.7-Flash": "glm47",
|
||||
# GLM-5
|
||||
"zai-org/GLM-5": "glm47",
|
||||
"zai-org/GLM-5-FP8": "glm47",
|
||||
# MiniMax M2
|
||||
"MiniMaxAI/MiniMax-M2": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.1": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.5": "minimax_m2",
|
||||
# INTELLECT-3
|
||||
"PrimeIntellect/INTELLECT-3": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3-FP8": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3.1": "hermes",
|
||||
# Qwen3 dense
|
||||
"Qwen/Qwen3-0.6B": "hermes",
|
||||
"Qwen/Qwen3-0.6B-Base": "hermes",
|
||||
"Qwen/Qwen3-0.6B-FP8": "hermes",
|
||||
"Qwen/Qwen3-1.7B": "hermes",
|
||||
"Qwen/Qwen3-1.7B-Base": "hermes",
|
||||
"Qwen/Qwen3-1.7B-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B": "hermes",
|
||||
"Qwen/Qwen3-4B-Base": "hermes",
|
||||
"Qwen/Qwen3-4B-FP8": "hermes",
|
||||
"Qwen/Qwen3-8B": "hermes",
|
||||
"Qwen/Qwen3-8B-Base": "hermes",
|
||||
"Qwen/Qwen3-8B-FP8": "hermes",
|
||||
"Qwen/Qwen3-14B": "hermes",
|
||||
"Qwen/Qwen3-14B-Base": "hermes",
|
||||
"Qwen/Qwen3-14B-FP8": "hermes",
|
||||
"Qwen/Qwen3-32B": "hermes",
|
||||
"Qwen/Qwen3-32B-FP8": "hermes",
|
||||
# Qwen3 MoE
|
||||
"Qwen/Qwen3-30B-A3B": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Base": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-FP8": "hermes",
|
||||
# Qwen3 2507
|
||||
"Qwen/Qwen3-4B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507-FP8": "hermes",
|
||||
# Qwen3-Next
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking-FP8": "hermes",
|
||||
# Qwen3-Coder
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8": "hermes",
|
||||
# Qwen3-Coder-Next
|
||||
"Qwen/Qwen3-Coder-Next": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-Base": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-FP8": "hermes",
|
||||
# Qwen3.5 dense (uses qwen3_coder tool format, not hermes)
|
||||
"Qwen/Qwen3.5-0.8B": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-0.8B-Base": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-2B": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-2B-Base": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-4B": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-4B-Base": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-9B": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-9B-Base": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-27B": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-27B-FP8": "qwen3_coder",
|
||||
# Qwen3.5 MoE (uses qwen3_coder tool format, not hermes)
|
||||
"Qwen/Qwen3.5-35B-A3B": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-35B-A3B-Base": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-35B-A3B-FP8": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-122B-A10B": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-122B-A10B-FP8": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-397B-A17B": "qwen3_coder",
|
||||
"Qwen/Qwen3.5-397B-A17B-FP8": "qwen3_coder",
|
||||
# NemotronH
|
||||
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16": "qwen3_coder",
|
||||
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16": "qwen3_coder",
|
||||
}
|
||||
|
||||
|
||||
def resolve_tool_call_parser(model_name: str, tool_call_parser: str | None) -> str | None:
|
||||
"""Resolve tool_call_parser from model name if set to "auto"."""
|
||||
if tool_call_parser == "auto":
|
||||
return MODEL_TOOL_CALL_PARSER.get(model_name)
|
||||
return tool_call_parser
|
||||
|
||||
|
||||
logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_harmony_stop_token_propagation,
|
||||
monkey_patch_hermes_tool_parser_thread_safety,
|
||||
monkey_patch_load_lora_adapter,
|
||||
monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
monkey_patch_tokenizer_thread_safety,
|
||||
)
|
||||
from prime_rl.inference.vllm.serving_chat_with_tokens import (
|
||||
ChatCompletionRequestWithTokens,
|
||||
OpenAIServingChatWithTokens,
|
||||
)
|
||||
|
||||
# NOTE: Fix harmony stop token propagation for GPT-OSS models (vLLM 0.17.0 bug)
|
||||
monkey_patch_harmony_stop_token_propagation()
|
||||
# NOTE: Monkeypatch PrometheusStatLogger to avoid NotImplementedError for LoRA in DP mode
|
||||
monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode()
|
||||
# NOTE: Monkeypatch LoadLoRAAdapter to allow loading the same adapter multiple times
|
||||
@@ -41,6 +157,9 @@ monkey_patch_load_lora_adapter()
|
||||
monkey_patch_tokenize_params_validation()
|
||||
# NOTE: Monkeypatch Hermes tool parser to fix "Already borrowed" RuntimeError under concurrent load
|
||||
monkey_patch_hermes_tool_parser_thread_safety()
|
||||
# NOTE: Monkeypatch HF tokenizer to fix "Already borrowed" RuntimeError during concurrent chat template processing
|
||||
# Can be removed once https://github.com/vllm-project/vllm/pull/36557 is merged and we upgrade vllm
|
||||
monkey_patch_tokenizer_thread_safety()
|
||||
|
||||
logger = init_logger("vllm.entrypoints.openai.api_server")
|
||||
|
||||
@@ -70,11 +189,22 @@ def chat_with_tokens(request: Request) -> OpenAIServingChatWithTokens | None:
|
||||
return request.app.state.openai_serving_chat_with_tokens
|
||||
|
||||
|
||||
@router.post("/pause")
|
||||
async def pause(request: Request):
|
||||
await engine_client(request).pause_generation(mode="keep", clear_cache=False)
|
||||
return {"status": "paused"}
|
||||
|
||||
|
||||
@router.post("/resume")
|
||||
async def resume(request: Request):
|
||||
await engine_client(request).resume_generation()
|
||||
return {"status": "resumed"}
|
||||
|
||||
|
||||
@router.post("/update_weights")
|
||||
async def update_weights(request: Request):
|
||||
data = await request.json()
|
||||
await engine_client(request).collective_rpc("update_weights_from_path", args=(data.get("weight_dir"),))
|
||||
# Reset prefix cache to invalidate KV states computed with old weights
|
||||
await engine_client(request).reset_prefix_cache()
|
||||
return {"status": "ok"}
|
||||
|
||||
@@ -101,12 +231,13 @@ async def init_broadcaster(request: Request):
|
||||
host = data.get("host")
|
||||
port = data.get("port")
|
||||
timeout = data.get("timeout")
|
||||
# Support both legacy and new field names
|
||||
server_rank = data.get("server_rank")
|
||||
num_inference_server = data.get("num_inference_server")
|
||||
rank_offset = data.get("rank_offset")
|
||||
inference_world_size = data.get("inference_world_size")
|
||||
gpus_per_server = data.get("gpus_per_server")
|
||||
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
|
||||
await engine_client(request).collective_rpc(
|
||||
"init_broadcaster",
|
||||
args=(host, port, server_rank, num_inference_server, timeout),
|
||||
args=(host, port, rank_offset, inference_world_size, gpus_per_server, timeout, quantize_in_weight_transfer),
|
||||
)
|
||||
return {"status": "ok"}
|
||||
|
||||
@@ -165,28 +296,31 @@ async def custom_init_app_state(
|
||||
|
||||
resolved_chat_template = load_chat_template(args.chat_template)
|
||||
|
||||
state.openai_serving_chat_with_tokens = (
|
||||
OpenAIServingChatWithTokens(
|
||||
engine_client,
|
||||
state.openai_serving_models,
|
||||
args.response_role,
|
||||
request_logger=request_logger,
|
||||
chat_template=resolved_chat_template,
|
||||
chat_template_content_format=args.chat_template_content_format,
|
||||
trust_request_chat_template=args.trust_request_chat_template,
|
||||
return_tokens_as_token_ids=args.return_tokens_as_token_ids,
|
||||
enable_auto_tools=args.enable_auto_tool_choice,
|
||||
exclude_tools_when_tool_choice_none=args.exclude_tools_when_tool_choice_none,
|
||||
tool_parser=args.tool_call_parser,
|
||||
reasoning_parser=args.structured_outputs_config.reasoning_parser,
|
||||
enable_prompt_tokens_details=args.enable_prompt_tokens_details,
|
||||
enable_force_include_usage=args.enable_force_include_usage,
|
||||
enable_log_outputs=args.enable_log_outputs,
|
||||
log_error_stack=args.log_error_stack,
|
||||
)
|
||||
if "generate" in supported_tasks
|
||||
else None
|
||||
chat_kwargs = dict(
|
||||
request_logger=request_logger,
|
||||
chat_template=resolved_chat_template,
|
||||
chat_template_content_format=args.chat_template_content_format,
|
||||
trust_request_chat_template=args.trust_request_chat_template,
|
||||
return_tokens_as_token_ids=args.return_tokens_as_token_ids,
|
||||
enable_auto_tools=args.enable_auto_tool_choice,
|
||||
exclude_tools_when_tool_choice_none=args.exclude_tools_when_tool_choice_none,
|
||||
tool_parser=args.tool_call_parser,
|
||||
reasoning_parser=args.structured_outputs_config.reasoning_parser,
|
||||
enable_prompt_tokens_details=args.enable_prompt_tokens_details,
|
||||
enable_force_include_usage=args.enable_force_include_usage,
|
||||
enable_log_outputs=args.enable_log_outputs,
|
||||
)
|
||||
if hasattr(args, "log_error_stack"):
|
||||
chat_kwargs["log_error_stack"] = args.log_error_stack
|
||||
|
||||
serving_chat = OpenAIServingChatWithTokens(
|
||||
engine_client,
|
||||
state.openai_serving_models,
|
||||
args.response_role,
|
||||
**chat_kwargs,
|
||||
)
|
||||
state.openai_serving_chat = serving_chat if "generate" in supported_tasks else None
|
||||
state.openai_serving_chat_with_tokens = serving_chat if "generate" in supported_tasks else None
|
||||
|
||||
|
||||
def custom_run_api_server_worker_proc(listen_address, sock, args, client_config=None, **uvicorn_kwargs) -> None:
|
||||
@@ -226,16 +360,26 @@ vllm.entrypoints.cli.serve.run_api_server_worker_proc = custom_run_api_server_wo
|
||||
# Adapted from vllm/entrypoints/cli/serve.py
|
||||
# Only difference we do some config translation (i.e. pass populated namespace
|
||||
# to `parse_args`) and additional arg validation
|
||||
def server(config: InferenceConfig, vllm_args: list[str]):
|
||||
def server(config: InferenceConfig, vllm_extra: dict[str, Any] | None = None):
|
||||
from vllm.entrypoints.cli.serve import run_headless, run_multi_api_server
|
||||
from vllm.entrypoints.openai.api_server import run_server
|
||||
|
||||
namespace = config.to_vllm()
|
||||
if vllm_extra:
|
||||
for key, value in vllm_extra.items():
|
||||
setattr(namespace, key, value)
|
||||
|
||||
parser = FlexibleArgumentParser(description="vLLM OpenAI-Compatible RESTful API server.")
|
||||
parser = make_arg_parser(parser)
|
||||
args = parser.parse_args(args=vllm_args, namespace=config.to_vllm())
|
||||
args = parser.parse_args(args=[], namespace=namespace)
|
||||
assert args is not None
|
||||
validate_parsed_serve_args(args)
|
||||
|
||||
args.tool_call_parser = resolve_tool_call_parser(args.model, args.tool_call_parser)
|
||||
args.enable_auto_tool_choice = args.tool_call_parser is not None
|
||||
if args.tool_call_parser is not None:
|
||||
logger.info(f"Using tool_call_parser='{args.tool_call_parser}' for model '{args.model}'")
|
||||
|
||||
# Set the worker extension class based on the broadcast backend
|
||||
args.worker_extension_cls = WORKER_EXTENSION_CLS[config.weight_broadcast.type]
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
from collections.abc import AsyncGenerator
|
||||
import base64
|
||||
from collections.abc import AsyncGenerator, AsyncIterator
|
||||
from typing import ClassVar, Optional, Union
|
||||
|
||||
import numpy as np
|
||||
from fastapi import Request
|
||||
from pydantic import Field
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest, ChatCompletionResponse
|
||||
@@ -8,57 +10,37 @@ from vllm.entrypoints.openai.chat_completion.serving import OpenAIServingChat
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, RequestResponseMetadata
|
||||
from vllm.entrypoints.openai.engine.serving import GenerationError
|
||||
from vllm.entrypoints.utils import get_max_tokens
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.logger import init_logger
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.reasoning import ReasoningParser
|
||||
from vllm.sampling_params import BeamSearchParams, SamplingParams
|
||||
from vllm.v1.sample.logits_processor import validate_logits_processors_parameters
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _collapse_image_placeholders(
|
||||
original_tokens: list[int],
|
||||
override_tokens: list[int],
|
||||
) -> list[int]:
|
||||
"""
|
||||
Collapse pre-expanded image placeholder tokens in override_tokens.
|
||||
class _RoutedExpertsCapture:
|
||||
def __init__(self, generator: AsyncGenerator[RequestOutput, None]):
|
||||
self._generator = generator
|
||||
self.routed_experts: dict[int, dict] = {}
|
||||
|
||||
In multi-turn VLM conversations, tokens from previous turns already have
|
||||
expanded image placeholders (e.g., 64 consecutive <|image_pad|> tokens).
|
||||
If left as-is, _process_inputs re-expands each token individually, causing
|
||||
compounding token inflation across turns.
|
||||
def _encode_routed_experts(self, arr: np.ndarray) -> dict:
|
||||
return {
|
||||
"data": base64.b85encode(arr.tobytes()).decode("ascii"),
|
||||
"shape": list(arr.shape),
|
||||
}
|
||||
|
||||
Detects placeholder token IDs by comparing with the original engine tokens
|
||||
(which have single placeholders from _preprocess_chat), then collapses
|
||||
consecutive runs back to single tokens so _process_inputs can expand
|
||||
them correctly.
|
||||
"""
|
||||
if not override_tokens or original_tokens == override_tokens:
|
||||
return override_tokens
|
||||
async def __aiter__(self):
|
||||
async for request_output in self._generator:
|
||||
for output in request_output.outputs:
|
||||
if output.routed_experts is not None:
|
||||
self.routed_experts[output.index] = self._encode_routed_experts(output.routed_experts)
|
||||
yield request_output
|
||||
|
||||
def get_block_tokens(tokens: list[int], min_run: int) -> set[int]:
|
||||
"""Return token IDs that appear in consecutive runs >= min_run."""
|
||||
result = set()
|
||||
run_start = 0
|
||||
for i in range(1, len(tokens) + 1):
|
||||
if i == len(tokens) or tokens[i] != tokens[run_start]:
|
||||
if i - run_start >= min_run:
|
||||
result.add(tokens[run_start])
|
||||
run_start = i
|
||||
return result
|
||||
|
||||
# Placeholder tokens appear in blocks of 2+ in override but only as singles in original
|
||||
placeholder_ids = get_block_tokens(override_tokens, 2) - get_block_tokens(original_tokens, 2)
|
||||
if not placeholder_ids:
|
||||
return override_tokens
|
||||
|
||||
result = []
|
||||
for token in override_tokens:
|
||||
if token in placeholder_ids and result and result[-1] == token:
|
||||
continue
|
||||
result.append(token)
|
||||
return result
|
||||
def post_process(self, response: ChatCompletionResponse):
|
||||
for choice in response.choices:
|
||||
if choice.index in self.routed_experts:
|
||||
choice.routed_experts = self.routed_experts[choice.index]
|
||||
|
||||
|
||||
class ChatCompletionRequestWithTokens(ChatCompletionRequest):
|
||||
@@ -67,7 +49,46 @@ class ChatCompletionRequestWithTokens(ChatCompletionRequest):
|
||||
|
||||
|
||||
class OpenAIServingChatWithTokens(OpenAIServingChat):
|
||||
"""OpenAI-compatible generate API that allows token-in."""
|
||||
"""OpenAI-compatible generate API that allows token-in and routed experts capture."""
|
||||
|
||||
async def chat_completion_full_generator(
|
||||
self,
|
||||
request: ChatCompletionRequest,
|
||||
result_generator: AsyncIterator[RequestOutput],
|
||||
request_id: str,
|
||||
model_name: str,
|
||||
conversation,
|
||||
tokenizer,
|
||||
request_metadata: RequestResponseMetadata,
|
||||
reasoning_parser: ReasoningParser | None = None,
|
||||
) -> ErrorResponse | ChatCompletionResponse:
|
||||
# We need to override the full_generator to be able to capture the routed experts
|
||||
# By default, VLLM does not save the routed experts into ChatCompletionResponse.choices, so we need to capture them manually
|
||||
# How this works:
|
||||
# 1. We create a custom generator that encapsulates the original result_generator in self._generator
|
||||
# 2. We override it's __aiter__ method to also capture the routed experts as an extra field in ChatCompletionResponse.choices
|
||||
# 3. We override the full_generator method to use the custom generator instead of the original one if expert routing is enabled
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
capture = _RoutedExpertsCapture(result_generator)
|
||||
result_generator = capture
|
||||
else:
|
||||
capture = None
|
||||
|
||||
response = await super().chat_completion_full_generator(
|
||||
request,
|
||||
result_generator,
|
||||
request_id,
|
||||
model_name,
|
||||
conversation,
|
||||
tokenizer,
|
||||
request_metadata,
|
||||
reasoning_parser,
|
||||
)
|
||||
|
||||
if capture and isinstance(response, ChatCompletionResponse):
|
||||
capture.post_process(response)
|
||||
|
||||
return response
|
||||
|
||||
async def create_chat_completion_with_tokens(
|
||||
self,
|
||||
@@ -75,8 +96,11 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
|
||||
raw_request: Optional[Request] = None,
|
||||
) -> Union[AsyncGenerator[str, None], ChatCompletionResponse, ErrorResponse]:
|
||||
"""
|
||||
Copy of OpenAIServingChat.create_chat_completion, adapted to use prompt
|
||||
ids directly via ChatCompletionRequestWithTokens.
|
||||
Chat Completion API similar to OpenAI's API.
|
||||
|
||||
See https://platform.openai.com/docs/api-reference/chat/create
|
||||
for the API specification. This API mimics the OpenAI
|
||||
Chat Completion API.
|
||||
"""
|
||||
# Streaming response
|
||||
tokenizer = self.renderer.tokenizer
|
||||
@@ -102,16 +126,10 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
|
||||
|
||||
conversation, engine_prompts = result
|
||||
|
||||
# For VLM models: collapse pre-expanded image placeholders before _process_inputs.
|
||||
# In multi-turn token prompts, previous turns' image placeholders are already expanded
|
||||
# (e.g., 64 consecutive <|image_pad|>). Without collapsing, _process_inputs re-expands
|
||||
# each token, inflating counts (64 → 127 → 253 → ...) across turns.
|
||||
if engine_prompts[0].get("multi_modal_data"):
|
||||
override_tokens = _collapse_image_placeholders(engine_prompts[0]["prompt_token_ids"], request.tokens) # type: ignore
|
||||
else:
|
||||
override_tokens = request.tokens
|
||||
|
||||
engine_prompts[0]["prompt_token_ids"] = override_tokens # type: ignore
|
||||
# We override prompt tokens directly.
|
||||
# VLM conversations use MITO (message-based) instead of TITO, so
|
||||
# multi_modal_data is not expected here.
|
||||
engine_prompts[0]["prompt_token_ids"] = request.tokens # type: ignore
|
||||
|
||||
request_id = f"chatcmpl-{self._base_request_id(raw_request, request.request_id)}"
|
||||
|
||||
@@ -131,20 +149,33 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
|
||||
data_parallel_rank = self._get_data_parallel_rank(raw_request)
|
||||
|
||||
# Schedule the request and get the result generator.
|
||||
max_model_len = self.model_config.max_model_len
|
||||
generators: list[AsyncGenerator[RequestOutput, None]] = []
|
||||
try:
|
||||
for i, engine_prompt in enumerate(engine_prompts):
|
||||
prompt_text = self._extract_prompt_text(engine_prompt)
|
||||
prompt_token_ids = self._extract_prompt_components(engine_prompt).token_ids
|
||||
|
||||
# If we are creating sub requests for multiple prompts, ensure that they
|
||||
# have unique request ids.
|
||||
sub_request_id = request_id if len(engine_prompts) == 1 else f"{request_id}_{i}"
|
||||
|
||||
prompt_len = self._extract_prompt_len(engine_prompt)
|
||||
if prompt_len >= max_model_len:
|
||||
raise VLLMValidationError(
|
||||
f"This model's maximum context length is "
|
||||
f"{max_model_len} tokens. However, your request has "
|
||||
f"{prompt_len} input tokens. Please reduce the length of "
|
||||
"the input messages.",
|
||||
parameter="input_tokens",
|
||||
value=prompt_len,
|
||||
)
|
||||
|
||||
max_tokens = get_max_tokens(
|
||||
self.max_model_len,
|
||||
max_model_len,
|
||||
request.max_completion_tokens if request.max_completion_tokens is not None else request.max_tokens,
|
||||
self._extract_prompt_len(engine_prompt),
|
||||
self.default_sampling_params,
|
||||
self.override_max_tokens,
|
||||
)
|
||||
|
||||
sampling_params: SamplingParams | BeamSearchParams
|
||||
@@ -153,13 +184,8 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
|
||||
else:
|
||||
sampling_params = request.to_sampling_params(
|
||||
max_tokens,
|
||||
self.model_config.logits_processor_pattern,
|
||||
self.default_sampling_params,
|
||||
)
|
||||
validate_logits_processors_parameters(
|
||||
self.logits_processors,
|
||||
sampling_params,
|
||||
)
|
||||
|
||||
self._log_inputs(
|
||||
sub_request_id,
|
||||
@@ -179,35 +205,19 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
|
||||
trace_headers=trace_headers,
|
||||
)
|
||||
else:
|
||||
tok_params = request.build_tok_params(self.model_config)
|
||||
tokenization_kwargs = tok_params.get_encode_kwargs()
|
||||
reasoning_ended = (
|
||||
reasoning_parser.is_reasoning_end(prompt_token_ids or []) if reasoning_parser else None
|
||||
)
|
||||
|
||||
engine_request = self.input_processor.process_inputs(
|
||||
sub_request_id,
|
||||
generator = self.engine_client.generate(
|
||||
engine_prompt,
|
||||
sampling_params,
|
||||
lora_request=lora_request,
|
||||
tokenization_kwargs=tokenization_kwargs,
|
||||
trace_headers=trace_headers,
|
||||
priority=request.priority,
|
||||
data_parallel_rank=data_parallel_rank,
|
||||
)
|
||||
reasoning_ended = None
|
||||
if reasoning_parser:
|
||||
reasoning_ended = reasoning_parser.is_reasoning_end(
|
||||
engine_request.prompt_token_ids or [] # type: ignore[attr-defined]
|
||||
)
|
||||
engine_request.reasoning_ended = reasoning_ended
|
||||
generator = self.engine_client.generate(
|
||||
engine_request,
|
||||
sampling_params,
|
||||
sub_request_id,
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
priority=request.priority,
|
||||
prompt_text=prompt_text,
|
||||
tokenization_kwargs=tokenization_kwargs,
|
||||
data_parallel_rank=data_parallel_rank,
|
||||
reasoning_ended=reasoning_ended,
|
||||
)
|
||||
|
||||
generators.append(generator)
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
from prime_rl.inference.patches import monkey_patch_LRUCacheWorkerLoRAManager, monkey_patch_minimax_m2_for_lora
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_fused_moe_lora_dp,
|
||||
monkey_patch_LRUCacheWorkerLoRAManager,
|
||||
monkey_patch_minimax_m2_for_lora,
|
||||
)
|
||||
|
||||
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
|
||||
monkey_patch_LRUCacheWorkerLoRAManager()
|
||||
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
|
||||
monkey_patch_minimax_m2_for_lora()
|
||||
# NOTE: Fix LoRA + MoE + DP>1 corrupted output (vLLM 0.17.0 bug)
|
||||
# Applied here so it runs inside every worker subprocess, not just the main API server process.
|
||||
monkey_patch_fused_moe_lora_dp()
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user