Compare commits
39
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e466d233e9 | ||
|
|
9ea9fb193e | ||
|
|
91c86b7383 | ||
|
|
d4b30bf3ae | ||
|
|
d5ce4ce84d | ||
|
|
04d067145f | ||
|
|
632ef2b318 | ||
|
|
c8759c370a | ||
|
|
0695f9caa5 | ||
|
|
e0f8a35c78 | ||
|
|
54012df504 | ||
|
|
53b22b55c8 | ||
|
|
c2a5fa466c | ||
|
|
90b074492e | ||
|
|
766e36f000 | ||
|
|
209f76eb52 | ||
|
|
e5c9169566 | ||
|
|
65914f924f | ||
|
|
b67fd12fe6 | ||
|
|
e6998a6f41 | ||
|
|
7f6ca61ecc | ||
|
|
434c9c0a42 | ||
|
|
3979894bae | ||
|
|
63af82343d | ||
|
|
5b5f234053 | ||
|
|
f619e36b63 | ||
|
|
563b37a9c7 | ||
|
|
e7517948f2 | ||
|
|
43f6261454 | ||
|
|
bf7eab0640 | ||
|
|
8d88f5e302 | ||
|
|
c13409e2c1 | ||
|
|
c613ec5631 | ||
|
|
3ce918920f | ||
|
|
517ee5c486 | ||
|
|
b243184d19 | ||
|
|
f3ad435508 | ||
|
|
da9a92a79c | ||
|
|
9589c04de3 |
@@ -7,9 +7,6 @@
|
||||
[submodule "research-environments"]
|
||||
path = deps/research-environments
|
||||
url = git@github.com:PrimeIntellect-ai/research-environments.git
|
||||
[submodule "configs/private"]
|
||||
path = configs/private
|
||||
url = git@github.com:PrimeIntellect-ai/research-configs.git
|
||||
[submodule "pydantic-config"]
|
||||
path = deps/pydantic-config
|
||||
url = https://github.com/PrimeIntellect-ai/pydantic-config
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
|
||||
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
|
||||
- **`orchestrator.seed` removed**: was only consumed by the deleted buffer; no replacement.
|
||||
- **`orchestrator.eval.eval_base_model` → `orchestrator.eval.skip_first_step`** (semantics inverted): `eval_base_model = true` becomes `skip_first_step = false` (the default — run the step-0 eval before any train rollouts). No alias; configs setting `eval_base_model` must rename.
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
|
||||
|
||||
# Build stage - multi-arch base (supports amd64 + arm64)
|
||||
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu22.04 AS builder
|
||||
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04 AS builder
|
||||
LABEL maintainer="prime intellect"
|
||||
LABEL repository="prime-rl"
|
||||
|
||||
|
||||
@@ -55,10 +55,10 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
|
||||
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#vision-language-models) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
|
||||
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
|
||||
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
|
||||
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ❌ |
|
||||
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
|
||||
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
|
||||
| GLM-4 · GLM-4.5 MoE · INTELLECT-3 (`glm4_moe`) | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5-Air`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | yes | ✅ | ✅ |
|
||||
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ❌ | ✅ |
|
||||
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ✅ | ✅ |
|
||||
| Other HF causal LMs | Qwen3 dense, Mistral, … (`impl = "hf"`) | varies | ❌ | ✅ |
|
||||
|
||||
|
||||
@@ -110,6 +110,15 @@ source $HOME/.local/bin/env
|
||||
uv sync --all-extras
|
||||
```
|
||||
|
||||
4.1. On aarch64 hosts: build flash-attn from source for your GPU
|
||||
|
||||
> *NOTE*: aarch64 has no prebuilt flash-attn wheel. This step compiles the CUDA extension for your local GPU (~20-30 minutes). Compute capability is auto-detected from `nvidia-smi`; override with `TORCH_CUDA_ARCH_LIST=9.0` (Hopper) / `10.0` (Blackwell) if needed.
|
||||
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`.
|
||||
|
||||
```bash
|
||||
bash scripts/docker-arm64-post-install.sh
|
||||
```
|
||||
|
||||
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
|
||||
|
||||
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text-v1"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
args = { v1 = true }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference]
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
Submodule configs/private deleted from 70c3503e1d
Vendored
+1
-1
Submodule deps/renderers updated: 35c2407e92...e6dba5ad6c
Vendored
+1
-1
Submodule deps/research-environments updated: c752781984...4c08260f07
Vendored
+1
-1
Submodule deps/verifiers updated: 43016ea6e4...0ad8b4d523
+7
-9
@@ -36,18 +36,17 @@ impl = "custom" # or "hf" to force the HF path
|
||||
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
|
||||
| GPT-OSS (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
|
||||
|
||||
The custom path enables EP, selective activation checkpointing, FP8 training (`model.fp8 = true`, requires SM90+), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
|
||||
The custom path enables you to set EP, CP, selective activation checkpointing, FP8 training (`model.fp8 = true`, requires SM90+), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
|
||||
|
||||
### Expert Parallelism Backends
|
||||
|
||||
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
|
||||
|
||||
- **`torch`** (default): TorchTitan's all-to-all collective. Works everywhere, no extra install.
|
||||
- **`deepep`**: Custom kernels from DeepEP. Faster but requires DeepEP build (`bash scripts/install_deep_gemm.sh`, `bash scripts/install_ep_kernels.sh`) and tuning of `deepep_num_sms` (default 20) and `deepep_token_chunk_size` for your hardware.
|
||||
- **`deepep`**: Utilizes DeepEP's custom all-to-all collectives. This provides better performance if EP dimension spans multiple nodes. We provide pre-built binaries for H100/H200 with cuda runtime 12.9 installed, you can install them by running `uv sync --all-extras`.
|
||||
DeepEP requires some careful tuning to achieve optimal performance, tuning parameters are `deepep_num_sms` and `deepep_token_chunk_size`.
|
||||
|
||||
DeepEP intranode dispatch derives the RDMA channel count as `deepep_num_sms / 2`. Lower SM count leaves more for compute; higher speeds up dispatch. Useful starting points: 16–24 SMs on H100, 20–40 on B200.
|
||||
|
||||
When you enable DeepEP, gradient clipping is auto-disabled (`optim.max_norm` set to `None`) because the kernels don't currently support it.
|
||||
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
|
||||
|
||||
## Multimodal Training
|
||||
|
||||
@@ -80,7 +79,7 @@ language_model_attr = "model.language_model"
|
||||
# freeze_vision_encoder = true # default; set false to fine-tune the encoder
|
||||
```
|
||||
|
||||
A bad attribute path errors immediately — no silent fallbacks. The weight-broadcast key prefix is derived as `{language_model_attr}.layers.` automatically.
|
||||
The weight-broadcast key prefix is derived as `{language_model_attr}.layers.` automatically.
|
||||
|
||||
To add a new model family permanently, append an entry to `VLM_REGISTRY` in `src/prime_rl/utils/vlm.py`.
|
||||
|
||||
@@ -116,7 +115,7 @@ LoRA pairs naturally with [multi-tenant training](#multi-tenant-training) — ea
|
||||
|
||||
## Multi-Tenant Training
|
||||
|
||||
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/src/prime_rl/trainer/runs).
|
||||
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/src/prime_rl/trainer/runs.py).
|
||||
|
||||
## Disaggregated Prefill/Decode Inference
|
||||
|
||||
@@ -138,8 +137,7 @@ curl -s http://<decode_node>:8200/metrics | grep num_requests_waiting
|
||||
|
||||
If prefill queues and decode is idle, add prefill nodes (and vice versa).
|
||||
|
||||
**UCX 1.19 requirement.** NVSHMEM needs UCX ≥ 1.19 for multi-GPU CUDA. Most clusters ship UCX 1.17 via HPC-X, which manifests as `cuStreamCreate: invalid device context` errors during DeepEP internode dispatch. Check with `/opt/hpcx/ucx/bin/ucx_info -v` and, if needed, build from source:
|
||||
|
||||
**UCX 1.19 requirement.** NVSHMEM needs UCX ≥ 1.19 for multi-GPU CUDA. If your cluster doesn't ship with UCX >=1.19, you can build it from source with the following command:
|
||||
```bash
|
||||
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
|
||||
```
|
||||
|
||||
@@ -167,6 +167,22 @@ kwargs = { eps = 1e-8 }
|
||||
|
||||
`AdvantageInputs.rollouts` is a list of `verifiers.RolloutOutput`, so you have access to the full rollout (turns, tool calls, custom metadata) — not just the reward. Use this for anything reward-shaping-like that needs trajectory context.
|
||||
|
||||
### Per-Env Advantage
|
||||
|
||||
`advantage` can be set per training environment. Each env inherits the top-level `[orchestrator.advantage]` when it doesn't set its own, so mixed-env runs can give each env its own advantage computation:
|
||||
|
||||
```toml
|
||||
[orchestrator.advantage]
|
||||
type = "default" # the default every env inherits unless it overrides
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env" # inherits the default above
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "agent-env"
|
||||
advantage = { type = "custom", import_path = "my_module.normalized_advantage" }
|
||||
```
|
||||
|
||||
## Filters
|
||||
|
||||
Filters drop rollouts between scoring and training. Built-ins (composable):
|
||||
|
||||
@@ -129,3 +129,12 @@ What to look for:
|
||||
- **Loss reasonable.** Not NaN, not stuck.
|
||||
|
||||
Don't expect reward to climb meaningfully in 20 steps on a random model.
|
||||
|
||||
### Requirements for merging a new model
|
||||
|
||||
Before merging a new model, you need to ensure the following:
|
||||
|
||||
- The model is correctly registered and defines and all the required methods - such as `convert_hf_layer_to_tt` and `convert_tt_layer_to_hf`.
|
||||
- The small smoke test passes.
|
||||
|
||||
In the PR that adds the new model, you also need to provide a table covering the KL mismatch across 20 steps on `math` environment with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not met, the PR will not be merged (unless reasonable justification is provided). This is to ensure all our models are consistent and their implementations match the implementations in the inference framework.
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
# Inference
|
||||
|
||||
This page covers the inference configuration and the supported features/deployment shapes. It covers how to scale the inference server from a single GPU to 1000s of GPUs that run agentic workloads at the speed of light with all the bells and whistles configured.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Single-Node](#single-node)
|
||||
- [Multi-Node](#multi-node)
|
||||
- [Multi-replica](#multi-replica)
|
||||
- [Wide-EP](#wide-ep)
|
||||
- [P/D Dissagregation](#pd-dissagregation)
|
||||
- [Router](#router)
|
||||
- [Routing policies](#routing-policies)
|
||||
- [Advanced Configuration](#advanced-configuration)
|
||||
- [KV Cache Offload](#kv-cache-offload)
|
||||
- [Optimized P/D disaggregation deployment](#optimized-pd-disaggregation-deployment)
|
||||
- [Other vLLM features](#other-vllm-features)
|
||||
- [Router Replay](#router-replay)
|
||||
|
||||
|
||||
## Overview
|
||||
|
||||
`prime-rl` chooses to use `vLLM` as the inference engine. We aim to stay up-to-date with the latest vLLM features, being at-most 1 version behind the latest stable release. This allows us to use the latest features from vLLM as soon as they are released - such as router replay, CPU KV cache offload, and more.
|
||||
|
||||
We support 3 distinct deployment shapes:
|
||||
- [Single-Node](#single-node) - Runs the inference server on a single node. Useful for debugging, small scale experiments or smaller models. The default deployment shape.
|
||||
- [Multi-Node](#multi-node) - Runs the inference server on multiple nodes. Useful for large scale experiments or larger models, where latency is not a concern - i.e. single turn inference, long context inference, etc.
|
||||
- [Disaggregated](#disaggregated) - Runs the inference server on multiple nodes, but disaggregates the prefill and decode stages. Useful for large scale experiments or larger models, where latency is a concern and multi-node deployment creates very high E2E rollout latency, such as agentic workflows.
|
||||
|
||||
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
|
||||
|
||||
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `router_port`, `backend_port`, etc.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "single_node" # or "multi_node" or "disaggregated"
|
||||
```
|
||||
|
||||
To configure the inference server, you can use the `InferenceConfig` field. This is a config-field that allows you to set the inference server-specific knobs. Most of these are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
|
||||
|
||||
```toml
|
||||
[inference]
|
||||
model = "PrimeIntellect/INTELLECT-3"
|
||||
...
|
||||
```
|
||||
|
||||
We will now walk through the supported features and deployment shapes in detail, starting with the single-node deployment.
|
||||
|
||||
## Single-Node
|
||||
|
||||
The single-node deployment is the default deployment shape. It runs the inference server on a single node. It is useful for debugging, small scale experiments or smaller models. You can configure the single-node deployment with the `SingleNodeInferenceDeploymentConfig` config-field.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "single_node"
|
||||
```
|
||||
|
||||
This deployment shape runs the inference server on a single node, if configured with NVLink enabled, it allows you more freedom in terms of parallelism configurations.
|
||||
|
||||
```toml
|
||||
[inference]
|
||||
enable_expert_parallel = true # defaults to False
|
||||
|
||||
[inference.parallel]
|
||||
tp = 2
|
||||
dp = 4
|
||||
|
||||
[inference.deployment]
|
||||
type = "single_node"
|
||||
```
|
||||
|
||||
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required `orchestrator.max_inflight_requests`. Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
|
||||
|
||||
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.enable_expert_parallel` or `inference.parallel.tp` to maximize the available GPU memory.
|
||||
|
||||
You can also increase the available KV cache memory by enabling `inference.kv_cache_offload`. More details in the [Advanced Configuration](#advanced-configuration) section.
|
||||
|
||||
|
||||
## Multi-Node
|
||||
|
||||
This deployment shape branches into 2 sub-shapes:
|
||||
|
||||
- [Multi-replica](#multi-replica) - Runs the inference server on multiple nodes, but each node runs an independent vLLM replica. You can think of this as a for-loop over single-node deployments.
|
||||
- [Wide-EP](#wide-ep) - This option is gated behind `inference.enable_expert_parallel = true`. It allows you to run the inference server on multiple nodes, allowing you to use multi-node expert parallelism. This is a more advanced feature that is suitable for high-throughput, high-concurrency workloads.
|
||||
|
||||
### Multi-replica
|
||||
|
||||
This deployment shape runs the inference server on multiple nodes, but each node runs an independent vLLM replica.
|
||||
Parallelism configuration is the same as the single-node deployment. The shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.deployment.num_nodes` to the number of nodes you want to run the inference server on.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 2
|
||||
|
||||
[inference]
|
||||
model = "PrimeIntellect/INTELLECT-3"
|
||||
|
||||
[inference.parallel]
|
||||
tp = 2
|
||||
dp = 4
|
||||
```
|
||||
|
||||
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing will be handled by the `vllm-router` instance running on the same node as the 1st replica. We aim to support more advanced routing options, such as `llm-d` or `dynamo` in the future. You can read more about the supported routing options in the [router](#router) section.
|
||||
|
||||
### Wide-EP
|
||||
|
||||
For huge, 200B+ scale models, you might want to use multi-node expert parallelism to maximize the KV-cache space. This deployment shape is defined by setting `inference.deployment.type = "multi_node"` and `inference.enable_expert_parallel = true`.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 2
|
||||
|
||||
[inference]
|
||||
model = "PrimeIntellect/INTELLECT-3"
|
||||
enable_expert_parallel = true
|
||||
|
||||
[inference.parallel]
|
||||
tp = 2
|
||||
dp = 8
|
||||
```
|
||||
|
||||
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tp = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
|
||||
|
||||
## P/D Dissagregation
|
||||
|
||||
This is the most advanced deployment shape. It allows you to disaggregate the prefill and decode stages, with KV cache flowing between them. This is useful for large scale deployments, where there are high requirements on latency, such as agentic workflows spanning 100s of turns.
|
||||
|
||||
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and `inference.deployment.num_prefill_nodes` and `inference.deployment.num_decode_nodes` to the number of nodes you want to run the prefill and decode stages on.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 2
|
||||
num_decode_nodes = 2
|
||||
```
|
||||
|
||||
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode node groups. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of replicas you want to run.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 2
|
||||
num_decode_nodes = 2
|
||||
|
||||
num_prefill_replicas = 2
|
||||
num_decode_replicas = 1
|
||||
```
|
||||
|
||||
Now the total deployment will span 6 nodes - 2x2 for prefill and 1x2 for decode. 2 prefill replicas will run on 2 nodes each - total of 4 nodes for prefill. 1 decode replica will run on 2 nodes for decode.
|
||||
|
||||
We also allow you to configure the total amount of inference replicas - this is useful if you'd like to multiply the above configuration by a factor of `k`, each running behind a separate `vllm-router` instance.
|
||||
|
||||
```toml
|
||||
[deployment] # this is a top-level RL deployment, not inference.deployment!!
|
||||
type = "multi_node"
|
||||
num_train_nodes = 4
|
||||
num_infer_nodes = 6 # this is per-replica
|
||||
|
||||
num_infer_replicas = 3
|
||||
```
|
||||
|
||||
This will run 3 inference replicas, each running on 6 nodes. Each replica will run on 2x2 nodes for prefill and 1x2 nodes for decode. The total deployment will span 18 nodes. This will also spin-up 3 separate `vllm-router` instances.
|
||||
|
||||
|
||||
## Router
|
||||
|
||||
We use our own fork of [vllm-router](https://github.com/PrimeIntellect-ai/router) as the request handler. We plan to support more advanced proxy options in the future.
|
||||
|
||||
Right now, router handles 2 most important things:
|
||||
- Request routing - KV cache re-use and balanced routing
|
||||
- P/D disaggregation - handling the prefill and decode stages separately
|
||||
|
||||
### Routing policies
|
||||
The 2 policies you might want to configure are:
|
||||
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - this works by hashing a request header to determine where to route the request to. You can configure what to hash by setting
|
||||
`orchestrator.student.client.extra_headers_from_state` to the header the `router` expects to be set.
|
||||
|
||||
We set it to a sensible default, that works with all verifiers environments.
|
||||
|
||||
```toml
|
||||
[orchestrator.student.client.extra_headers_from_state]
|
||||
X-Session-ID = "trajectory_id" # this is the default - each rollout has a unique trajectory_id and router expects X-Session-ID
|
||||
```
|
||||
|
||||
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
|
||||
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### KV Cache Offload
|
||||
|
||||
Maximizing KV-Cache space is crucial to support high-concurrency workloads. You can offload the KV cache to CPU memory (and, behind it, disk) by setting `inference.kv_cache_offload`. It is a discriminated config with two composable tiers, `cpu` and `disk`: a `cpu` tier is always required, and an optional `disk` tier is layered behind it (GPU → DRAM → disk). Disk-only is not supported.
|
||||
|
||||
The `type` field selects the backend:
|
||||
|
||||
- `native` — vLLM's built-in offloading. CPU-only uses `OffloadingConnector`; CPU+disk uses `TieringOffloadingSpec` (a CPU primary tier with a filesystem secondary tier). Fully self-contained — no extra processes.
|
||||
- `mooncake` — a [Mooncake](https://github.com/kvcache-ai/Mooncake) **shared distributed store** (SLURM only). One `mooncake_master` + metadata server runs on the head inference node; every inference node runs a `mooncake_client` that contributes its DRAM (and, with `disk`, SSD) segment to that *single* pool. Because blocks are keyed by model + parallel rank + content hash (no instance id), a prefix cached by one node/replica is reusable by all of them over RDMA — pooling every node's CPU RAM into one KV cache. Use `native` for local/single-process runs.
|
||||
|
||||
```toml
|
||||
# Native CPU offload (reserves 128GB of CPU KV cache for this instance)
|
||||
[inference.kv_cache_offload]
|
||||
type = "native"
|
||||
[inference.kv_cache_offload.cpu]
|
||||
num_bytes = 128_000_000_000 # 128GB
|
||||
|
||||
# Native CPU + disk tiering (self-contained)
|
||||
[inference.kv_cache_offload]
|
||||
type = "native"
|
||||
[inference.kv_cache_offload.cpu]
|
||||
num_bytes = 128_000_000_000
|
||||
[inference.kv_cache_offload.disk]
|
||||
path = "/scratch/kv" # disk capacity is bounded by the filesystem
|
||||
|
||||
# Mooncake CPU + disk (per-node distributed store, RDMA)
|
||||
[inference.kv_cache_offload]
|
||||
type = "mooncake"
|
||||
[inference.kv_cache_offload.cpu]
|
||||
num_bytes = 128_000_000_000
|
||||
[inference.kv_cache_offload.disk]
|
||||
path = "/scratch/kv"
|
||||
```
|
||||
|
||||
For `native`, `cpu.num_bytes` is the aggregate CPU KV pool for the instance (vLLM shards it across workers). For `mooncake`, `cpu.num_bytes` is the DRAM each node contributes to the shared pool (so the total pool ≈ `num_bytes × #inference-nodes`); the store uses RDMA, so it requires an RDMA-capable fabric. Enabling offload automatically enables prefix caching.
|
||||
|
||||
|
||||
### Optimized P/D disaggregation deployment
|
||||
|
||||
For optimal P/D disaggregation deployment, we automatically set the decode `all2all_backend` to `deepep_low_latency` and the prefill `all2all_backend` to `deepep_high_throughput`. We currently don't support customizing all2all backends for P/D disaggragation out of the box. You can do this by overriding the slurm template only.
|
||||
|
||||
For KV cache transfer, we utilize the NIXL connector. This is the default and only currently supported connector. We aim to support more advanced options, such as D->P transfer, or Mooncake Connector in the future.
|
||||
|
||||
For configuring various knobs with environment variables, we enable you to configure prefill and decode environment variables separately. This is useful if you want to configure different environment variables for the prefill and decode stages.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
|
||||
prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip"}
|
||||
decode_env_overrides = {"VLLM_DEEP_GEMM_WARMUP"="skip"}
|
||||
```
|
||||
|
||||
### Other vLLM features
|
||||
We support various other vLLM features. Some of those, such as `enable_dbo`, `enable_eplb` are exposed as a top-level config fields. For those that are not, you can configure them by setting `inference.vllm_extra` to the desired value.
|
||||
|
||||
```toml
|
||||
[inference.vllm_extra]
|
||||
headless = true
|
||||
```
|
||||
|
||||
### Router Replay
|
||||
|
||||
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
|
||||
|
||||
To enable router replay, you can set `inference.enable_return_routed_experts = true`.
|
||||
|
||||
```toml
|
||||
[trainer]
|
||||
enable_router_replay = true # this will also auto-set the inference.enable_return_routed_experts = true
|
||||
|
||||
[inference]
|
||||
enable_return_routed_experts = true
|
||||
```
|
||||
|
||||
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend increasing `orchestrator.*.env.num_workers` to allow for more parallelization on the verifiers side.
|
||||
|
||||
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
|
||||
@@ -7,6 +7,7 @@
|
||||
"overview",
|
||||
"configuration",
|
||||
"training",
|
||||
"inference",
|
||||
"scaling",
|
||||
"algorithms",
|
||||
"advanced",
|
||||
|
||||
+4
-3
@@ -8,9 +8,9 @@ A `prime-rl` RL run is three cooperating processes:
|
||||
|
||||

|
||||
|
||||
- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). Supports data + tensor + expert parallelism (with `deepep` and `flashinfer` all-to-all backends and EPLB), FP8 inference, prefill/decode disaggregation behind a `vllm-router`, CPU KV-cache offload, and *router replay* (the routed-expert mask is returned to the trainer for FP8 MoE numerical parity). Weights are pushed in place through a custom `update_weights` endpoint over filesystem or NCCL transports.
|
||||
- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). We are trying to stay up-to-date with the latest vLLM features, you can read more about the supported features and deployment options in the dedicated [inference documentation](inference.md).
|
||||
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
|
||||
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment).
|
||||
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
|
||||
|
||||
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses the filesystem (or NCCL for synchronous setups). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
|
||||
|
||||
@@ -20,7 +20,7 @@ The three processes communicate through configurable transports — by default t
|
||||
curl -sSL https://raw.githubusercontent.com/PrimeIntellect-ai/prime-rl/main/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`research-environments`](https://github.com/PrimeIntellect-ai/research-environments) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, MoE-only installs (DeepGEMM / DeepEP / NIXL), or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
|
||||
The script clones the repo, initializes the [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) / [`renderers`](https://github.com/PrimeIntellect-ai/renderers) / [`research-environments`](https://github.com/PrimeIntellect-ai/research-environments) submodules, installs `uv`, and runs `uv sync --all-extras`. For manual setup, or troubleshooting, see the [README](https://github.com/PrimeIntellect-ai/prime-rl#setup).
|
||||
|
||||
You need at least one NVIDIA GPU (RTX 3090/4090/5090, A100, H100, H200, or B200). Single-GPU runs are supported for debugging; production RL is typically 1× inference node + 1+ trainer nodes.
|
||||
|
||||
@@ -38,6 +38,7 @@ The `rl` entrypoint reads `examples/reverse_text/rl.toml`, splits it into per-pr
|
||||
|
||||
- **[Configuration](configuration.md)** — TOML composition, CLI overrides, dry-run.
|
||||
- **[Training](training.md)** — Launch and observe RL and SFT runs.
|
||||
- **[Inference](inference.md)** — vLLM-backed server (or fleet) holding the current policy.
|
||||
- **[Scaling](scaling.md)** — Single-GPU through multi-node clusters via FSDP / EP / CP and SLURM.
|
||||
- **[Algorithms](algorithms.md)** — Async semantics, loss / advantage / filter plugins, trajectory merging.
|
||||
- **[Advanced](advanced.md)** — Custom modeling, multimodal, LoRA, multi-tenant, P/D inference.
|
||||
|
||||
+11
-4
@@ -1,6 +1,6 @@
|
||||
# Scaling
|
||||
|
||||
This page covers how to scale `prime-rl` from a single GPU to a 1000-GPU cluster: single-node and multi-node deployments, FSDP / expert parallelism / context parallelism, and throughput benchmarking. For knobs that fit on one box, see [Training](training.md) first. For prefill/decode disaggregated inference, see [Advanced](advanced.md#disaggregated-prefilldecode-inference).
|
||||
This page covers how to scale `prime-rl` from a single GPU to a 1000-GPU cluster: single-node and multi-node deployments, FSDP / expert parallelism / context parallelism, and throughput benchmarking. See [Training](training.md) for detailed documentation of the trainer configuration and [Inference](inference.md) for the inference configuration.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -90,7 +90,7 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
|
||||
|
||||
### Expert Parallelism
|
||||
|
||||
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
|
||||
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
@@ -103,14 +103,14 @@ ep_comm_backend = "torch" # or "deepep"
|
||||
|
||||
### Context Parallelism
|
||||
|
||||
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Only available with the custom impl and flash-attention.
|
||||
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. We reccomend using `ulysses` style CP for most of the models to get the most throughput. Some models (e.g. GLM-5) only support `ring` style CP. Wrong setting will be rejected on validation.
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2" # or fa3 / fa4
|
||||
cp = 2 # CP degree
|
||||
cp_style = "ring" # "ulysses" for non-FA kernels
|
||||
cp_style = "ulysses" # "ring"
|
||||
```
|
||||
|
||||
### Activation Checkpointing and Offloading
|
||||
@@ -129,6 +129,13 @@ mode = "selective"
|
||||
targets = ["norm", "attn_proj"] # see Reference for the full list per architecture
|
||||
```
|
||||
|
||||
We reccomend also using `ac_offloading` and `ac_offloading.max_inflight_activations = 5` to further reduce the memory footprint in tradeoff for some throughput. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput:
|
||||
|
||||
```toml
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
```
|
||||
|
||||
### Optimizer Offloading
|
||||
|
||||
Offloading optimizer states to CPU is a near-free memory win at low GPU counts:
|
||||
|
||||
@@ -5,7 +5,7 @@ from typing import Annotated, Any, Literal, TypeAlias
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic_config import BaseConfig
|
||||
|
||||
from prime_rl.configs.shared import BaseModelConfig, SlurmConfig
|
||||
from prime_rl.configs.shared import BaseModelConfig, LogConfig, SlurmConfig
|
||||
from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
|
||||
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
|
||||
|
||||
@@ -86,9 +86,71 @@ class WeightBroadcastConfig(BaseConfig):
|
||||
"""Weight broadcast transport."""
|
||||
|
||||
|
||||
class KVCacheOffloadConfig(BaseConfig):
|
||||
cpu_bytes: int = Field(1_000_000_000, gt=0)
|
||||
"""CPU bytes available for KV cache offloading per worker."""
|
||||
class CPUOffloadTier(BaseConfig):
|
||||
num_bytes: int = Field(..., gt=0)
|
||||
"""CPU/DRAM offload capacity. For the ``native`` backend this is vLLM's aggregate ``cpu_bytes_to_use`` (scaled across workers internally). For the ``mooncake`` backend this is the per-node store client's DRAM segment (``-global_segment_size``)."""
|
||||
|
||||
|
||||
class DiskOffloadTier(BaseConfig):
|
||||
path: Path
|
||||
"""Filesystem root for the disk tier. For ``native`` this is the ``fs_python`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota)."""
|
||||
|
||||
|
||||
class BaseKVCacheOffloadConfig(BaseConfig):
|
||||
cpu: CPUOffloadTier | None = None
|
||||
"""CPU/DRAM offload tier. Always required — disk-only offload is not supported."""
|
||||
|
||||
disk: DiskOffloadTier | None = None
|
||||
"""Optional disk tier, layered behind the CPU tier (GPU → DRAM → disk)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def valid_tiers(self):
|
||||
# Both backends support only two shapes: cpu-only or cpu+disk. Native disk
|
||||
# tiering needs a CPU primary tier; Mooncake standalone-store needs a DRAM
|
||||
# staging tier. Disk-only is rejected for both.
|
||||
if self.cpu is None:
|
||||
raise ValueError("inference.kv_cache_offload requires a cpu tier (disk-only offload is not supported).")
|
||||
return self
|
||||
|
||||
|
||||
class NativeKVCacheOffloadConfig(BaseKVCacheOffloadConfig):
|
||||
type: Literal["native"] = "native"
|
||||
"""vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs_python`` disk secondary). Fully self-contained — no external processes."""
|
||||
|
||||
def to_connector_dict(self) -> dict[str, Any]:
|
||||
assert self.cpu is not None
|
||||
extra: dict[str, Any] = {"cpu_bytes_to_use": int(self.cpu.num_bytes)}
|
||||
if self.disk is not None:
|
||||
extra["spec_name"] = "TieringOffloadingSpec"
|
||||
extra["secondary_tiers"] = [{"type": "fs_python", "root_dir": str(self.disk.path)}]
|
||||
return {
|
||||
"kv_connector": "OffloadingConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": extra,
|
||||
}
|
||||
|
||||
|
||||
class MooncakeKVCacheOffloadConfig(BaseKVCacheOffloadConfig):
|
||||
type: Literal["mooncake"] = "mooncake"
|
||||
"""Mooncake distributed store offloading (SLURM only). One ``mooncake_master`` + metadata server runs on the head inference node; every node runs a ``mooncake_client`` contributing its segment to the single shared pool, so prefixes cached on any node are reusable by all. The cpu tier sizes each node's DRAM segment; the optional disk tier adds an SSD tier."""
|
||||
|
||||
device_name: str = ""
|
||||
"""RDMA device name(s) for the store (empty = auto-detect)."""
|
||||
|
||||
def to_connector_dict(self) -> dict[str, Any]:
|
||||
# Addresses/sizes/tiers are realized by the per-node store launch in the sbatch
|
||||
# template (MOONCAKE_CONFIG_PATH JSON); blocks are keyed by model + parallel rank +
|
||||
# content hash (no instance id), so the shared pool is reused across nodes/replicas.
|
||||
return {
|
||||
"kv_connector": "MooncakeStoreConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {},
|
||||
}
|
||||
|
||||
|
||||
KVCacheOffloadConfig: TypeAlias = Annotated[
|
||||
NativeKVCacheOffloadConfig | MooncakeKVCacheOffloadConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
# Valid vLLM max_lora_rank values (from vllm/config/lora.py)
|
||||
@@ -105,10 +167,33 @@ All2AllBackend = Literal[
|
||||
]
|
||||
|
||||
|
||||
class VllmRouterConfig(BaseConfig):
|
||||
"""PrimeIntellect vllm-router fronting the per-rank (external-LB) endpoints."""
|
||||
|
||||
type: Literal["vllm-router"] = "vllm-router"
|
||||
|
||||
port: int = 8000
|
||||
"""Port the router listens on — becomes the client-facing router URL."""
|
||||
|
||||
policy: str = "consistent_hash"
|
||||
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
|
||||
|
||||
|
||||
# Discriminated on ``type`` so additional router backends can be added to the
|
||||
# union (a single member needs no discriminator yet).
|
||||
RouterConfig: TypeAlias = VllmRouterConfig
|
||||
|
||||
|
||||
class BaseInferenceDeploymentConfig(BaseConfig):
|
||||
gpus_per_node: int = 8
|
||||
"""GPUs per node."""
|
||||
|
||||
backend_port: int = 8100
|
||||
"""Port for the per-rank vLLM backend instances."""
|
||||
|
||||
router: RouterConfig = VllmRouterConfig()
|
||||
"""Router fronting the per-rank endpoints."""
|
||||
|
||||
|
||||
class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
type: Literal["single_node"] = "single_node"
|
||||
@@ -121,15 +206,6 @@ class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
num_nodes: int = Field(2, ge=1)
|
||||
"""Inference nodes."""
|
||||
|
||||
router_port: int = 8000
|
||||
"""Port for the vllm-router."""
|
||||
|
||||
backend_port: int = 8100
|
||||
"""Port for vLLM backend instances."""
|
||||
|
||||
router_policy: str = "consistent_hash"
|
||||
"""vllm-router routing policy (e.g. ``consistent_hash``, ``round_robin``)."""
|
||||
|
||||
|
||||
# Disaggregated prefill/decode inference. Each replica is split into separate
|
||||
# prefill and decode node groups. Requires NIXL for KV transfer and a vllm-router
|
||||
@@ -152,18 +228,12 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
num_decode_replicas: int = Field(1, ge=1)
|
||||
"""Independent decode vLLM instances. Must evenly divide ``num_decode_nodes``."""
|
||||
|
||||
router_port: int = 8000
|
||||
"""Port for the vllm-router on each replica."""
|
||||
|
||||
prefill_port: int = 8100
|
||||
"""Port for prefill vLLM instances."""
|
||||
|
||||
decode_port: int = 8200
|
||||
"""Port for decode vLLM instances."""
|
||||
|
||||
router_policy: str = "consistent_hash"
|
||||
"""vllm-router routing policy (e.g. ``consistent_hash``, ``round_robin``)."""
|
||||
|
||||
prefill_env_overrides: dict[str, str] = {}
|
||||
"""Extra environment variables exported only on prefill nodes."""
|
||||
|
||||
@@ -207,6 +277,9 @@ class InferenceConfig(BaseConfig):
|
||||
parallel: ParallelConfig = ParallelConfig()
|
||||
"""Multi-node and multi-GPU parallelism (TP, DP, PP)."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
"""Logging configuration."""
|
||||
|
||||
enable_lora: bool = False
|
||||
"""Enable LoRA. Forwarded as ``--enable-lora``."""
|
||||
|
||||
@@ -256,17 +329,20 @@ class InferenceConfig(BaseConfig):
|
||||
"""Enable dual batch overlap (DBO). Forwarded as ``--enable-dbo``."""
|
||||
|
||||
use_deep_gemm: bool = False
|
||||
"""Enable vLLM DeepGEMM FP8 kernels. Only works with per-tensor FP8 quantization (e.g. GLM-5-FP8)."""
|
||||
"""Enable vLLM DeepGEMM FP8 kernels ``VLLM_USE_DEEP_GEMM=1``. Only works with block-wise FP8 quantization (e.g. GLM-5-FP8)."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig = WeightBroadcastConfig()
|
||||
|
||||
kv_cache_offload: KVCacheOffloadConfig | None = None
|
||||
"""CPU KV cache offload for inference workers. Standard inference uses vLLM's ``OffloadingConnector``. Disaggregated P/D deployments combine it with NIXL through ``MultiConnector`` in the SLURM launcher."""
|
||||
"""KV cache offload for inference workers, as composable CPU/disk tiers. Discriminated on ``type``: ``native`` (vLLM ``OffloadingConnector``/``TieringOffloadingSpec``, self-contained) or ``mooncake`` (per-node Mooncake distributed store). Disaggregated P/D combines the chosen connector with NIXL through ``MultiConnector``."""
|
||||
|
||||
use_pd_kv_transfer: bool = False
|
||||
"""Auto-set for disaggregated P/D: emit the NIXL transfer connector. Persisted into the per-node config (which drops ``deployment``) so the connector is still built per worker. Not meant to be set by hand."""
|
||||
|
||||
enable_return_routed_experts: bool = False
|
||||
"""Return routed experts in responses. Forwarded as ``--enable-return-routed-experts``."""
|
||||
|
||||
enable_fp32_lm_head: bool = False
|
||||
enable_fp32_lm_head: bool = True
|
||||
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
|
||||
|
||||
vllm_extra: dict[str, Any] = {}
|
||||
@@ -289,8 +365,8 @@ class InferenceConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
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.")
|
||||
if self.deployment.type in ("multi_node", "disaggregated") and self.slurm is None:
|
||||
raise ValueError("Must use SLURM for multi-node / disaggregated deployment.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -307,6 +383,7 @@ class InferenceConfig(BaseConfig):
|
||||
def auto_setup_disaggregated(self):
|
||||
"""Auto-configure inference for disaggregated P/D: enable EP and compute DP."""
|
||||
if self.deployment.type == "disaggregated":
|
||||
self.use_pd_kv_transfer = True
|
||||
if "enable_expert_parallel" not in self.model_fields_set:
|
||||
self.enable_expert_parallel = True
|
||||
if "enable_eplb" not in self.model_fields_set:
|
||||
@@ -368,6 +445,35 @@ class InferenceConfig(BaseConfig):
|
||||
self.api_server_count = 1 # LoRA requires only one API server
|
||||
return self
|
||||
|
||||
def build_kv_transfer_config(self) -> dict[str, Any] | None:
|
||||
"""Build the single vLLM ``kv_transfer_config`` from the transfer + offload connectors.
|
||||
|
||||
Disaggregated P/D always uses NIXL for prefill→decode transfer. KV cache offload (if
|
||||
configured) contributes its own connector. When both are present they are composed via
|
||||
``MultiConnector``. Returns None when neither applies.
|
||||
"""
|
||||
connectors: list[dict[str, Any]] = []
|
||||
if self.use_pd_kv_transfer:
|
||||
connectors.append(
|
||||
{
|
||||
"kv_connector": "NixlConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {"num_threads": 1},
|
||||
}
|
||||
)
|
||||
if self.kv_cache_offload is not None:
|
||||
connectors.append(self.kv_cache_offload.to_connector_dict())
|
||||
|
||||
if not connectors:
|
||||
return None
|
||||
if len(connectors) == 1:
|
||||
return connectors[0]
|
||||
return {
|
||||
"kv_connector": "MultiConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {"connectors": connectors},
|
||||
}
|
||||
|
||||
def to_vllm(self) -> Namespace:
|
||||
"""Convert InferenceConfig to vLLM-compatible Namespace."""
|
||||
namespace = Namespace()
|
||||
@@ -411,18 +517,9 @@ class InferenceConfig(BaseConfig):
|
||||
# Set `logprobs_mode` to `processed_logprobs` by default
|
||||
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
|
||||
|
||||
if self.kv_cache_offload is not None:
|
||||
rsetattr(
|
||||
namespace,
|
||||
"kv_transfer_config",
|
||||
{
|
||||
"kv_connector": "OffloadingConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {
|
||||
"cpu_bytes_to_use": int(self.kv_cache_offload.cpu_bytes),
|
||||
},
|
||||
},
|
||||
)
|
||||
kv_transfer_config = self.build_kv_transfer_config()
|
||||
if kv_transfer_config is not None:
|
||||
rsetattr(namespace, "kv_transfer_config", kv_transfer_config)
|
||||
|
||||
# Pass prime-rl-specific flags through vLLM's additional_config dict;
|
||||
# workers read these via get_current_vllm_config().additional_config.
|
||||
|
||||
@@ -143,6 +143,49 @@ class EvalSamplingConfig(BaseConfig):
|
||||
return data
|
||||
|
||||
|
||||
class TokensLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["tokens"] = "tokens"
|
||||
|
||||
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on model completion tokens. Finite and non-negative."""
|
||||
|
||||
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
|
||||
|
||||
|
||||
class TurnsLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["turns"] = "turns"
|
||||
|
||||
|
||||
LengthPenaltyConfig: TypeAlias = Annotated[
|
||||
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class DefaultAdvantageConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
length_penalty: LengthPenaltyConfig | None = None
|
||||
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseConfig):
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
import_path: str
|
||||
"""Import path to the advantage function (e.g. ``my_module.my_advantage``)."""
|
||||
|
||||
kwargs: dict[str, Any] = Field(default_factory=dict)
|
||||
"""Kwargs forwarded to the advantage function."""
|
||||
|
||||
|
||||
AdvantageConfig: TypeAlias = Annotated[
|
||||
DefaultAdvantageConfig | CustomAdvantageConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class EnvConfig(BaseConfig):
|
||||
id: str = "reverse-text"
|
||||
"""Registered verifiers environment ID (e.g. ``math-env``, ``primeintellect/math-env``). May include an ``@version`` suffix for installation."""
|
||||
@@ -214,6 +257,11 @@ class TrainEnvConfig(EnvConfig):
|
||||
"""Rollouts generated per example for GRPO group-relative advantages.
|
||||
Inherits from ``orchestrator.group_size`` when unset."""
|
||||
|
||||
advantage: AdvantageConfig | None = None
|
||||
"""Advantage strategy for this env's GRPO groups. Inherits from the top-level
|
||||
``orchestrator.advantage`` when unset; set a different ``default``/``custom``
|
||||
config to give this env its own advantage computation."""
|
||||
|
||||
|
||||
class EvalEnvConfig(EnvConfig):
|
||||
sampling: EvalSamplingConfig = EvalSamplingConfig()
|
||||
@@ -374,49 +422,6 @@ class CheckpointConfig(BaseConfig):
|
||||
"""Skip loading the progress from checkpoint."""
|
||||
|
||||
|
||||
class TokensLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["tokens"] = "tokens"
|
||||
|
||||
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on model completion tokens. Finite and non-negative."""
|
||||
|
||||
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
|
||||
|
||||
|
||||
class TurnsLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["turns"] = "turns"
|
||||
|
||||
|
||||
LengthPenaltyConfig: TypeAlias = Annotated[
|
||||
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class DefaultAdvantageConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
length_penalty: LengthPenaltyConfig | None = None
|
||||
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseConfig):
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
import_path: str
|
||||
"""Import path to the advantage function (e.g. ``my_module.my_advantage``)."""
|
||||
|
||||
kwargs: dict[str, Any] = Field(default_factory=dict)
|
||||
"""Kwargs forwarded to the advantage function."""
|
||||
|
||||
|
||||
AdvantageConfig: TypeAlias = Annotated[
|
||||
DefaultAdvantageConfig | CustomAdvantageConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
# Flags rare tokens generated at high entropy (Section 5.2, https://arxiv.org/abs/2510.02387).
|
||||
class GibberishFilterConfig(BaseConfig):
|
||||
type: Literal["gibberish"] = "gibberish"
|
||||
@@ -517,7 +522,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
"""Typed renderer config (``renderers.RendererConfig`` discriminated
|
||||
union). Defaults to ``"auto"``, which resolves from
|
||||
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. ``None``
|
||||
opts into MITO (``openai_chat_completions``); SFT mode forces this."""
|
||||
opts into MITO (``openai_chat_completions``)."""
|
||||
|
||||
pool_size: int | None = Field(None, ge=1)
|
||||
"""Number of renderer slots shared across concurrent rollouts. Bump
|
||||
@@ -754,11 +759,10 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _force_no_renderer_for_sft(self):
|
||||
"""SFT rolls out via the teacher's plain chat-completions endpoint; the
|
||||
renderer client doesn't apply. Force ``renderer=None`` so the user
|
||||
doesn't have to remember to set it. Declared before the renderer
|
||||
validators below so they see the corrected value."""
|
||||
if self.training_mode == "sft":
|
||||
"""Teacher-backed SFT rolls out via the teacher's plain chat-completions
|
||||
endpoint; the renderer client doesn't apply. When no teacher is
|
||||
configured, SFT uses the student rollout path and keeps the renderer."""
|
||||
if self.training_mode == "sft" and self.teacher is not None:
|
||||
self.renderer = None
|
||||
return self
|
||||
|
||||
@@ -768,8 +772,8 @@ class OrchestratorConfig(BaseConfig):
|
||||
has_teacher = self.teacher is not None
|
||||
if self.training_mode == "rl" and has_teacher:
|
||||
raise ValueError("orchestrator.teacher must not be set when training_mode = 'rl'.")
|
||||
if self.training_mode in ("opd", "sft") and not has_teacher:
|
||||
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
|
||||
if self.training_mode == "opd" and not has_teacher:
|
||||
raise ValueError("orchestrator.teacher must be configured when training_mode = 'opd'.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -876,6 +880,11 @@ class OrchestratorConfig(BaseConfig):
|
||||
if "group_size" not in env_cfg.model_fields_set:
|
||||
env_cfg.group_size = self.group_size
|
||||
|
||||
# Propagate the top-level ``advantage`` into each train env that didn't set its own.
|
||||
for env_cfg in self.train.env:
|
||||
if "advantage" not in env_cfg.model_fields_set:
|
||||
env_cfg.advantage = self.advantage
|
||||
|
||||
# Resolve train env num_workers from max_inflight_rollouts
|
||||
for env_cfg in self.train.env:
|
||||
if env_cfg.num_workers == "auto":
|
||||
|
||||
@@ -51,10 +51,10 @@ class RLExperimentalConfig(BaseConfig):
|
||||
|
||||
class SharedLogConfig(BaseConfig):
|
||||
level: str | None = None
|
||||
"""Log level for trainer and orchestrator. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
|
||||
"""Log level for trainer, orchestrator, and inference. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
|
||||
|
||||
json_logging: bool = False
|
||||
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.)."""
|
||||
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.). Propagated to trainer, orchestrator, and inference."""
|
||||
|
||||
|
||||
class SharedWandbConfig(BaseConfig):
|
||||
@@ -448,6 +448,20 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_mooncake_offload_requires_slurm(self):
|
||||
if (
|
||||
self.slurm is None
|
||||
and self.inference is not None
|
||||
and self.inference.kv_cache_offload is not None
|
||||
and self.inference.kv_cache_offload.type == "mooncake"
|
||||
):
|
||||
raise ValueError(
|
||||
"Mooncake KV offload requires SLURM — the per-node store is launched by the sbatch "
|
||||
"template. Use inference.kv_cache_offload.type='native' for local runs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_deployment(self):
|
||||
if self.deployment.type == "single_node": # single-node
|
||||
@@ -534,11 +548,14 @@ class RLConfig(BaseConfig):
|
||||
self.inference.api_server_count = dp_per_node
|
||||
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
|
||||
# Compute inference_world_size from actual worker count per server:
|
||||
# each api_server runs tp workers that participate in collective_rpc.
|
||||
api_server_count = self.inference.api_server_count if self.inference else 1
|
||||
tp = self.inference.parallel.tp if self.inference else 1
|
||||
total_infer_workers = self.deployment.total_infer_nodes * api_server_count * tp
|
||||
# Every allocated inference GPU is a NCCL rank in the weight broadcast.
|
||||
# The external-LB launcher starts dp_per_node (= gpus_per_node / tp)
|
||||
# TP-sharded servers per node, i.e. gpus_per_node workers per node, so use
|
||||
# the GPU count directly. Deriving it from api_server_count double-counts:
|
||||
# api_server_count can resolve to the *global* DP size, making the node
|
||||
# factor count twice and NCCL wait for ranks that never connect. Matches
|
||||
# the disaggregated path below.
|
||||
total_infer_workers = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
|
||||
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_workers
|
||||
@@ -566,7 +583,13 @@ class RLConfig(BaseConfig):
|
||||
|
||||
total_infer_gpus = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
|
||||
if "inference_metrics_roles" not in self.orchestrator.model_fields_set:
|
||||
role_order = ["prefill"] * infer_deploy.num_prefill_nodes + ["decode"] * infer_deploy.num_decode_nodes
|
||||
# External-LB: one admin client per DP rank, so roles expand per rank
|
||||
# (stride = dp_local = gpus_per_node / tp). ADMIN_URLS lists all prefill
|
||||
# ranks, then all decode ranks, per replica — match that order.
|
||||
stride = self.deployment.gpus_per_node // self.inference.parallel.tp
|
||||
role_order = ["prefill"] * (infer_deploy.num_prefill_nodes * stride) + ["decode"] * (
|
||||
infer_deploy.num_decode_nodes * stride
|
||||
)
|
||||
self.orchestrator.inference_metrics_roles = role_order * self.deployment.num_infer_replicas
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
|
||||
assert self.trainer.weight_broadcast.type == "nccl"
|
||||
|
||||
@@ -84,8 +84,13 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
)
|
||||
|
||||
# [log]
|
||||
propagate("log.level", "trainer.log.level", "orchestrator.log.level")
|
||||
propagate("log.json_logging", "trainer.log.json_logging", "orchestrator.log.json_logging")
|
||||
propagate("log.level", "trainer.log.level", "orchestrator.log.level", "inference.log.level")
|
||||
propagate(
|
||||
"log.json_logging",
|
||||
"trainer.log.json_logging",
|
||||
"orchestrator.log.json_logging",
|
||||
"inference.log.json_logging",
|
||||
)
|
||||
|
||||
# [ckpt] leaves. (Bare empty ``[ckpt]`` block enablement is at the end.)
|
||||
# ``orchestrator.ckpt`` has no ``output_dir`` field — trainer-only.
|
||||
@@ -127,6 +132,12 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
propagate("max_steps", "trainer.max_steps", "orchestrator.max_steps")
|
||||
propagate("seq_len", "trainer.model.seq_len", "orchestrator.seq_len")
|
||||
|
||||
# [slurm] → inference: a multi-node RL run drives its inference deployment under
|
||||
# the same SLURM allocation, so the nested inference inherits [slurm]. This is
|
||||
# what lets the nested InferenceConfig's multi-node / disaggregated SLURM check
|
||||
# pass (the per-rank inference.toml drops slurm, so each rank still runs locally).
|
||||
propagate("slurm", "inference.slurm")
|
||||
|
||||
# output_dir: orchestrator gets a ``/run_default`` subdir so trainer +
|
||||
# orchestrator nest under the same experiment root without colliding.
|
||||
# Conflicts are reported against the *transformed* sub-config value, not
|
||||
|
||||
+48
-79
@@ -6,6 +6,7 @@ readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"prime-rl-configs",
|
||||
"prime-pydantic-config",
|
||||
"beartype>=0.21.0",
|
||||
"datasets>=4.0.0",
|
||||
"jaxtyping>=0.3.2",
|
||||
@@ -17,8 +18,9 @@ dependencies = [
|
||||
"torchvision",
|
||||
"torchaudio",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers",
|
||||
"vllm>=0.21.0",
|
||||
"transformers==5.6.2",
|
||||
"vllm>=0.22.0",
|
||||
"mooncake-transfer-engine>=0.3.10.post2",
|
||||
"wandb>=0.26.1",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.6.4",
|
||||
@@ -26,6 +28,7 @@ dependencies = [
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
"openai>=1.106.1",
|
||||
"orjson>=3.11.0",
|
||||
"rich>=14.0.0",
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
@@ -76,7 +79,6 @@ envs = [
|
||||
"math-python",
|
||||
"math500",
|
||||
"mini-swe-agent-plus",
|
||||
"mini-swe-agent-plus-rlm",
|
||||
"mmlu-pro",
|
||||
"opencode-cp",
|
||||
"opencode-deepdive",
|
||||
@@ -89,6 +91,7 @@ envs = [
|
||||
"simpleqa-verified",
|
||||
"tau2-bench",
|
||||
"wiki-search",
|
||||
"wordle",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
@@ -127,44 +130,6 @@ dev = [
|
||||
"ruff>=0.12.1",
|
||||
]
|
||||
|
||||
|
||||
[tool.uv.workspace]
|
||||
members = [
|
||||
"packages/prime-rl-configs",
|
||||
"deps/pydantic-config",
|
||||
"deps/verifiers",
|
||||
"deps/renderers",
|
||||
"deps/verifiers/environments/alphabet_sort",
|
||||
"deps/verifiers/environments/math_python",
|
||||
"deps/verifiers/environments/reverse_text",
|
||||
"deps/verifiers/environments/wiki_search",
|
||||
"deps/research-environments/environments/aime2024",
|
||||
"deps/research-environments/environments/aime2025",
|
||||
"deps/research-environments/environments/code_env",
|
||||
"deps/research-environments/environments/color_codeword",
|
||||
"deps/research-environments/environments/deepdive",
|
||||
"deps/research-environments/environments/general_agent",
|
||||
"deps/research-environments/environments/gpqa",
|
||||
"deps/research-environments/environments/hle",
|
||||
"deps/research-environments/environments/ifeval",
|
||||
"deps/research-environments/environments/livecodebench",
|
||||
"deps/research-environments/environments/logic_env",
|
||||
"deps/research-environments/environments/math500",
|
||||
"deps/research-environments/environments/math_env",
|
||||
"deps/research-environments/environments/mini_swe_agent_plus",
|
||||
"deps/research-environments/environments/mini_swe_agent_plus_rlm",
|
||||
"deps/research-environments/environments/mmlu_pro",
|
||||
"deps/research-environments/environments/opencode_cp",
|
||||
"deps/research-environments/environments/opencode_deepdive",
|
||||
"deps/research-environments/environments/opencode_math",
|
||||
"deps/research-environments/environments/opencode_science",
|
||||
"deps/research-environments/environments/opencode_swe",
|
||||
"deps/research-environments/environments/rlm_swe",
|
||||
"deps/research-environments/environments/science_env",
|
||||
"deps/research-environments/environments/simpleqa_verified",
|
||||
"deps/research-environments/environments/tau2_bench",
|
||||
]
|
||||
|
||||
[tool.uv]
|
||||
# Enforce a uv version that supports the friendly-duration form
|
||||
# (`"7 days"`) in the static pyproject parser. Older uvs silently parse
|
||||
@@ -183,9 +148,10 @@ environments = [
|
||||
override-dependencies = [
|
||||
"nvidia-cudnn-cu12>=9.15",
|
||||
"nvidia-cutlass-dsl>=4.4.1",
|
||||
"transformers>=5.1.0.dev0",
|
||||
"transformers==5.6.2",
|
||||
"torch>=2.9.0",
|
||||
"openenv-core",
|
||||
"verifiers[packages]>=0.1.15.dev150",
|
||||
]
|
||||
|
||||
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
|
||||
@@ -220,6 +186,8 @@ prime-tunnel = false
|
||||
prime-evals = false
|
||||
verifiers = false
|
||||
renderers = false
|
||||
tasksets = false
|
||||
harnesses = false
|
||||
prime-pydantic-config = false
|
||||
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
|
||||
vllm-router = false
|
||||
@@ -229,50 +197,51 @@ deep-gemm = false
|
||||
nixl-cu12 = false
|
||||
|
||||
[tool.uv.sources]
|
||||
prime-rl-configs = { workspace = true }
|
||||
verifiers = { workspace = true }
|
||||
renderers = { workspace = true }
|
||||
aime2024 = { workspace = true }
|
||||
aime2025 = { workspace = true }
|
||||
alphabet-sort = { workspace = true }
|
||||
code-env = { workspace = true }
|
||||
color-codeword = { workspace = true }
|
||||
deepdive = { workspace = true }
|
||||
general-agent = { workspace = true }
|
||||
gpqa = { workspace = true }
|
||||
hle = { workspace = true }
|
||||
ifeval = { workspace = true }
|
||||
livecodebench = { workspace = true }
|
||||
logic-env = { workspace = true }
|
||||
math-env = { workspace = true }
|
||||
math-python = { workspace = true }
|
||||
math500 = { workspace = true }
|
||||
mini-swe-agent-plus = { workspace = true }
|
||||
mini-swe-agent-plus-rlm = { workspace = true }
|
||||
mmlu-pro = { workspace = true }
|
||||
opencode-cp = { workspace = true }
|
||||
opencode-deepdive = { workspace = true }
|
||||
opencode-math = { workspace = true }
|
||||
opencode-science = { workspace = true }
|
||||
opencode-swe = { workspace = true }
|
||||
reverse-text = { workspace = true }
|
||||
rlm-swe = { workspace = true }
|
||||
science-env = { workspace = true }
|
||||
simpleqa-verified = { workspace = true }
|
||||
tau2-bench = { workspace = true }
|
||||
wiki-search = { workspace = true }
|
||||
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
verifiers = { path = "deps/verifiers", editable = true }
|
||||
renderers = { path = "deps/renderers", editable = true }
|
||||
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
|
||||
aime2024 = { path = "deps/research-environments/environments/aime2024", editable = true }
|
||||
aime2025 = { path = "deps/research-environments/environments/aime2025", editable = true }
|
||||
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
|
||||
code-env = { path = "deps/research-environments/environments/code_env", editable = true }
|
||||
color-codeword = { path = "deps/research-environments/environments/color_codeword", editable = true }
|
||||
deepdive = { path = "deps/research-environments/environments/deepdive", editable = true }
|
||||
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
|
||||
gpqa = { path = "deps/research-environments/environments/gpqa", editable = true }
|
||||
harnesses = { path = "deps/verifiers/packages/harnesses", editable = true }
|
||||
hle = { path = "deps/research-environments/environments/hle", editable = true }
|
||||
ifeval = { path = "deps/research-environments/environments/ifeval", editable = true }
|
||||
livecodebench = { path = "deps/research-environments/environments/livecodebench", editable = true }
|
||||
logic-env = { path = "deps/research-environments/environments/logic_env", editable = true }
|
||||
math-env = { path = "deps/research-environments/environments/math_env", editable = true }
|
||||
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
|
||||
math500 = { path = "deps/research-environments/environments/math500", editable = true }
|
||||
mini-swe-agent-plus = { path = "deps/research-environments/environments/mini_swe_agent_plus", editable = true }
|
||||
mmlu-pro = { path = "deps/research-environments/environments/mmlu_pro", editable = true }
|
||||
opencode-cp = { path = "deps/research-environments/environments/opencode_cp", editable = true }
|
||||
opencode-deepdive = { path = "deps/research-environments/environments/opencode_deepdive", editable = true }
|
||||
opencode-math = { path = "deps/research-environments/environments/opencode_math", editable = true }
|
||||
opencode-science = { path = "deps/research-environments/environments/opencode_science", editable = true }
|
||||
opencode-swe = { path = "deps/research-environments/environments/opencode_swe", editable = true }
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
|
||||
science-env = { path = "deps/research-environments/environments/science_env", editable = true }
|
||||
simpleqa-verified = { path = "deps/research-environments/environments/simpleqa_verified", editable = true }
|
||||
tau2-bench = { path = "deps/research-environments/environments/tau2_bench", editable = true }
|
||||
tasksets = { path = "deps/verifiers/packages/tasksets", editable = true }
|
||||
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
|
||||
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
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 = "c1c3424" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
prime-pydantic-config = { workspace = true }
|
||||
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
vllm = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/vllm-0.21.0+cu129.r42434.pr39568.a106aa6-cp38-abi3-manylinux_2_34_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.22.0/vllm-0.22.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.22.0/vllm-0.22.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
|
||||
@@ -303,7 +272,7 @@ select = ["F", "I"]
|
||||
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
# `prime_rl` is split across two workspace wheels (prime-rl + prime-rl-configs).
|
||||
# `prime_rl` is split across two editable wheels (prime-rl + prime-rl-configs).
|
||||
# Without this, ruff classifies prime_rl.configs.* as third-party because it
|
||||
# doesn't live under src/.
|
||||
known-first-party = ["prime_rl"]
|
||||
|
||||
@@ -1,17 +1,44 @@
|
||||
#!/bin/bash
|
||||
# arm64 post-install fixups for Docker builds.
|
||||
set -e
|
||||
# arm64 post-install fixups: rebuild flash-attn from source for the target GPU.
|
||||
#
|
||||
# Why this exists: pyproject.toml sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE to keep
|
||||
# `uv sync` fast; on x86_64 it pins a prebuilt wheel to fill in the binary, but no
|
||||
# such wheel exists for aarch64. Without this script, `import flash_attn` fails on
|
||||
# aarch64 with `ModuleNotFoundError: No module named 'flash_attn_2_cuda'`.
|
||||
#
|
||||
# Defaults preserve the existing Docker behavior (sm_100 / GB200). On a host with
|
||||
# `nvidia-smi` available, the compute capability is auto-detected from the local
|
||||
# GPU. Override via env vars if needed:
|
||||
# TORCH_CUDA_ARCH_LIST e.g. 9.0 (Hopper), 10.0 (Blackwell)
|
||||
# VENV_PATH path to the venv (default: $(pwd)/.venv)
|
||||
# MAX_JOBS parallel nvcc jobs (default: 4)
|
||||
set -euo pipefail
|
||||
|
||||
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
|
||||
if [ -z "${TORCH_CUDA_ARCH_LIST:-}" ]; then
|
||||
# Try to detect from the local GPU. Tolerate any failure mode (binary missing,
|
||||
# driver not loaded, Docker buildx without --gpus) and fall back to GB200.
|
||||
TORCH_CUDA_ARCH_LIST="$(nvidia-smi --query-gpu=compute_cap --format=csv,noheader 2>/dev/null | head -1 | tr -d ' ' || true)"
|
||||
: "${TORCH_CUDA_ARCH_LIST:=10.0}"
|
||||
fi
|
||||
export TORCH_CUDA_ARCH_LIST
|
||||
|
||||
VENV_PATH="${VENV_PATH:-$(pwd)/.venv}"
|
||||
if [ ! -x "$VENV_PATH/bin/python" ]; then
|
||||
echo "ERROR: no python at $VENV_PATH/bin/python. Run from the project root or set VENV_PATH." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export MAX_JOBS="${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 "=== building flash-attn from source (TORCH_CUDA_ARCH_LIST=$TORCH_CUDA_ARCH_LIST, MAX_JOBS=$MAX_JOBS) ==="
|
||||
echo " target venv: $VENV_PATH"
|
||||
# Run from /tmp so uv ignores the project's [tool.uv.extra-build-variables],
|
||||
# which sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and would prevent kernel compilation.
|
||||
(cd /tmp && uv pip install --python "$VENV_PATH/bin/python" \
|
||||
"flash-attn==2.8.3" --no-build-isolation --no-binary flash-attn --no-cache --reinstall-package flash-attn)
|
||||
|
||||
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
|
||||
uv pip install --reinstall --no-deps \
|
||||
uv pip install --python "$VENV_PATH/bin/python" --reinstall --no-deps \
|
||||
"flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
|
||||
|
||||
+11
-17
@@ -74,27 +74,11 @@ ensure_known_hosts() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Initialize each submodule independently so that a missing private repo
|
||||
# (e.g. configs/private when the user lacks access) does not abort the install.
|
||||
init_submodules() {
|
||||
if [ ! -f .gitmodules ]; then
|
||||
return 0
|
||||
fi
|
||||
local paths failures
|
||||
paths=$(git config -f .gitmodules --get-regexp '^submodule\..*\.path$' | awk '{print $2}')
|
||||
failures=()
|
||||
for path in $paths; do
|
||||
log_info "Initializing submodule: ${path}"
|
||||
if git submodule update --init --recursive -- "$path"; then
|
||||
:
|
||||
else
|
||||
log_warn "Could not initialize submodule '${path}' (likely no access). Continuing without it."
|
||||
failures+=("$path")
|
||||
fi
|
||||
done
|
||||
if [ "${#failures[@]}" -gt 0 ]; then
|
||||
log_warn "Skipped submodules: ${failures[*]}"
|
||||
fi
|
||||
git submodule update --init --recursive
|
||||
}
|
||||
|
||||
main() {
|
||||
@@ -159,6 +143,16 @@ main() {
|
||||
log_info "Installing pre-commit hooks..."
|
||||
uv run pre-commit install
|
||||
|
||||
# aarch64 has no prebuilt flash-attn wheel; build it from source for the local GPU.
|
||||
# Without this, `import flash_attn` fails with `ModuleNotFoundError: flash_attn_2_cuda`.
|
||||
# Run last so no subsequent uv operation (which implicitly syncs against the lockfile)
|
||||
# rebuilds flash-attn from PyPI with FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and undoes this.
|
||||
if [ "$(uname -m)" = "aarch64" ]; then
|
||||
log_info "aarch64 detected: building flash-attn from source (this takes 20-30 minutes)..."
|
||||
log_warn "Future 'uv sync --all-extras' or 'uv run' will remove this build. Use 'uv sync --inexact' or 'uv run --no-sync' to keep it."
|
||||
bash scripts/docker-arm64-post-install.sh
|
||||
fi
|
||||
|
||||
log_info "Installation completed!"
|
||||
}
|
||||
|
||||
|
||||
@@ -74,5 +74,4 @@ Leave it unset for normal training. When enabled, it exports every sequence from
|
||||
|
||||
- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli`
|
||||
- `configs/debug/` — minimal debug configs
|
||||
- `configs/private/` — private configs submodule (internal)
|
||||
- `examples/` — full example configs
|
||||
|
||||
@@ -16,11 +16,9 @@ bash scripts/install.sh # clones, inits submodules, installs uv, runs `uv sync
|
||||
For an existing clone, init submodules explicitly:
|
||||
|
||||
```bash
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
Do **not** run `git submodule update --init --recursive` without paths — it tries to clone the private `configs/private` submodule and aborts for users without access. `scripts/install.sh` walks submodules one at a time and skips failures, so it works for everyone.
|
||||
|
||||
## Sync
|
||||
|
||||
```bash
|
||||
|
||||
@@ -34,6 +34,12 @@ uv run rl @ examples/reverse_text/rl.toml --dry-run
|
||||
- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/rl.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
|
||||
- SLURM: single- and multi-node
|
||||
- Environment packages: before launching a config with a non-core verifier env id,
|
||||
verify the package imports under `uv run` (for example
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('rlm_swe'))"`).
|
||||
If a local env exists under `deps/research-environments/environments/` but does not
|
||||
import, add it to the root `pyproject.toml` env extra, workspace members, and
|
||||
`[tool.uv.sources]`, then run `uv sync --all-extras`.
|
||||
|
||||
## `sft` — SFT training
|
||||
|
||||
|
||||
@@ -36,6 +36,9 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
is_disaggregated = config.deployment.type == "disaggregated"
|
||||
dp_per_node = config.deployment.gpus_per_node // config.parallel.tp
|
||||
|
||||
offload = config.kv_cache_offload
|
||||
is_mooncake = offload is not None and offload.type == "mooncake"
|
||||
|
||||
template_vars = dict(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
@@ -45,7 +48,11 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
num_nodes=getattr(config.deployment, "num_nodes", 1),
|
||||
port=config.server.port,
|
||||
disaggregated=is_disaggregated,
|
||||
kv_offload=config.kv_cache_offload is not None,
|
||||
kv_offload=offload is not None,
|
||||
kv_offload_mooncake=is_mooncake,
|
||||
kv_offload_cpu_bytes=int(offload.cpu.num_bytes) if is_mooncake else 0,
|
||||
kv_offload_disk_path=str(offload.disk.path) if (is_mooncake and offload.disk is not None) else "",
|
||||
kv_offload_device_name=offload.device_name if is_mooncake else "",
|
||||
)
|
||||
|
||||
is_multi_node = config.deployment.type == "multi_node"
|
||||
@@ -58,19 +65,20 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
num_decode_replicas=config.deployment.num_decode_replicas,
|
||||
prefill_port=config.deployment.prefill_port,
|
||||
decode_port=config.deployment.decode_port,
|
||||
router_port=config.deployment.router_port,
|
||||
router_policy=config.deployment.router_policy,
|
||||
router_port=config.deployment.router.port,
|
||||
router_policy=config.deployment.router.policy,
|
||||
data_parallel_rpc_port=config.data_parallel_rpc_port,
|
||||
use_deep_gemm=config.use_deep_gemm,
|
||||
prefill_env_overrides=config.deployment.prefill_env_overrides,
|
||||
decode_env_overrides=config.deployment.decode_env_overrides,
|
||||
kv_offload_cpu_bytes=int(config.kv_cache_offload.cpu_bytes) if config.kv_cache_offload else 0,
|
||||
)
|
||||
elif is_multi_node:
|
||||
template_vars.update(
|
||||
router_port=config.deployment.router_port,
|
||||
router_port=config.deployment.router.port,
|
||||
backend_port=config.deployment.backend_port,
|
||||
router_policy=config.deployment.router_policy,
|
||||
router_policy=config.deployment.router.policy,
|
||||
data_parallel_rpc_port=config.data_parallel_rpc_port,
|
||||
enable_expert_parallel=config.enable_expert_parallel,
|
||||
)
|
||||
|
||||
script = template.render(**template_vars)
|
||||
@@ -83,7 +91,7 @@ def inference_slurm(config: InferenceConfig):
|
||||
"""Run inference via SLURM."""
|
||||
assert config.slurm is not None
|
||||
|
||||
logger = setup_logger("info")
|
||||
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = get_config_dir(config.output_dir)
|
||||
exclude = (
|
||||
@@ -119,7 +127,7 @@ def inference_local(config: InferenceConfig):
|
||||
"""Run inference locally."""
|
||||
from prime_rl.inference.server import setup_vllm_env
|
||||
|
||||
logger = setup_logger("info")
|
||||
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
|
||||
if config.dry_run:
|
||||
logger.success("Dry run complete. To start inference locally, remove --dry-run from your command.")
|
||||
|
||||
@@ -336,6 +336,16 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
|
||||
template = env.get_template(config.slurm.template_path.name)
|
||||
|
||||
offload = config.inference.kv_cache_offload if config.inference is not None else None
|
||||
is_mooncake = offload is not None and offload.type == "mooncake"
|
||||
mooncake_vars = dict(
|
||||
kv_offload=offload is not None,
|
||||
kv_offload_mooncake=is_mooncake,
|
||||
kv_offload_cpu_bytes=int(offload.cpu.num_bytes) if is_mooncake else 0,
|
||||
kv_offload_disk_path=str(offload.disk.path) if (is_mooncake and offload.disk is not None) else "",
|
||||
kv_offload_device_name=offload.device_name if is_mooncake else "",
|
||||
)
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
@@ -361,7 +371,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
num_prefill_replicas=infer_deploy.num_prefill_replicas,
|
||||
num_decode_replicas=infer_deploy.num_decode_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router_port=infer_deploy.router_port,
|
||||
router_port=infer_deploy.router.port,
|
||||
prefill_port=infer_deploy.prefill_port,
|
||||
decode_port=infer_deploy.decode_port,
|
||||
inference_tp=config.inference.parallel.tp,
|
||||
@@ -370,10 +380,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
prefill_env_overrides=infer_deploy.prefill_env_overrides,
|
||||
decode_env_overrides=infer_deploy.decode_env_overrides,
|
||||
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
|
||||
kv_offload=config.inference.kv_cache_offload is not None,
|
||||
kv_offload_cpu_bytes=int(config.inference.kv_cache_offload.cpu_bytes)
|
||||
if config.inference.kv_cache_offload
|
||||
else 0,
|
||||
**mooncake_vars,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
)
|
||||
@@ -389,13 +396,13 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
nodes_per_infer_replica=config.deployment.num_infer_nodes,
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
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,
|
||||
router_port=config.inference.deployment.router.port if config.inference else 8000,
|
||||
backend_port=config.inference.deployment.backend_port 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,
|
||||
dp_per_node=(config.deployment.gpus_per_node // config.inference.parallel.tp) if config.inference else 1,
|
||||
kv_offload=config.inference is not None and config.inference.kv_cache_offload is not None,
|
||||
**mooncake_vars,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Stdlib `logging`-based JSON formatter and dictConfig for vLLM.
|
||||
|
||||
Trainer and orchestrator emit JSON via loguru
|
||||
(`prime_rl.utils.logger.json_sink`). vLLM uses Python's stdlib
|
||||
`logging` and spawns workers via `multiprocessing.spawn`, so we can't
|
||||
share the loguru sink directly. We emit the same flat shape from a
|
||||
stdlib `Formatter` and drive it via a dictConfig file pointed to by
|
||||
`VLLM_LOGGING_CONFIG_PATH` — env vars cross the spawn boundary, so
|
||||
worker processes inherit the same logging config.
|
||||
"""
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import logging
|
||||
import tempfile
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
"""Emit one JSON object per record matching `build_log_entry` in
|
||||
`prime_rl.utils.logger` so the platform's JsonLogsViewer renders
|
||||
inference rows identically to trainer / orchestrator rows."""
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
entry: dict[str, Any] = {
|
||||
"timestamp": datetime.datetime.fromtimestamp(record.created, tz=datetime.timezone.utc).isoformat(),
|
||||
"level": record.levelname,
|
||||
"message": record.getMessage(),
|
||||
"module": record.module,
|
||||
"function": record.funcName,
|
||||
"line": record.lineno,
|
||||
}
|
||||
if record.exc_info:
|
||||
entry["exception"] = "".join(traceback.format_exception(*record.exc_info))
|
||||
return json.dumps(entry, default=str)
|
||||
|
||||
|
||||
# Loguru-only level names that stdlib `logging` doesn't recognize.
|
||||
# Mapped to the nearest stdlib level so `dictConfig` accepts them.
|
||||
_LOGURU_TO_STDLIB = {"TRACE": "DEBUG", "SUCCESS": "INFO"}
|
||||
|
||||
|
||||
def build_dict_config(level: str = "info") -> dict[str, Any]:
|
||||
"""`logging.config.dictConfig` payload that routes vLLM, uvicorn,
|
||||
fastapi, and the root logger through `JsonFormatter` to stdout.
|
||||
|
||||
Used inline for the parent process and serialized to disk for vLLM
|
||||
workers (via `VLLM_LOGGING_CONFIG_PATH`).
|
||||
"""
|
||||
upper = _LOGURU_TO_STDLIB.get(level.upper(), level.upper())
|
||||
handler = {
|
||||
"class": "logging.StreamHandler",
|
||||
"formatter": "prime_rl_json",
|
||||
"level": upper,
|
||||
"stream": "ext://sys.stdout",
|
||||
}
|
||||
# Each named logger is configured explicitly: vLLM, uvicorn, and
|
||||
# transformers all set propagate=False on their own loggers, so a
|
||||
# root-only setup wouldn't reach them.
|
||||
named = ("vllm", "uvicorn", "uvicorn.error", "uvicorn.access", "fastapi", "transformers")
|
||||
return {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"formatters": {
|
||||
"prime_rl_json": {
|
||||
"()": "prime_rl.inference.json_logging.JsonFormatter",
|
||||
},
|
||||
},
|
||||
"handlers": {"stdout_json": handler},
|
||||
"loggers": {
|
||||
"": {"handlers": ["stdout_json"], "level": upper},
|
||||
**{name: {"handlers": ["stdout_json"], "level": upper, "propagate": False} for name in named},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def write_logging_config(level: str = "info") -> Path:
|
||||
"""Persist a dictConfig JSON to a temp path. Caller sets the path on
|
||||
`VLLM_LOGGING_CONFIG_PATH` so vLLM (and its spawned workers) load
|
||||
the same config at import time."""
|
||||
config = build_dict_config(level)
|
||||
fd, path_str = tempfile.mkstemp(prefix="prime_rl_logging_", suffix=".json")
|
||||
path = Path(path_str)
|
||||
with open(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(config, f)
|
||||
return path
|
||||
@@ -18,8 +18,6 @@ def transformers_v5_compat():
|
||||
_patch_qwen35_lora()
|
||||
_patch_lora_key_prefix()
|
||||
monkey_patch_deep_gemm_silu_mul_quant_int64()
|
||||
monkey_patch_dp_engine_core_pause_resume_deadlock()
|
||||
monkey_patch_vllm_layerwise_reload_alias_buffers()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
|
||||
@@ -68,38 +66,6 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
|
||||
|
||||
|
||||
def monkey_patch_vllm_layerwise_reload_alias_buffers():
|
||||
# vLLM's layerwise reload materializes each buffer as an independent tensor
|
||||
# and then copies it back into the original kernel storage. When a buffer
|
||||
# aliases a parameter (e.g. NemotronH Mamba's mixer.conv_weights, a view of
|
||||
# mixer.conv1d.weight), the buffer copy stamps garbage into the parameter's
|
||||
# storage *after* the parameter has been correctly reloaded. Skip the copy
|
||||
# for any buffer that shares storage with a parameter; _place_kernel_tensors
|
||||
# re-registers the original view, which trivially reflects the parameter.
|
||||
# Remove this patch once https://github.com/vllm-project/vllm/pull/42481 is
|
||||
# included in the vLLM release we pin/use.
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.reload import layerwise as reload_layerwise
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
def _copy_and_restore_kernel_tensors(layer: torch.nn.Module, info: reload_layerwise.LayerReloadingInfo):
|
||||
assert info.kernel_tensors is not None
|
||||
parameters, buffers = info.kernel_tensors
|
||||
param_storage_ptrs = {p.untyped_storage().data_ptr() for p in layer.parameters(recurse=True)}
|
||||
for name, param in parameters.items():
|
||||
param.data.copy_(getattr(layer, name))
|
||||
for name, buffer in buffers.items():
|
||||
if buffer.untyped_storage().data_ptr() in param_storage_ptrs:
|
||||
continue
|
||||
buffer.data.copy_(getattr(layer, name))
|
||||
|
||||
reload_layerwise._place_kernel_tensors(layer, info)
|
||||
|
||||
reload_layerwise._copy_and_restore_kernel_tensors = _copy_and_restore_kernel_tensors
|
||||
logger.warning("Enabled vLLM layerwise reload alias-buffer patch.")
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel(
|
||||
y_ptr,
|
||||
@@ -782,87 +748,6 @@ def monkey_patch_harmony_stop_token_propagation():
|
||||
ChatCompletionRequest.to_sampling_params = _patched_to_sampling_params
|
||||
|
||||
|
||||
def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
"""Fix DP pause/resume deadlocks around weight updates.
|
||||
|
||||
Bug 1 (job 3756): while paused, START_DP_WAVE can wake idle ranks into the
|
||||
DP loop. Those ranks then run dummy batches and hit DP collectives while
|
||||
other ranks are still in NCCL weight transfer.
|
||||
|
||||
Bug 2 (jobs 3769/3771): resume ties the DP running state to local
|
||||
unfinished requests, but the DP wave state is global. Ranks with no local
|
||||
work still need to re-enter the loop so they can participate in the same
|
||||
DP collectives as ranks that are resuming remote-KV or decode work.
|
||||
|
||||
Fix:
|
||||
- ignore START_DP_WAVE wakeups while paused
|
||||
- on resume, wake every DP rank and force an immediate global unfinished
|
||||
sync instead of waiting for the normal 32-step cadence
|
||||
|
||||
This also bypasses vLLM's two-phase DP pause implementation
|
||||
(https://github.com/vllm-project/vllm/pull/39366), which makes resume
|
||||
reject states that our weight-update flow can validly hit.
|
||||
"""
|
||||
from vllm.config import ParallelConfig
|
||||
from vllm.v1.core.sched.interface import PauseState
|
||||
from vllm.v1.engine import EngineCoreOutputs, EngineCoreRequestType
|
||||
from vllm.v1.engine.core import DPEngineCoreProc, EngineCore, EngineCoreProc
|
||||
from vllm.v1.request import Request
|
||||
|
||||
_base_add_request = EngineCore.add_request
|
||||
_base_handle_client_request = EngineCoreProc._handle_client_request
|
||||
_base_pause_complete = EngineCoreProc._pause_complete
|
||||
_base_resume_scheduler = EngineCoreProc.resume_scheduler
|
||||
|
||||
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)))
|
||||
|
||||
def _patched_handle_client_request(self, request_type, request):
|
||||
if request_type == EngineCoreRequestType.START_DP_WAVE:
|
||||
new_wave, exclude_eng_index = request
|
||||
if exclude_eng_index != self.engine_index and new_wave >= self.current_wave:
|
||||
self.current_wave = new_wave
|
||||
if not self.engines_running and self.scheduler.pause_state == PauseState.UNPAUSED:
|
||||
self.engines_running = True
|
||||
else:
|
||||
_base_handle_client_request(self, request_type, request)
|
||||
|
||||
def _patched_pause_complete(self) -> bool:
|
||||
self.pending_pause = False
|
||||
self.ignore_start_dp_wave = False
|
||||
return _base_pause_complete(self)
|
||||
|
||||
def _patched_resume_scheduler(self):
|
||||
was_paused = self.scheduler.pause_state != PauseState.UNPAUSED
|
||||
self.pending_pause = False
|
||||
self.ignore_start_dp_wave = False
|
||||
_base_resume_scheduler(self)
|
||||
if was_paused:
|
||||
self.engines_running = True
|
||||
self._force_dp_running_state_sync = True
|
||||
|
||||
def _patched_has_global_unfinished_reqs(self, local_unfinished: bool) -> bool:
|
||||
self.step_counter += 1
|
||||
if getattr(self, "_force_dp_running_state_sync", False):
|
||||
self._force_dp_running_state_sync = False
|
||||
return ParallelConfig.has_unfinished_dp(self.dp_group, local_unfinished)
|
||||
if self.step_counter % 32 != 0:
|
||||
return True
|
||||
return ParallelConfig.has_unfinished_dp(self.dp_group, local_unfinished)
|
||||
|
||||
DPEngineCoreProc.add_request = _patched_add_request
|
||||
DPEngineCoreProc._handle_client_request = _patched_handle_client_request
|
||||
DPEngineCoreProc._pause_complete = _patched_pause_complete
|
||||
DPEngineCoreProc.resume_scheduler = _patched_resume_scheduler
|
||||
DPEngineCoreProc._has_global_unfinished_reqs = _patched_has_global_unfinished_reqs
|
||||
|
||||
|
||||
def monkey_patch_no_moe_lora():
|
||||
"""This disables LoRA for MoE layers and makes them pick better kernels.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import logging.config
|
||||
import os
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
@@ -17,6 +18,21 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
if config.enable_lora:
|
||||
os.environ["VLLM_ALLOW_RUNTIME_LORA_UPDATING"] = "True"
|
||||
|
||||
if config.log.json_logging:
|
||||
# Route vLLM's stdlib loggers through a JSON formatter matching
|
||||
# trainer / orchestrator. The env var (not in-process dictConfig)
|
||||
# is what reaches vLLM's spawned workers.
|
||||
from prime_rl.inference.json_logging import build_dict_config, write_logging_config
|
||||
|
||||
config_path = write_logging_config(config.log.level)
|
||||
# vLLM raises if VLLM_LOGGING_CONFIG_PATH is set while
|
||||
# VLLM_CONFIGURE_LOGGING=0 (its supported way to disable logger
|
||||
# setup). Force it on — opting into JSON logging is an explicit
|
||||
# request to configure vLLM's logger.
|
||||
os.environ["VLLM_CONFIGURE_LOGGING"] = "1"
|
||||
os.environ["VLLM_LOGGING_CONFIG_PATH"] = str(config_path)
|
||||
logging.config.dictConfig(build_dict_config(config.log.level))
|
||||
|
||||
|
||||
def main():
|
||||
config = cli(InferenceConfig)
|
||||
|
||||
@@ -24,6 +24,37 @@ else:
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_nccl")
|
||||
|
||||
# NemotronH mixer.D is dropped by vLLM 0.22's layerwise online-reload path (left uninitialized).
|
||||
_RELOAD_CORRUPTED_SUFFIXES = (".mixer.D",)
|
||||
|
||||
|
||||
def _restore_reload_corrupted_params(model: Module, received: dict[str, torch.Tensor]) -> None:
|
||||
"""Work around a vLLM 0.22 layerwise-reload bug for NemotronH.
|
||||
|
||||
The online reload drops the weight load for every Mamba layer's ``mixer.D`` (the SSD skip
|
||||
connection), leaving it as uninitialized ``empty_strided`` memory -- it reads back as garbage
|
||||
(NaN/inf) and the logits go NaN after a weight update. The received broadcast value is correct,
|
||||
so restore D from it via the param's own ``weight_loader``. Remove once the upstream bug is fixed.
|
||||
"""
|
||||
|
||||
def _layer_key(name: str) -> str:
|
||||
index = name.find("layers.")
|
||||
return name[index:] if index >= 0 else name
|
||||
|
||||
received_by_key = {_layer_key(name): tensor for name, tensor in received.items()}
|
||||
for name, param in model.named_parameters():
|
||||
if not name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
|
||||
continue
|
||||
tensor = received_by_key.get(_layer_key(name))
|
||||
if tensor is None:
|
||||
continue
|
||||
tensor = tensor.to(device=param.device)
|
||||
weight_loader = getattr(param, "weight_loader", None)
|
||||
if weight_loader is not None:
|
||||
weight_loader(param, tensor)
|
||||
elif tensor.shape == param.shape:
|
||||
param.data.copy_(tensor.to(param.dtype))
|
||||
|
||||
|
||||
def receive_integer(communicator: PyNcclCommunicator) -> int:
|
||||
"""Receive an integer from the trainer master rank using NCCL communicator."""
|
||||
@@ -148,9 +179,20 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
update_mla_absorbed_weights(model)
|
||||
return
|
||||
|
||||
# vLLM 0.22's layerwise reload drops NemotronH mixer.D's weight load (see
|
||||
# _restore_reload_corrupted_params). Capture the correct received value to restore after.
|
||||
received_reload_fix: dict[str, torch.Tensor] = {}
|
||||
|
||||
def _capture_reload_fix(weights):
|
||||
for name, tensor in weights:
|
||||
if name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
|
||||
received_reload_fix[name] = tensor.detach().to("cpu", copy=True)
|
||||
yield name, tensor
|
||||
|
||||
load_weights_checkpoint_layerwise(
|
||||
model,
|
||||
state_iter,
|
||||
_capture_reload_fix(state_iter),
|
||||
self.model_runner.model_config,
|
||||
self.vllm_config,
|
||||
)
|
||||
_restore_reload_corrupted_params(model, received_reload_fix)
|
||||
|
||||
@@ -12,7 +12,9 @@
|
||||
source's emptiness), so in-flight rollouts of the opposite kind drain
|
||||
naturally on either side of an eval boundary.
|
||||
- ``on_new_version`` (called by the watcher) bumps ``off_policy_steps`` on
|
||||
every in-flight rollout and drops groups past ``max_off_policy_steps``.
|
||||
in-flight train rollouts and drops groups past ``max_off_policy_steps``.
|
||||
Eval rollouts are measurements for the policy version they started with,
|
||||
so they are allowed to finish even if training advances.
|
||||
Cancellations surface as synthetic ``Cancelled`` markers so the sink's
|
||||
count-to-``group_size`` finalization still fires.
|
||||
"""
|
||||
@@ -131,6 +133,7 @@ class RolloutDispatcher:
|
||||
tasks_per_minute: float | None,
|
||||
max_off_policy_steps: int,
|
||||
training_mode: Literal["rl", "opd", "sft"],
|
||||
use_cache_salt: bool = True,
|
||||
) -> None:
|
||||
self.policy = policy
|
||||
self.train_envs = train_envs
|
||||
@@ -142,6 +145,7 @@ class RolloutDispatcher:
|
||||
self.train_source = train_source
|
||||
self.eval_source = eval_source
|
||||
self.training_mode = training_mode
|
||||
self.use_cache_salt = use_cache_salt
|
||||
self.max_off_policy_steps = max_off_policy_steps
|
||||
|
||||
self.max_inflight = max_inflight_rollouts
|
||||
@@ -262,32 +266,33 @@ class RolloutDispatcher:
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""Bump off-policy counters and drop groups past
|
||||
``max_off_policy_steps`` (drop_group emits ``Cancelled`` markers so
|
||||
the sink still finalizes the partial group)."""
|
||||
stale_groups: dict[uuid.UUID, RolloutKind] = {}
|
||||
cancelled_by_kind: dict[RolloutKind, int] = {"train": 0, "eval": 0}
|
||||
the sink still finalizes the partial group). Eval rollouts are not
|
||||
aged because they are tied to their start-time policy version."""
|
||||
stale_groups: set[uuid.UUID] = set()
|
||||
cancelled = 0
|
||||
for meta in self.inflight.values():
|
||||
if meta.kind != "train":
|
||||
continue
|
||||
meta.off_policy_steps += 1
|
||||
if meta.off_policy_steps > self.max_off_policy_steps:
|
||||
stale_groups[meta.group_id] = meta.kind
|
||||
stale_groups.add(meta.group_id)
|
||||
|
||||
for gid, kind in stale_groups.items():
|
||||
for gid in stale_groups:
|
||||
removed = await self.drop_group(gid)
|
||||
cancelled_by_kind[kind] += removed
|
||||
cancelled += removed
|
||||
|
||||
for kind in ("train", "eval"):
|
||||
n = cancelled_by_kind[kind]
|
||||
if n:
|
||||
get_logger().warning(
|
||||
f"Cancelled {n} {kind} rollouts past max_off_policy_steps={self.max_off_policy_steps}. "
|
||||
"Consider increasing it to avoid this."
|
||||
)
|
||||
if cancelled:
|
||||
get_logger().warning(
|
||||
f"Cancelled {cancelled} train rollouts past max_off_policy_steps={self.max_off_policy_steps}. "
|
||||
"Consider increasing it to avoid this."
|
||||
)
|
||||
|
||||
async def fill_inflight(self) -> None:
|
||||
"""Schedule new rollouts up to ``max_inflight``, honoring
|
||||
``self.mode``. When ``PREFER_EVAL``'s source exhausts we flip back
|
||||
to ``PREFER_TRAIN`` so the eval tail drains alongside fresh train."""
|
||||
if not self.dispatch_allowed.is_set():
|
||||
return
|
||||
``self.mode``. Eval scheduling ignores the orchestrator's dispatch
|
||||
gate (evals are version-pinned measurements); only train scheduling
|
||||
respects it. When ``PREFER_EVAL``'s source exhausts we flip back to
|
||||
``PREFER_TRAIN`` so the eval tail drains alongside fresh train."""
|
||||
while True:
|
||||
if self.available_permits <= 0:
|
||||
return
|
||||
@@ -308,7 +313,9 @@ class RolloutDispatcher:
|
||||
scheduled = await self.try_schedule("eval")
|
||||
if not scheduled:
|
||||
return
|
||||
else: # PREFER_TRAIN
|
||||
else: # PREFER_TRAIN — respects the orchestrator's dispatch gate
|
||||
if not self.dispatch_allowed.is_set():
|
||||
return
|
||||
scheduled = await self.try_schedule("train")
|
||||
if not scheduled:
|
||||
return
|
||||
@@ -408,7 +415,10 @@ class RolloutDispatcher:
|
||||
if env_collection is None:
|
||||
return False
|
||||
env = env_collection.get(group.env_name)
|
||||
cache_salt = str(group.policy_version_at_start)
|
||||
if group.kind == "eval" or self.use_cache_salt:
|
||||
cache_salt = str(group.policy_version_at_start)
|
||||
else:
|
||||
cache_salt = None
|
||||
|
||||
if env.requires_group_scoring:
|
||||
permits = group.rollouts_to_schedule
|
||||
|
||||
@@ -1,26 +1,21 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import atexit
|
||||
import multiprocessing as mp
|
||||
import time
|
||||
from collections.abc import Awaitable, Callable, Iterator, Sequence
|
||||
from collections.abc import Iterator, Sequence
|
||||
from multiprocessing.process import BaseProcess
|
||||
from pathlib import Path
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
import pandas as pd
|
||||
import verifiers as vf
|
||||
from verifiers.serve import ZMQEnvClient, ZMQEnvServer
|
||||
from verifiers.utils.serve_utils import get_free_port
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalEnvConfig, TrainEnvConfig
|
||||
from prime_rl.orchestrator.eval_utils import compute_pass_at_k
|
||||
from prime_rl.utils.logger import ProgressTracker, get_logger
|
||||
from prime_rl.utils.monitor import get_monitor
|
||||
from prime_rl.utils.utils import capitalize
|
||||
from prime_rl.orchestrator.advantage import AdvantageFn, setup_advantage_fn
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
REQUIRED_STATE_COLUMNS = ["trajectory", "sampling_args"]
|
||||
REQUIRED_STATE_COLUMNS = ["trajectory"]
|
||||
|
||||
|
||||
class Env:
|
||||
@@ -103,8 +98,10 @@ class Env:
|
||||
self._env_server_process = process
|
||||
return address
|
||||
|
||||
def _sampling_args_with_salt(self, cache_salt: str) -> dict:
|
||||
def _sampling_args_with_salt(self, cache_salt: str | None) -> dict:
|
||||
sampling_args = {**self.sampling_args}
|
||||
if cache_salt is None:
|
||||
return sampling_args
|
||||
extra_body = {**sampling_args.get("extra_body", {}), "cache_salt": cache_salt}
|
||||
sampling_args["extra_body"] = extra_body
|
||||
return sampling_args
|
||||
@@ -123,7 +120,7 @@ class Env:
|
||||
client: vf.ClientConfig,
|
||||
example: dict,
|
||||
model_name: str,
|
||||
cache_salt: str,
|
||||
cache_salt: str | None,
|
||||
) -> vf.RolloutOutput:
|
||||
"""Run a single rollout for an example."""
|
||||
return await self.env.run_rollout(
|
||||
@@ -142,7 +139,7 @@ class Env:
|
||||
example: dict,
|
||||
model_name: str,
|
||||
group_size: int,
|
||||
cache_salt: str,
|
||||
cache_salt: str | None,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
"""Run a group of rollouts for an example. Required for group-scoring envs."""
|
||||
return await self.env.run_group(
|
||||
@@ -168,6 +165,11 @@ class TrainEnv(Env):
|
||||
def __init__(self, config: TrainEnvConfig):
|
||||
super().__init__(config)
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
# Built once — custom advantage funcs do an ``import_object`` we don't
|
||||
# want to pay per group. ``None`` = reward-only path.
|
||||
self.advantage_fn: AdvantageFn | None = (
|
||||
setup_advantage_fn(config.advantage) if config.advantage is not None else None
|
||||
)
|
||||
|
||||
def get_dataset(self, seed: int | None = None):
|
||||
return self.env.get_dataset(seed=seed)
|
||||
@@ -181,147 +183,6 @@ class EvalEnv(Env):
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
self.examples = self.env.get_eval_dataset(n=config.num_examples).to_list()
|
||||
|
||||
async def evaluate(
|
||||
self,
|
||||
model_name: str,
|
||||
get_client: Callable[[], Awaitable[vf.ClientConfig]],
|
||||
step: int,
|
||||
cache_salt: str,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
num_examples = len(self.examples)
|
||||
group_size = self.config.group_size
|
||||
get_logger().info(f"Evaluating {self.name} ({num_examples=}, {group_size=})")
|
||||
total_rollouts = num_examples * group_size
|
||||
pbar = ProgressTracker(total=total_rollouts, desc=f"Evaluating {self.name}")
|
||||
eval_start = time.perf_counter()
|
||||
|
||||
if self.requires_group_scoring:
|
||||
|
||||
async def run_with_progress(example: dict) -> list[vf.RolloutOutput] | None:
|
||||
"""Run group_size rollouts as a scored group for one example."""
|
||||
try:
|
||||
client = await get_client()
|
||||
outputs = await self.run_group(
|
||||
client=client,
|
||||
example=example,
|
||||
model_name=model_name,
|
||||
group_size=group_size,
|
||||
cache_salt=cache_salt,
|
||||
)
|
||||
pbar.update(group_size)
|
||||
return outputs
|
||||
except Exception as e:
|
||||
get_logger().warning(f"Group failed: {e}")
|
||||
pbar.update(group_size)
|
||||
return None
|
||||
|
||||
coros = [run_with_progress(example) for example in self.examples]
|
||||
|
||||
else:
|
||||
|
||||
async def run_with_progress(example: dict) -> list[vf.RolloutOutput] | None:
|
||||
"""Run a single rollout for one example."""
|
||||
try:
|
||||
client = await get_client()
|
||||
output = await self.run_rollout(
|
||||
client=client, example=example, model_name=model_name, cache_salt=cache_salt
|
||||
)
|
||||
pbar.update(1)
|
||||
return [output]
|
||||
except Exception as e:
|
||||
get_logger().warning(f"Rollout failed: {e}")
|
||||
pbar.update(1)
|
||||
return None
|
||||
|
||||
coros = [run_with_progress(example) for example in self.examples for _ in range(group_size)]
|
||||
|
||||
try:
|
||||
results = await asyncio.gather(*coros)
|
||||
finally:
|
||||
pbar.close()
|
||||
|
||||
successful_outputs = [o for group in results if group is not None for o in group]
|
||||
failed_count = total_rollouts - len(successful_outputs)
|
||||
eval_time = time.perf_counter() - eval_start
|
||||
|
||||
if failed_count:
|
||||
get_logger().warning(
|
||||
f"{failed_count}/{total_rollouts} ({failed_count / total_rollouts * 100:.1f}%) rollouts failed"
|
||||
)
|
||||
|
||||
if not successful_outputs:
|
||||
get_logger().warning(f"All rollouts failed for {self.name}, skipping logging metrics")
|
||||
get_monitor().log(
|
||||
{
|
||||
f"eval/{self.name}/failed_rollouts": failed_count / total_rollouts,
|
||||
"step": step,
|
||||
},
|
||||
step=step,
|
||||
)
|
||||
return []
|
||||
|
||||
# Log metrics
|
||||
monitor = get_monitor()
|
||||
|
||||
rows = [
|
||||
{
|
||||
"example_id": o["example_id"],
|
||||
"reward": o["reward"],
|
||||
"completion_len": o["token_usage"]["final_output_tokens"],
|
||||
"is_truncated": o["is_truncated"],
|
||||
"has_error": o.get("error") is not None,
|
||||
"no_response": not o.get("completion"),
|
||||
}
|
||||
for o in successful_outputs
|
||||
]
|
||||
results_df = pd.DataFrame(rows)
|
||||
|
||||
unique_rewards = results_df.reward.dropna().unique()
|
||||
could_be_binary = set(unique_rewards).issubset({0.0, 1.0})
|
||||
if could_be_binary:
|
||||
pass_at_k = (
|
||||
results_df.groupby("example_id")
|
||||
.apply(lambda x: compute_pass_at_k(x.reward.dropna()), include_groups=False)
|
||||
.apply(pd.Series)
|
||||
)
|
||||
else:
|
||||
pass_at_k = None
|
||||
get_logger().warning("Skipping computing pass@k rates because the task rewards appear to be non-binary")
|
||||
|
||||
message = f"Evaluated {self.name} in {eval_time:.2f}s (Avg@{group_size}={results_df.reward.mean():.4f}"
|
||||
if could_be_binary:
|
||||
assert pass_at_k is not None
|
||||
for pass_rate, pass_rate_score in pd.Series(pass_at_k.mean()).items():
|
||||
message += f", {capitalize(str(pass_rate))}: {pass_rate_score:.4f}"
|
||||
|
||||
message += (
|
||||
f", No-response: {results_df.no_response.mean() * 100:.1f}%"
|
||||
f", Completion Length: {results_df.completion_len.mean():.2f} (±{results_df.completion_len.std():.2f}, ∈[{results_df.completion_len.min():.2f}, {results_df.completion_len.max():.2f}])"
|
||||
f", Truncated: {results_df.is_truncated.mean() * 100:.1f}%)"
|
||||
)
|
||||
get_logger().success(message)
|
||||
|
||||
eval_metrics = {
|
||||
f"avg@{group_size}": float(results_df.reward.mean()),
|
||||
"no_response/mean": float(results_df.no_response.mean()),
|
||||
"no_response/count": int(results_df.no_response.sum()),
|
||||
"completion_len/mean": results_df.completion_len.mean().item(),
|
||||
"completion_len/max": results_df.completion_len.max().item(),
|
||||
"completion_len/min": results_df.completion_len.min().item(),
|
||||
"is_truncated/mean": results_df.is_truncated.mean().item(),
|
||||
"failed_rollouts": failed_count / total_rollouts,
|
||||
"time": eval_time,
|
||||
}
|
||||
if could_be_binary:
|
||||
assert pass_at_k is not None
|
||||
eval_metrics.update(pd.Series(pass_at_k.mean()).to_dict())
|
||||
eval_metrics = {f"eval/{self.name}/{key}": v for key, v in eval_metrics.items()}
|
||||
eval_metrics["step"] = step
|
||||
monitor.log(eval_metrics, step=step)
|
||||
monitor.log_eval_samples(successful_outputs, env_name=self.name, step=step)
|
||||
|
||||
return successful_outputs
|
||||
|
||||
|
||||
EnvT = TypeVar("EnvT", bound=Env)
|
||||
|
||||
|
||||
@@ -345,13 +345,14 @@ class Orchestrator:
|
||||
else:
|
||||
get_logger().info("Training from scratch")
|
||||
|
||||
# SFT generates rollouts via the teacher (the student is trained on
|
||||
# the teacher's outputs); RL / OPD generate via the student
|
||||
if config.training_mode == "sft":
|
||||
assert self.teacher_inference is not None, "sft mode requires teacher inference"
|
||||
# SFT train rollouts come from the teacher when configured; otherwise
|
||||
# they use the existing student rollout pool.
|
||||
if config.training_mode == "sft" and self.teacher_inference is not None:
|
||||
rollout_inference = self.teacher_inference
|
||||
use_cache_salt = False
|
||||
else:
|
||||
rollout_inference = self.student_inference
|
||||
use_cache_salt = True
|
||||
|
||||
self.train_source = TrainSource(self.train_envs, seed=42)
|
||||
self.eval_source: EvalSource | None = (
|
||||
@@ -379,6 +380,7 @@ class Orchestrator:
|
||||
tasks_per_minute=config.tasks_per_minute,
|
||||
max_off_policy_steps=config.max_off_policy_steps,
|
||||
training_mode=config.training_mode,
|
||||
use_cache_salt=use_cache_salt,
|
||||
)
|
||||
self.metrics = MetricsBuilder(config)
|
||||
self.train_sink = TrainSink(
|
||||
@@ -389,7 +391,6 @@ class Orchestrator:
|
||||
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
|
||||
batch_size=config.batch_size,
|
||||
token_batch_size=config.token_batch_size,
|
||||
advantage_config=config.advantage,
|
||||
pre_filters=pre_filters,
|
||||
post_filters=post_filters,
|
||||
)
|
||||
@@ -499,7 +500,7 @@ class Orchestrator:
|
||||
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
|
||||
eval_batch = self.eval_sink.add(rollout)
|
||||
if eval_batch is not None:
|
||||
self.finalize_eval_batch(eval_batch)
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
continue
|
||||
|
||||
assert isinstance(rollout, TrainRollout)
|
||||
@@ -761,7 +762,7 @@ class Orchestrator:
|
||||
)
|
||||
get_logger().success("\n\t\t ".join(lines))
|
||||
|
||||
def finalize_eval_batch(self, batch: EvalBatch) -> None:
|
||||
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
|
||||
"""Persist + log one completed eval epoch (save_rollouts,
|
||||
monitor.log_eval_samples, monitor.log)."""
|
||||
if not batch.rollouts:
|
||||
@@ -770,24 +771,32 @@ class Orchestrator:
|
||||
|
||||
rollout_dicts = [r.to_dict() for r in batch.rollouts]
|
||||
step_path = get_step_path(get_rollout_dir(self.config.output_dir), batch.step)
|
||||
save_rollouts(
|
||||
await asyncio.to_thread(
|
||||
save_rollouts,
|
||||
rollout_dicts,
|
||||
step_path / f"eval_rollouts_{batch.env_name}.jsonl",
|
||||
exclude_keys={"trajectory"},
|
||||
)
|
||||
self.monitor.log_eval_samples(rollout_dicts, env_name=batch.env_name, step=batch.step)
|
||||
self.monitor.log(batch.metrics.to_wandb_dict(env_name=batch.env_name, step=batch.step), step=batch.step)
|
||||
policy_versions = {r.policy_version for r in batch.rollouts}
|
||||
policy_version = min(policy_versions)
|
||||
if len(policy_versions) > 1:
|
||||
get_logger().warning(
|
||||
f"Eval {batch.env_name} step {batch.step} had mixed policy versions: {sorted(policy_versions)}"
|
||||
)
|
||||
metrics = batch.metrics.to_wandb_dict(env_name=batch.env_name, step=batch.step)
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(policy_version)
|
||||
self.monitor.log(metrics, step=batch.step)
|
||||
|
||||
n_total = batch.metrics.n_rollouts
|
||||
error_rate = ((batch.metrics.n_cancelled + batch.metrics.n_errored) / n_total) if n_total else 0.0
|
||||
max_off_policy = max((r.off_policy_steps for r in batch.rollouts), default=0)
|
||||
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
|
||||
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
|
||||
|
||||
get_logger().success(
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"{format_time(elapsed):>7} | Reward {batch.metrics.reward_mean:.4f} | "
|
||||
f"Turns {batch.metrics.num_turns_mean:.1f} | Max Off-Policy {max_off_policy} | "
|
||||
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {batch.metrics.reward_mean:.4f} | "
|
||||
f"Turns {batch.metrics.num_turns_mean:.1f} | "
|
||||
f"Error {error_rate:.1%} | Truncation {batch.metrics.truncation_rate:.1%}"
|
||||
)
|
||||
|
||||
|
||||
@@ -17,8 +17,8 @@ import asyncio
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
|
||||
from prime_rl.configs.orchestrator import AdvantageConfig, OrchestratorConfig
|
||||
from prime_rl.orchestrator.advantage import assign_advantages, setup_advantage_fn
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.advantage import assign_advantages
|
||||
from prime_rl.orchestrator.envs import TrainEnvs
|
||||
from prime_rl.orchestrator.filters import RolloutFilter, apply_filters
|
||||
from prime_rl.orchestrator.trajectories import (
|
||||
@@ -44,7 +44,6 @@ class TrainSink:
|
||||
mm_token_type_ids_mapping: dict[int, int] | None,
|
||||
batch_size: int | None,
|
||||
token_batch_size: int | None,
|
||||
advantage_config: AdvantageConfig | None,
|
||||
pre_filters: list[RolloutFilter],
|
||||
post_filters: list[RolloutFilter],
|
||||
) -> None:
|
||||
@@ -58,9 +57,6 @@ class TrainSink:
|
||||
self.mm_token_type_ids_mapping = mm_token_type_ids_mapping
|
||||
self.batch_size = batch_size
|
||||
self.token_batch_size = token_batch_size
|
||||
# Built once — custom advantage funcs do an ``import_object`` and
|
||||
# we don't want to pay that per group. ``None`` = reward-only path
|
||||
self.advantage_fn = setup_advantage_fn(advantage_config) if advantage_config is not None else None
|
||||
self.pre_filters = pre_filters
|
||||
self.post_filters = post_filters
|
||||
|
||||
@@ -200,16 +196,20 @@ class TrainSink:
|
||||
)
|
||||
return
|
||||
|
||||
assign_advantages(survivors, self.advantage_fn)
|
||||
assign_advantages(survivors, self.train_envs.get(env_name).advantage_fn)
|
||||
|
||||
# Propagate to the pre-tokenized samples so the orchestrator can
|
||||
# collect samples at ship time without re-walking rollouts
|
||||
# collect samples at ship time without re-walking rollouts. The env
|
||||
# has a single sampling temperature; fan it out across each sample's
|
||||
# completion tokens here (interleave leaves it empty).
|
||||
temperature = env.sampling_args["temperature"]
|
||||
for r in survivors:
|
||||
for sample in r.samples:
|
||||
sample.advantage = r.advantage
|
||||
sample.reward = r.reward
|
||||
sample.env_name = r.env_name
|
||||
sample.training_mode = self.config.training_mode
|
||||
sample.completion_temperatures = [temperature] * len(sample.completion_ids)
|
||||
|
||||
if self.pre_filters:
|
||||
apply_filters(self.pre_filters, survivors)
|
||||
|
||||
@@ -238,8 +238,6 @@ def interleave_rollout(
|
||||
return None
|
||||
|
||||
has_error = output["error"] is not None
|
||||
# this field should be guaranteed because we set temperature in get_sampling_args
|
||||
temperature = output["sampling_args"]["temperature"]
|
||||
|
||||
def prepare_step_tokens(step: vf.TrajectoryStep, step_idx: int) -> dict[str, Any] | None:
|
||||
tokens = step["tokens"]
|
||||
@@ -304,7 +302,7 @@ def interleave_rollout(
|
||||
completion_ids=completion_ids,
|
||||
completion_mask=completion_mask,
|
||||
completion_logprobs=list(tokens["completion_logprobs"]),
|
||||
completion_temperatures=[temperature] * len(completion_ids),
|
||||
completion_temperatures=[],
|
||||
teacher_logprobs=None,
|
||||
advantage=None,
|
||||
env_name=env_name,
|
||||
@@ -377,7 +375,6 @@ def interleave_rollout(
|
||||
sample.completion_ids.extend(new_prompt_ids)
|
||||
sample.completion_mask.extend([False] * len(new_prompt_ids))
|
||||
sample.completion_logprobs.extend([0.0] * len(new_prompt_ids))
|
||||
sample.completion_temperatures.extend([temperature] * len(new_prompt_ids))
|
||||
|
||||
# Extend with new completion tokens
|
||||
completion_ids = tokens["completion_ids"]
|
||||
@@ -387,7 +384,6 @@ def interleave_rollout(
|
||||
else:
|
||||
sample.completion_mask.extend(tokens["completion_mask"])
|
||||
sample.completion_logprobs.extend(tokens["completion_logprobs"])
|
||||
sample.completion_temperatures.extend([temperature] * len(completion_ids))
|
||||
|
||||
step_routed = tokens.get("routed_experts")
|
||||
state = sample_routed_state.get(id(sample))
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
{# Shared external-LB vLLM launch helper, included once per template and called
|
||||
from every per-rank launch site (multi-node and disaggregated).
|
||||
One vLLM API server per DP rank, pinned to its GPU slice. #}
|
||||
# rank_log <node_rank> <k> — DP rank 0 logs to the node-level file (node_<rank>.log,
|
||||
# the target of the top-level inference.log symlink) so it captures real server output;
|
||||
# ranks 1+ get their own node_<rank>_rank<k>.log.
|
||||
rank_log() {
|
||||
if [ "$2" -eq 0 ]; then
|
||||
echo "$OUTPUT_DIR/logs/inference/node_$1.log"
|
||||
else
|
||||
echo "$OUTPUT_DIR/logs/inference/node_$1_rank$2.log"
|
||||
fi
|
||||
}
|
||||
|
||||
# launch_inference_rank <port> <cuda_visible_devices> <dp> <rpc_port> <vllm_extra_json|""> <nixl_side_channel_port|""> <log_file>
|
||||
launch_inference_rank() {
|
||||
local port="$1" gpus="$2" dp="$3" rpc="$4" extra="$5" nixl="$6" log="$7"
|
||||
local -a cmd=(uv run inference @ "$CONFIG_PATH"
|
||||
--server.host 0.0.0.0 --server.port "$port"
|
||||
--parallel.dp "$dp" --data-parallel-size-local 1 --api-server-count 1)
|
||||
[ -n "$rpc" ] && cmd+=(--data-parallel-rpc-port "$rpc")
|
||||
[ -n "$extra" ] && cmd+=(--vllm-extra "$extra")
|
||||
if [ -n "$nixl" ]; then
|
||||
CUDA_VISIBLE_DEVICES="$gpus" VLLM_NIXL_SIDE_CHANNEL_PORT="$nixl" "${cmd[@]}" 2>&1 | tee -a "$log" &
|
||||
else
|
||||
CUDA_VISIBLE_DEVICES="$gpus" "${cmd[@]}" 2>&1 | tee -a "$log" &
|
||||
fi
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{# Shared router launch helper, included once per template and called by the
|
||||
replica-head rank. vllm-router today; an llm-d (EPP+Envoy) branch can slot in
|
||||
here so the call sites stay router-agnostic. #}
|
||||
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log_file> [replica_idx]
|
||||
launch_router() {
|
||||
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-}"
|
||||
local tag="vllm-router"; [ "$mode" = pd ] && tag="vllm-router (PD)"
|
||||
echo "Starting $tag on $LOCAL_IP:$port${replica:+ for replica $replica}" | tee "$log"
|
||||
local -a cmd=(vllm-router --policy "$policy" --host 0.0.0.0 --port "$port"
|
||||
--worker-startup-timeout-secs 4200 --log-level debug)
|
||||
if [ "$mode" = pd ]; then
|
||||
cmd+=(--vllm-pd-disaggregation $worker_args)
|
||||
else
|
||||
cmd+=(--worker-urls $worker_args)
|
||||
fi
|
||||
"${cmd[@]}" >> "$log" 2>&1 &
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{#- Mooncake distributed store (shared pool across inference nodes) for KV cache offload.
|
||||
One master + HTTP metadata server runs on the head inference node (first in the SLURM
|
||||
nodelist); every inference node runs a client that contributes its DRAM/SSD segment to
|
||||
that single pool, so any node can reuse prefixes cached by any other. Included by the
|
||||
SLURM templates inside the per-node `bash -c` body, so NO single quotes / apostrophes.
|
||||
Requires shell vars: LOCAL_IP, INFER_NODE_RANK, OUTPUT_DIR (and SLURM env).
|
||||
Requires jinja vars: kv_offload_cpu_bytes, kv_offload_disk_path, kv_offload_device_name.
|
||||
Exports PYTHONHASHSEED + MOONCAKE_CONFIG_PATH for the vLLM process on this node. -#}
|
||||
# ---- Mooncake distributed store (shared pool across inference nodes) ----
|
||||
MC_DIR="$OUTPUT_DIR/mooncake/node_${INFER_NODE_RANK}"
|
||||
mkdir -p "$MC_DIR"
|
||||
export PYTHONHASHSEED=0
|
||||
export MOONCAKE_CONFIG_PATH="$MC_DIR/config.json"
|
||||
# The head inference node (first in the nodelist) hosts the one master + metadata server.
|
||||
MC_HEAD=$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -1)
|
||||
MC_MASTER="$MC_HEAD:50051"
|
||||
MC_METADATA="http://$MC_HEAD:8080/metadata"
|
||||
{%- if kv_offload_disk_path %}
|
||||
mkdir -p "{{ kv_offload_disk_path }}"
|
||||
export MOONCAKE_OFFLOAD_FSDIR="{{ kv_offload_disk_path }}"
|
||||
export MOONCAKE_OFFLOAD_FILE_STORAGE_PATH="{{ kv_offload_disk_path }}"
|
||||
export MOONCAKE_OFFLOAD_ENABLE_EVICTION=true
|
||||
{%- endif %}
|
||||
if [ "$SLURMD_NODENAME" = "$MC_HEAD" ]; then
|
||||
{%- if kv_offload_disk_path %}
|
||||
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -enable_offload=true -root_fs_dir={{ kv_offload_disk_path }} > "$MC_DIR/master.log" 2>&1 &
|
||||
{%- else %}
|
||||
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 > "$MC_DIR/master.log" 2>&1 &
|
||||
{%- endif %}
|
||||
fi
|
||||
# Every node waits for the shared master + metadata, then contributes its segment.
|
||||
for _ in $(seq 1 120); do timeout 1 bash -c "echo > /dev/tcp/$MC_HEAD/50051" 2>/dev/null && break; sleep 1; done
|
||||
for _ in $(seq 1 120); do timeout 1 bash -c "echo > /dev/tcp/$MC_HEAD/8080" 2>/dev/null && break; sleep 1; done
|
||||
mooncake_client -host=$LOCAL_IP -port=50052 -master_server_address=$MC_MASTER -metadata_server=$MC_METADATA -protocol=rdma -global_segment_size={{ kv_offload_cpu_bytes }}{% if kv_offload_device_name %} -device_names={{ kv_offload_device_name }}{% endif %}{% if kv_offload_disk_path %} -enable_offload=true{% endif %} > "$MC_DIR/client.log" 2>&1 &
|
||||
for _ in $(seq 1 60); do timeout 1 bash -c "echo > /dev/tcp/$LOCAL_IP/50052" 2>/dev/null && break; sleep 1; done
|
||||
cat > "$MOONCAKE_CONFIG_PATH" <<MOONCAKE_JSON
|
||||
{"mode":"standalone-store","global_segment_size":0,"local_buffer_size":4294967296,"protocol":"rdma","device_name":"{{ kv_offload_device_name }}","master_server_address":"$MC_MASTER","metadata_server":"$MC_METADATA","enable_offload":{% if kv_offload_disk_path %}true{% else %}false{% endif %}}
|
||||
MOONCAKE_JSON
|
||||
echo "[mooncake] node ${INFER_NODE_RANK} ($SLURMD_NODENAME) joined shared pool: master=$MC_MASTER segment=$LOCAL_IP:50052"
|
||||
@@ -43,6 +43,7 @@ export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
{%- elif num_nodes > 1 %}
|
||||
export ROUTER_PORT={{ router_port }}
|
||||
export BACKEND_PORT={{ backend_port }}
|
||||
export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
{%- endif %}
|
||||
|
||||
# Paths
|
||||
@@ -78,26 +79,32 @@ for ((r=0; r<NUM_NODES/NODES_PER_REPLICA; r++)); do
|
||||
INFER_URLS="${INFER_URLS:+$INFER_URLS,}http://${router_host}:${ROUTER_PORT}/v1"
|
||||
|
||||
REPLICA_ROUTER_ARGS=""
|
||||
# External-LB: one --prefill/--decode endpoint per DP rank (PORT + k) on each node.
|
||||
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
|
||||
node_idx=$((replica_base + p))
|
||||
host="${HOSTNAMES[$node_idx]}"
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:${PREFILL_PORT}"
|
||||
host="${HOSTNAMES[$((replica_base + p))]}"
|
||||
for ((k=0; k<{{ dp_per_node }}; k++)); do
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
|
||||
done
|
||||
done
|
||||
for ((d=0; d<NUM_DECODE_NODES; d++)); do
|
||||
node_idx=$((replica_base + NUM_PREFILL_NODES + d))
|
||||
host="${HOSTNAMES[$node_idx]}"
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:${DECODE_PORT}"
|
||||
host="${HOSTNAMES[$((replica_base + NUM_PREFILL_NODES + d))]}"
|
||||
for ((k=0; k<{{ dp_per_node }}; k++)); do
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
|
||||
done
|
||||
done
|
||||
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
|
||||
done
|
||||
export INFER_URLS
|
||||
export ALL_ROUTER_ARGS
|
||||
{%- elif num_nodes > 1 %}
|
||||
# Single router on node 0, all nodes as backends
|
||||
# External LB: one router on node 0; one endpoint per DP rank (BACKEND_PORT + dp_local) on every node.
|
||||
INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1"
|
||||
DP_PER_NODE={{ dp_per_node }}
|
||||
ROUTER_ARGS=""
|
||||
for host in ${HOSTNAMES[@]}; do
|
||||
ROUTER_ARGS="$ROUTER_ARGS http://${host}:${BACKEND_PORT}"
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + d))"
|
||||
done
|
||||
done
|
||||
export INFER_URLS
|
||||
export ROUTER_ARGS
|
||||
@@ -130,9 +137,13 @@ srun bash -s <<'CLEANUP_SH'
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
pkill -9 "vllm::.*" 2>/dev/null
|
||||
# Mooncake store (master + client) left over from a prior offload run. -x matches
|
||||
# the exact process name, so it never hits the worktree path (e.g. mooncake-baby).
|
||||
pkill -9 -x mooncake_master 2>/dev/null
|
||||
pkill -9 -x mooncake_client 2>/dev/null
|
||||
sleep 2
|
||||
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::" | grep -v grep | wc -l)
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
CLEANUP_SH
|
||||
@@ -158,9 +169,14 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
INFER_NODE_RANK=$SLURM_PROCID
|
||||
LOCAL_IP=$(hostname -I | awk "{print \$1}")
|
||||
|
||||
{% include '_launch_rank.sh.j2' %}
|
||||
{% include '_launch_router.sh.j2' %}
|
||||
{%- if kv_offload %}
|
||||
ulimit -l unlimited
|
||||
{%- endif %}
|
||||
{%- if kv_offload_mooncake %}
|
||||
{% include "_mooncake_store.sh.j2" %}
|
||||
{%- endif %}
|
||||
|
||||
{% if disaggregated -%}
|
||||
# NVSHMEM libs for DeepEP — ensure the rpath target exists on all nodes
|
||||
@@ -178,29 +194,41 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
export VLLM_MOE_USE_DEEP_GEMM=1
|
||||
{%- endif %}
|
||||
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:False"
|
||||
export GLOO_SOCKET_IFNAME=bond0
|
||||
# Bind gloo to the interface that owns LOCAL_IP (the rendezvous IP) — NIC
|
||||
# names vary across clusters (bond0, eth0, ...). If the lookup fails, leave
|
||||
# GLOO_SOCKET_IFNAME unset so gloo falls back to its own detection.
|
||||
GLOO_IFNAME=$(ip -o -4 addr show to "$LOCAL_IP" 2>/dev/null | awk "{print \$2; exit}")
|
||||
if [ -n "$GLOO_IFNAME" ]; then export GLOO_SOCKET_IFNAME=$GLOO_IFNAME; fi
|
||||
export VLLM_ENGINE_READY_TIMEOUT_S=4200
|
||||
export UCX_TLS=all
|
||||
export UCX_NET_DEVICES=all
|
||||
# Enumerate RDMA NICs for UCX/NIXL from sysfs (ibv_devices is not on the job
|
||||
# PATH). Prefer InfiniBand ports and fall back to RoCE: "all" would also pick
|
||||
# up non-functional devices (e.g. an Ethernet bond UCX cannot open), which
|
||||
# fails NIXL backend creation. Hosts without RDMA devices keep "all" (TCP).
|
||||
rdma_ports() {
|
||||
for port in /sys/class/infiniband/*/ports/*; do
|
||||
[ "$(cat "$port/link_layer" 2>/dev/null)" = "$1" ] || continue
|
||||
grep -q ACTIVE "$port/state" 2>/dev/null || continue
|
||||
dev=${port%/ports/*}
|
||||
echo "$(basename "$dev"):$(basename "$port")"
|
||||
done | paste -sd,
|
||||
}
|
||||
UCX_NET_DEVICES=$(rdma_ports InfiniBand)
|
||||
[ -n "$UCX_NET_DEVICES" ] || UCX_NET_DEVICES=$(rdma_ports Ethernet)
|
||||
export UCX_NET_DEVICES=${UCX_NET_DEVICES:-all}
|
||||
export LD_LIBRARY_PATH="$PROJECT_DIR/third_party/ucx/lib:$PROJECT_DIR/third_party/ucx/lib/ucx:${LD_LIBRARY_PATH:-}"
|
||||
|
||||
export VLLM_NIXL_SIDE_CHANNEL_HOST=$LOCAL_IP
|
||||
export VLLM_NIXL_SIDE_CHANNEL_PORT=5600
|
||||
|
||||
{%- if kv_offload %}
|
||||
PREFILL_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
|
||||
{%- else %}
|
||||
PREFILL_KV_CFG='"'"'{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}}'"'"'
|
||||
{%- endif %}
|
||||
|
||||
{%- if kv_offload %}
|
||||
DECODE_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
|
||||
{%- else %}
|
||||
DECODE_KV_CFG='"'"'{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}}'"'"'
|
||||
{%- endif %}
|
||||
# The kv_transfer_config (NIXL transfer + any KV offload connector) is built in
|
||||
# InferenceConfig.to_vllm() from the per-node config, so it is no longer assembled here.
|
||||
|
||||
DECODE_COMPILE_CFG='"'"'{"cudagraph_mode":"FULL_DECODE_ONLY"}'"'"'
|
||||
|
||||
DP_PER_NODE={{ dp_per_node }}
|
||||
TP=$((GPUS_PER_NODE / DP_PER_NODE))
|
||||
|
||||
# Determine outer replica (P/D pair) and role
|
||||
REPLICA_IDX=$((INFER_NODE_RANK / NODES_PER_REPLICA))
|
||||
RANK_IN_REPLICA=$((INFER_NODE_RANK % NODES_PER_REPLICA))
|
||||
@@ -211,21 +239,14 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
ROLE="prefill"
|
||||
SUB_REPLICA=$((RANK_IN_REPLICA / NODES_PER_PREFILL_REPLICA))
|
||||
ROLE_RANK=$((RANK_IN_REPLICA % NODES_PER_PREFILL_REPLICA))
|
||||
EP=$((NODES_PER_PREFILL_REPLICA * GPUS_PER_NODE))
|
||||
DP=$((NODES_PER_PREFILL_REPLICA * DP_PER_NODE))
|
||||
PORT=$PREFILL_PORT
|
||||
START_RANK=$((ROLE_RANK * GPUS_PER_NODE))
|
||||
HEAD_HOST="${HOSTNAMES[$((REPLICA_BASE + SUB_REPLICA * NODES_PER_PREFILL_REPLICA))]}"
|
||||
|
||||
{% for key, value in prefill_env_overrides.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{% endfor %}
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\""
|
||||
|
||||
if [ "$ROLE_RANK" -eq 0 ]; then
|
||||
VLLM_EXTRA="{\"data_parallel_address\": \"$LOCAL_IP\", \"data_parallel_hybrid_lb\": true, \"kv_transfer_config\": $PREFILL_KV_CFG, $ROLE_EXTRA}"
|
||||
else
|
||||
VLLM_EXTRA="{\"data_parallel_address\": \"$HEAD_HOST\", \"data_parallel_start_rank\": $START_RANK, \"data_parallel_hybrid_lb\": true, \"kv_transfer_config\": $PREFILL_KV_CFG, $ROLE_EXTRA}"
|
||||
fi
|
||||
else
|
||||
# ── Decode node ──
|
||||
export UCX_NET_DEVICES=mlx5_0:1
|
||||
@@ -233,80 +254,63 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
RANK_IN_DECODE=$((RANK_IN_REPLICA - NUM_PREFILL_NODES))
|
||||
SUB_REPLICA=$((RANK_IN_DECODE / NODES_PER_DECODE_REPLICA))
|
||||
ROLE_RANK=$((RANK_IN_DECODE % NODES_PER_DECODE_REPLICA))
|
||||
EP=$((NODES_PER_DECODE_REPLICA * GPUS_PER_NODE))
|
||||
DP=$((NODES_PER_DECODE_REPLICA * DP_PER_NODE))
|
||||
PORT=$DECODE_PORT
|
||||
START_RANK=$((ROLE_RANK * GPUS_PER_NODE))
|
||||
HEAD_HOST="${HOSTNAMES[$((REPLICA_BASE + NUM_PREFILL_NODES + SUB_REPLICA * NODES_PER_DECODE_REPLICA))]}"
|
||||
|
||||
{% for key, value in decode_env_overrides.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{% endfor %}
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG"
|
||||
|
||||
if [ "$ROLE_RANK" -eq 0 ]; then
|
||||
VLLM_EXTRA="{\"data_parallel_address\": \"$LOCAL_IP\", \"data_parallel_hybrid_lb\": true, \"kv_transfer_config\": $DECODE_KV_CFG, $ROLE_EXTRA}"
|
||||
else
|
||||
VLLM_EXTRA="{\"data_parallel_address\": \"$HEAD_HOST\", \"data_parallel_start_rank\": $START_RANK, \"data_parallel_hybrid_lb\": true, \"kv_transfer_config\": $DECODE_KV_CFG, $ROLE_EXTRA}"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "NODE_RANK=$INFER_NODE_RANK ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK EP=$EP PORT=$PORT LOCAL_IP=$LOCAL_IP" \
|
||||
echo "NODE_RANK=$INFER_NODE_RANK ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT LOCAL_IP=$LOCAL_IP" \
|
||||
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
# Start vllm-router on the first prefill node of each replica (background)
|
||||
# Start the router on the first prefill node of each replica (external LB across per-rank endpoints)
|
||||
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
|
||||
ROUTER_LOG="$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log"
|
||||
echo "Starting vllm-router on $LOCAL_IP:$ROUTER_PORT for replica $REPLICA_IDX" | tee $ROUTER_LOG
|
||||
|
||||
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
|
||||
|
||||
vllm-router \
|
||||
--policy {{ router_policy }} \
|
||||
--vllm-pd-disaggregation \
|
||||
$REPLICA_ROUTER_ARGS \
|
||||
--host 0.0.0.0 \
|
||||
--port $ROUTER_PORT \
|
||||
--intra-node-data-parallel-size {{ dp_per_node }} \
|
||||
--worker-startup-timeout-secs 4200 \
|
||||
--log-level debug \
|
||||
>> $ROUTER_LOG 2>&1 &
|
||||
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router_policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
|
||||
fi
|
||||
|
||||
uv run inference \
|
||||
@ $CONFIG_PATH \
|
||||
--server.host 0.0.0.0 \
|
||||
--server.port $PORT \
|
||||
--parallel.dp $EP \
|
||||
--data-parallel-rpc-port $RPC_PORT \
|
||||
--vllm-extra "$VLLM_EXTRA" \
|
||||
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
|
||||
# External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP
|
||||
# slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP
|
||||
# group rooted on the role-replica head (HEAD_HOST); the router balances across the per-rank
|
||||
# endpoints. The kv_transfer_config is built in InferenceConfig.to_vllm() from the config.
|
||||
if [ "$ROLE_RANK" -eq 0 ]; then DP_ADDR=$LOCAL_IP; else DP_ADDR=$HEAD_HOST; fi
|
||||
for k in $(seq 0 $((DP_PER_NODE - 1))); do
|
||||
GLOBAL_RANK=$((ROLE_RANK * DP_PER_NODE + k))
|
||||
RANK_GPUS=$(seq -s, $((k * TP)) $((k * TP + TP - 1)))
|
||||
RANK_EXTRA="{\"data_parallel_address\": \"$DP_ADDR\", \"data_parallel_rank\": $GLOBAL_RANK, $ROLE_EXTRA}"
|
||||
launch_inference_rank "$((PORT + k))" "$RANK_GPUS" "$DP" "$RPC_PORT" "$RANK_EXTRA" "$((5600 + k))" "$(rank_log "$INFER_NODE_RANK" "$k")"
|
||||
done
|
||||
{%- elif num_nodes > 1 %}
|
||||
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
|
||||
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False
|
||||
DP_PER_NODE={{ dp_per_node }}
|
||||
TP=$((GPUS_PER_NODE / DP_PER_NODE))
|
||||
EP={{ "1" if enable_expert_parallel else "0" }}
|
||||
|
||||
# Start router on node 0
|
||||
# Start the router on node 0 (balances across per-rank endpoints — no intra-node DP header)
|
||||
if [ "$INFER_NODE_RANK" -eq 0 ]; then
|
||||
ROUTER_LOG="$OUTPUT_DIR/logs/inference/router.log"
|
||||
echo "Starting vllm-router on $LOCAL_IP:$ROUTER_PORT" | tee $ROUTER_LOG
|
||||
|
||||
vllm-router \
|
||||
--policy {{ router_policy }} \
|
||||
--worker-urls $ROUTER_ARGS \
|
||||
--host 0.0.0.0 \
|
||||
--port $ROUTER_PORT \
|
||||
--intra-node-data-parallel-size {{ dp_per_node }} \
|
||||
--worker-startup-timeout-secs 4200 \
|
||||
--log-level debug \
|
||||
>> $ROUTER_LOG 2>&1 &
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router_policy }}" "$OUTPUT_DIR/logs/inference/router.log"
|
||||
fi
|
||||
|
||||
uv run inference \
|
||||
@ $CONFIG_PATH \
|
||||
--server.host 0.0.0.0 \
|
||||
--server.port $BACKEND_PORT \
|
||||
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
|
||||
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
|
||||
# each pinned to its TP slice of GPUs. Each node is an independent replica, so any MoE EP
|
||||
# group is node-local (rendezvous on LOCAL_IP); dense models run independent engines.
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
RANK_GPUS=$(seq -s, $((d * TP)) $((d * TP + TP - 1)))
|
||||
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
|
||||
if [ "$EP" -eq 1 ]; then
|
||||
RANK_EXTRA="{\"data_parallel_rank\": $d, \"data_parallel_address\": \"$LOCAL_IP\"}"
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$DP_PER_NODE" "$RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
|
||||
else
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
|
||||
fi
|
||||
done
|
||||
{%- else %}
|
||||
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" | tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
# Required for graph compilation to work
|
||||
|
||||
@@ -48,12 +48,6 @@ export DECODE_PORT={{ decode_port }}
|
||||
{%- else -%}
|
||||
export BACKEND_PORT={{ backend_port }}
|
||||
export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parallel else "0" }}
|
||||
|
||||
# Enable distributed EP mode only when expert parallelism spans multiple inference nodes per replica.
|
||||
export USE_DISTRIBUTED_EP=0
|
||||
if [ "$INFERENCE_ENABLE_EXPERT_PARALLEL" -eq 1 ] && [ "$NODES_PER_INFER_REPLICA" -gt 1 ]; then
|
||||
USE_DISTRIBUTED_EP=1
|
||||
fi
|
||||
{%- endif %}
|
||||
{%- endif %}
|
||||
|
||||
@@ -94,17 +88,22 @@ for ((r=0; r<NUM_INFER_REPLICAS; r++)); do
|
||||
INFER_URLS="${INFER_URLS:+$INFER_URLS }http://${router_host}:${ROUTER_PORT}/v1"
|
||||
|
||||
REPLICA_ROUTER_ARGS=""
|
||||
# External-LB: one prefill/decode endpoint per DP rank (PORT + k) on each node.
|
||||
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
|
||||
node_idx=$((replica_base + p))
|
||||
host="${INFER_HOSTS[$node_idx]}"
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:${PREFILL_PORT}/v1"
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:${PREFILL_PORT}"
|
||||
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((PREFILL_PORT + k))/v1"
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
|
||||
done
|
||||
done
|
||||
for ((d=0; d<NUM_DECODE_NODES; d++)); do
|
||||
node_idx=$((replica_base + NUM_PREFILL_NODES + d))
|
||||
host="${INFER_HOSTS[$node_idx]}"
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:${DECODE_PORT}/v1"
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:${DECODE_PORT}"
|
||||
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((DECODE_PORT + k))/v1"
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
|
||||
done
|
||||
done
|
||||
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
|
||||
done
|
||||
@@ -118,8 +117,11 @@ for ((r=0; r<NUM_INFER_REPLICAS; r++)); do
|
||||
for ((n=0; n<NODES_PER_INFER_REPLICA; n++)); do
|
||||
node_idx=$((head_idx + n))
|
||||
host="${INFER_HOSTS[$node_idx]}"
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:${BACKEND_PORT}/v1"
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS http://${host}:${BACKEND_PORT}"
|
||||
# External-LB: one endpoint per DP rank (BACKEND_PORT + dp_local) on each node.
|
||||
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + k))/v1"
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS http://${host}:$((BACKEND_PORT + k))"
|
||||
done
|
||||
done
|
||||
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
|
||||
done
|
||||
@@ -130,9 +132,6 @@ export ALL_ROUTER_ARGS
|
||||
echo "INFER_HOSTS=${INFER_HOSTS[*]}"
|
||||
echo "INFER_URLS=${INFER_URLS}"
|
||||
echo "ADMIN_URLS=${ADMIN_URLS}"
|
||||
{%- if not is_disaggregated %}
|
||||
echo "USE_DISTRIBUTED_EP=${USE_DISTRIBUTED_EP}"
|
||||
{%- endif %}
|
||||
{%- endif %}
|
||||
|
||||
echo "HOSTNAMES=${HOSTNAMES[*]}"
|
||||
@@ -172,9 +171,13 @@ srun bash -s <<'CLEANUP_SH'
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
pkill -9 "vllm::.*" 2>/dev/null
|
||||
# Mooncake store (master + client) left over from a prior offload run. -x matches
|
||||
# the exact process name, so it never hits the worktree path (e.g. mooncake-baby).
|
||||
pkill -9 -x mooncake_master 2>/dev/null
|
||||
pkill -9 -x mooncake_client 2>/dev/null
|
||||
sleep 2
|
||||
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::" | grep -v grep | wc -l)
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
CLEANUP_SH
|
||||
@@ -213,6 +216,9 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
|
||||
{%- if kv_offload %}
|
||||
ulimit -l unlimited
|
||||
{%- endif %}
|
||||
{%- if kv_offload_mooncake %}
|
||||
{% include "_mooncake_store.sh.j2" %}
|
||||
{%- endif %}
|
||||
|
||||
REPLICA_IDX=$((INFER_NODE_RANK / NODES_PER_INFER_REPLICA))
|
||||
@@ -221,6 +227,10 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
echo "INFER_NODE_RANK=$INFER_NODE_RANK REPLICA=$REPLICA_IDX RANK_IN_REPLICA=$RANK_IN_REPLICA LOCAL_IP=$LOCAL_IP" \
|
||||
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
CONFIG_PATH="$CONFIG_DIR/inference.toml"
|
||||
{% include '_launch_rank.sh.j2' %}
|
||||
{% include '_launch_router.sh.j2' %}
|
||||
|
||||
{% if is_disaggregated -%}
|
||||
# PD disaggregated: NIXL KV transfer + role-based inference
|
||||
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
|
||||
@@ -229,25 +239,35 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
export VLLM_MOE_USE_DEEP_GEMM=1
|
||||
{%- endif %}
|
||||
|
||||
export GLOO_SOCKET_IFNAME=bond0
|
||||
# Bind gloo to the interface that owns LOCAL_IP (the rendezvous IP) — NIC
|
||||
# names vary across clusters (bond0, eth0, ...). If the lookup fails, leave
|
||||
# GLOO_SOCKET_IFNAME unset so gloo falls back to its own detection.
|
||||
GLOO_IFNAME=$(ip -o -4 addr show to "$LOCAL_IP" 2>/dev/null | awk "{print \$2; exit}")
|
||||
if [ -n "$GLOO_IFNAME" ]; then export GLOO_SOCKET_IFNAME=$GLOO_IFNAME; fi
|
||||
export VLLM_ENGINE_READY_TIMEOUT_S=4200
|
||||
export UCX_TLS=all
|
||||
export UCX_NET_DEVICES=all
|
||||
# Enumerate RDMA NICs for UCX/NIXL from sysfs (ibv_devices is not on the job
|
||||
# PATH). Prefer InfiniBand ports and fall back to RoCE: "all" would also pick
|
||||
# up non-functional devices (e.g. an Ethernet bond UCX cannot open), which
|
||||
# fails NIXL backend creation. Hosts without RDMA devices keep "all" (TCP).
|
||||
rdma_ports() {
|
||||
for port in /sys/class/infiniband/*/ports/*; do
|
||||
[ "$(cat "$port/link_layer" 2>/dev/null)" = "$1" ] || continue
|
||||
grep -q ACTIVE "$port/state" 2>/dev/null || continue
|
||||
dev=${port%/ports/*}
|
||||
echo "$(basename "$dev"):$(basename "$port")"
|
||||
done | paste -sd,
|
||||
}
|
||||
UCX_NET_DEVICES=$(rdma_ports InfiniBand)
|
||||
[ -n "$UCX_NET_DEVICES" ] || UCX_NET_DEVICES=$(rdma_ports Ethernet)
|
||||
export UCX_NET_DEVICES=${UCX_NET_DEVICES:-all}
|
||||
export LD_LIBRARY_PATH="$PROJECT_DIR/third_party/ucx/lib:$PROJECT_DIR/third_party/ucx/lib/ucx:${LD_LIBRARY_PATH:-}"
|
||||
export VLLM_NIXL_SIDE_CHANNEL_HOST=$LOCAL_IP
|
||||
export VLLM_NIXL_SIDE_CHANNEL_PORT=5600
|
||||
|
||||
{%- if kv_offload %}
|
||||
PREFILL_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
|
||||
{%- else %}
|
||||
PREFILL_KV_CFG='"'"'{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}}'"'"'
|
||||
{%- endif %}
|
||||
# The kv_transfer_config (NIXL transfer + any KV offload connector) is built in
|
||||
# InferenceConfig.to_vllm() from the per-node config, so it is no longer assembled here.
|
||||
|
||||
{%- if kv_offload %}
|
||||
DECODE_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
|
||||
{%- else %}
|
||||
DECODE_KV_CFG='"'"'{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}}'"'"'
|
||||
{%- endif %}
|
||||
DECODE_COMPILE_CFG='"'"'{"cudagraph_mode":"FULL_DECODE_ONLY"}'"'"'
|
||||
|
||||
REPLICA_BASE=$((REPLICA_IDX * NODES_PER_INFER_REPLICA))
|
||||
@@ -283,95 +303,52 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
echo "ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT" \
|
||||
| tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
if [ "$DP" -gt 1 ]; then
|
||||
if [ "$ROLE" = "prefill" ]; then
|
||||
KV_CFG_TO_USE="$PREFILL_KV_CFG"
|
||||
else
|
||||
KV_CFG_TO_USE="$DECODE_KV_CFG"
|
||||
fi
|
||||
|
||||
if [ "$ROLE_RANK" -eq 0 ]; then
|
||||
VLLM_EXTRA="{\"data_parallel_address\": \"$LOCAL_IP\", \"data_parallel_hybrid_lb\": true, \"kv_transfer_config\": $KV_CFG_TO_USE, $ROLE_EXTRA}"
|
||||
else
|
||||
VLLM_EXTRA="{\"data_parallel_address\": \"$HEAD_HOST\", \"data_parallel_start_rank\": $START_RANK, \"data_parallel_hybrid_lb\": true, \"kv_transfer_config\": $KV_CFG_TO_USE, $ROLE_EXTRA}"
|
||||
fi
|
||||
else
|
||||
if [ "$ROLE" = "prefill" ]; then
|
||||
VLLM_EXTRA="{\"kv_transfer_config\": $PREFILL_KV_CFG, $ROLE_EXTRA}"
|
||||
else
|
||||
VLLM_EXTRA="{\"kv_transfer_config\": $DECODE_KV_CFG, $ROLE_EXTRA}"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Start vllm-router on the first node of each replica (PD mode)
|
||||
# Start the router on the first node of each replica (PD mode, external LB across per-rank endpoints)
|
||||
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
|
||||
ROUTER_LOG="$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log"
|
||||
echo "Starting vllm-router (PD) on $LOCAL_IP:$ROUTER_PORT for replica $REPLICA_IDX" | tee $ROUTER_LOG
|
||||
|
||||
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
|
||||
|
||||
vllm-router \
|
||||
--policy consistent_hash \
|
||||
--vllm-pd-disaggregation \
|
||||
$REPLICA_ROUTER_ARGS \
|
||||
--host 0.0.0.0 \
|
||||
--port $ROUTER_PORT \
|
||||
--intra-node-data-parallel-size {{ dp_per_node }} \
|
||||
--worker-startup-timeout-secs 4200 \
|
||||
>> $ROUTER_LOG 2>&1 &
|
||||
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" consistent_hash "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
|
||||
fi
|
||||
|
||||
uv run inference \
|
||||
@ $CONFIG_DIR/inference.toml \
|
||||
--server.host 0.0.0.0 \
|
||||
--server.port $PORT \
|
||||
--parallel.dp $DP \
|
||||
--data-parallel-rpc-port $INFERENCE_DATA_PARALLEL_RPC_PORT \
|
||||
--vllm-extra "$VLLM_EXTRA" \
|
||||
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
|
||||
# External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP
|
||||
# slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP
|
||||
# group rooted on the role-replica head (HEAD_HOST); the router balances across the per-rank
|
||||
# endpoints. The kv_transfer_config is built in InferenceConfig.to_vllm() from the config.
|
||||
if [ "$ROLE_RANK" -eq 0 ]; then DP_ADDR=$LOCAL_IP; else DP_ADDR=$HEAD_HOST; fi
|
||||
for k in $(seq 0 $((INFERENCE_DP_LOCAL - 1))); do
|
||||
GLOBAL_RANK=$((START_RANK + k))
|
||||
RANK_GPUS=$(seq -s, $((k * INFERENCE_TP)) $((k * INFERENCE_TP + INFERENCE_TP - 1)))
|
||||
RANK_EXTRA="{\"data_parallel_address\": \"$DP_ADDR\", \"data_parallel_rank\": $GLOBAL_RANK, $ROLE_EXTRA}"
|
||||
launch_inference_rank "$((PORT + k))" "$RANK_GPUS" "$DP" "$INFERENCE_DATA_PARALLEL_RPC_PORT" "$RANK_EXTRA" "$((5600 + k))" "$(rank_log "$INFER_NODE_RANK" "$k")"
|
||||
done
|
||||
{%- else -%}
|
||||
# Start vllm-router on the first node of each replica
|
||||
# Start the router on the first node of each replica
|
||||
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
|
||||
ROUTER_LOG="$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log"
|
||||
echo "Starting vllm-router on $LOCAL_IP:$ROUTER_PORT for replica $REPLICA_IDX" | tee $ROUTER_LOG
|
||||
|
||||
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
|
||||
|
||||
vllm-router \
|
||||
--policy consistent_hash \
|
||||
--worker-urls $REPLICA_ROUTER_ARGS \
|
||||
--host 0.0.0.0 \
|
||||
--port $ROUTER_PORT \
|
||||
--intra-node-data-parallel-size {{ dp_per_node }} \
|
||||
--worker-startup-timeout-secs 4200 \
|
||||
>> $ROUTER_LOG 2>&1 &
|
||||
launch_router regular "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" consistent_hash "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
|
||||
fi
|
||||
|
||||
if [ "$USE_DISTRIBUTED_EP" -eq 1 ]; then
|
||||
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
|
||||
REPLICA_HEAD_HOST="${HOSTNAMES[$((REPLICA_IDX * NODES_PER_INFER_REPLICA))]}"
|
||||
INFER_DP_START_RANK=$((RANK_IN_REPLICA * INFERENCE_DP_LOCAL))
|
||||
|
||||
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
|
||||
VLLM_EXTRA="{\"data_parallel_address\": \"$LOCAL_IP\", \"data_parallel_hybrid_lb\": true}"
|
||||
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + d),
|
||||
# each pinned to its TP slice of GPUs; the router balances across the per-rank
|
||||
# endpoints. For MoE the ranks form one external-LB DP group (EP all2all spans
|
||||
# them) rooted on the replica-head DP coordinator. data_parallel_address is
|
||||
# per-node, not per-rank: every rank on the head reaches the coordinator via the
|
||||
# head LOCAL_IP, ranks on other nodes via the head hostname (matches the P/D path).
|
||||
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
|
||||
REPLICA_HEAD_HOST="${HOSTNAMES[$((REPLICA_IDX * NODES_PER_INFER_REPLICA))]}"
|
||||
INFER_GROUP_DP=$((NODES_PER_INFER_REPLICA * INFERENCE_DP_LOCAL))
|
||||
if [ "$RANK_IN_REPLICA" -eq 0 ]; then DP_ADDR="$LOCAL_IP"; else DP_ADDR="$REPLICA_HEAD_HOST"; fi
|
||||
for ((d=0; d<INFERENCE_DP_LOCAL; d++)); do
|
||||
RANK_GPUS=$(seq -s, $((d * INFERENCE_TP)) $((d * INFERENCE_TP + INFERENCE_TP - 1)))
|
||||
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
|
||||
if [ "$INFERENCE_ENABLE_EXPERT_PARALLEL" -eq 1 ]; then
|
||||
GLOBAL_DP_RANK=$((RANK_IN_REPLICA * INFERENCE_DP_LOCAL + d))
|
||||
RANK_EXTRA="{\"data_parallel_rank\": $GLOBAL_DP_RANK, \"data_parallel_address\": \"$DP_ADDR\"}"
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$INFER_GROUP_DP" "$INFERENCE_DATA_PARALLEL_RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
|
||||
else
|
||||
VLLM_EXTRA="{\"data_parallel_address\": \"$REPLICA_HEAD_HOST\", \"data_parallel_start_rank\": $INFER_DP_START_RANK, \"data_parallel_hybrid_lb\": true}"
|
||||
# Dense: independent single-engine servers (no DP linkage).
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
|
||||
fi
|
||||
|
||||
uv run inference \
|
||||
@ $CONFIG_DIR/inference.toml \
|
||||
--server.host 0.0.0.0 \
|
||||
--server.port $BACKEND_PORT \
|
||||
--data-parallel-rpc-port $INFERENCE_DATA_PARALLEL_RPC_PORT \
|
||||
--vllm-extra "$VLLM_EXTRA" \
|
||||
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
|
||||
else
|
||||
uv run inference \
|
||||
@ $CONFIG_DIR/inference.toml \
|
||||
--server.host 0.0.0.0 \
|
||||
--server.port $BACKEND_PORT \
|
||||
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
|
||||
fi
|
||||
done
|
||||
{%- endif %}
|
||||
|
||||
else
|
||||
@@ -426,7 +403,7 @@ REMAINING_PIDS=$(jobs -p)
|
||||
# in-flight trainer checkpoint on this node finish, and — because the task has
|
||||
# not exited yet — keeps --kill-on-bad-exit from reaping checkpointing trainers
|
||||
# on peer nodes. We then propagate the exit code so the allocation tears down. A
|
||||
# clean (zero) exit can't trip --kill-on-bad-exit, so we tear down immediately.
|
||||
# clean (zero) exit cannot trip --kill-on-bad-exit, so we tear down immediately.
|
||||
if [ "$EXIT_CODE" -ne 0 ]; then
|
||||
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for in-flight checkpoints to flush before teardown"
|
||||
sleep {{ cleanup_grace_period }}
|
||||
|
||||
@@ -9,7 +9,7 @@ from typing import Any
|
||||
|
||||
import torch
|
||||
from torch import Tensor, nn
|
||||
from torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dict
|
||||
from torch.distributed.checkpoint.state_dict import get_state_dict, set_model_state_dict, set_state_dict
|
||||
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
|
||||
from torch.distributed.checkpoint.state_dict_saver import save as dcp_save
|
||||
from torch.distributed.checkpoint.stateful import Stateful
|
||||
@@ -67,8 +67,13 @@ class AppState(Stateful):
|
||||
"""Extract base optimizers from wrappers like CPUOffloadOptimizer."""
|
||||
return [opt.base_optimizer if isinstance(opt, CPUOffloadOptimizer) else opt for opt in self.optimizers]
|
||||
|
||||
def _has_cpu_offload(self) -> bool:
|
||||
return any(isinstance(opt, CPUOffloadOptimizer) for opt in self.optimizers)
|
||||
|
||||
def state_dict(self) -> dict[str, Any]:
|
||||
# Move CPU-offloaded states to GPU before checkpointing
|
||||
# get_state_dict requires optimizer states to live on param.device. For an
|
||||
# already-initialized CPU-offload optimizer that means staging back to GPU
|
||||
# before the call; the matching offload happens after the dict is built.
|
||||
for opt in self.optimizers:
|
||||
if isinstance(opt, CPUOffloadOptimizer) and opt._initialized:
|
||||
opt._move_states("cuda")
|
||||
@@ -88,26 +93,53 @@ class AppState(Stateful):
|
||||
progress_state_dict = asdict(self.progress)
|
||||
state_dict["progress"] = progress_state_dict
|
||||
|
||||
# Move states back to CPU
|
||||
# Offload optimizer states to CPU for every CPUOffloadOptimizer, including
|
||||
# ones that were uninitialized on entry. dcp_load calls this method to build
|
||||
# a template, and get_state_dict's internal _init_optim_state populates an
|
||||
# empty optim.state with GPU tensors. Optimizer.state_dict() returns those
|
||||
# values via shallow copy, so optimizer_state_dict["state"][fqn] is the same
|
||||
# dict object as optim.state[param]. Replacing the entries with CPU tensors
|
||||
# in place therefore flips the template too — dcp_load reads bytes from disk
|
||||
# straight into CPU storage and optim.state is loaded by the time the load
|
||||
# returns, without GPU optimizer state ever existing for the duration of the
|
||||
# read.
|
||||
has_cpu_offload = self._has_cpu_offload()
|
||||
for opt in self.optimizers:
|
||||
if isinstance(opt, CPUOffloadOptimizer) and opt._initialized:
|
||||
if isinstance(opt, CPUOffloadOptimizer):
|
||||
opt._move_states("cpu")
|
||||
if has_cpu_offload:
|
||||
gc.collect()
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
return state_dict
|
||||
|
||||
def load_state_dict(self, state_dict: dict[str, Any]):
|
||||
base_optimizers = self._get_base_optimizers()
|
||||
set_state_dict(
|
||||
self.model, base_optimizers, model_state_dict=state_dict["model"], optim_state_dict=state_dict["optimizers"]
|
||||
)
|
||||
has_cpu_offload = self._has_cpu_offload()
|
||||
|
||||
# Re-initialize CPU offload wrappers after loading
|
||||
has_cpu_offload = False
|
||||
for opt in self.optimizers:
|
||||
if isinstance(opt, CPUOffloadOptimizer):
|
||||
opt._move_states("cpu")
|
||||
opt._initialized = True
|
||||
has_cpu_offload = True
|
||||
if has_cpu_offload:
|
||||
# When CPU offload is on, the optimizer is already loaded by the time we
|
||||
# get here: state_dict() handed dcp_load a template whose tensors share
|
||||
# storage with optim.state[p][k], and dcp_load wrote the checkpoint bytes
|
||||
# directly into those tensors via target_tensor.copy_(...). Running
|
||||
# set_state_dict on the optimizer would route the loaded CPU values
|
||||
# through Optimizer.load_state_dict, whose _cast hook does
|
||||
# value.to(param.dtype, param.device) and would allocate a fresh GPU
|
||||
# copy of every state tensor — undoing the in-place CPU load and
|
||||
# detaching optim.state from the tensors we just populated. So we only
|
||||
# apply the model side here and flip the wrappers to initialized so
|
||||
# subsequent steps take the steady-state path.
|
||||
set_model_state_dict(self.model, model_state_dict=state_dict["model"])
|
||||
for opt in self.optimizers:
|
||||
if isinstance(opt, CPUOffloadOptimizer):
|
||||
opt._initialized = True
|
||||
else:
|
||||
set_state_dict(
|
||||
self.model,
|
||||
base_optimizers,
|
||||
model_state_dict=state_dict["model"],
|
||||
optim_state_dict=state_dict["optimizers"],
|
||||
)
|
||||
|
||||
if self.scheduler is not None:
|
||||
self.scheduler.load_state_dict(state_dict["scheduler"])
|
||||
@@ -115,15 +147,13 @@ class AppState(Stateful):
|
||||
for key, value in state_dict["progress"].items():
|
||||
setattr(self.progress, key, value)
|
||||
|
||||
# Reclaim GPU memory freed by moving optimizer states to CPU.
|
||||
# After set_state_dict + _move_states("cpu"), the optimizer states live on CPU,
|
||||
# but the state_dict (owned by dcp_load) still holds references to stale GPU
|
||||
# optimizer tensors. Clearing them and flushing the CUDA cache prevents OOM on
|
||||
# the first training step.
|
||||
# state_dict is the same dict object that dcp_load held internally; clearing
|
||||
# it drops the last references to the loaded tensor wrappers so the cuda
|
||||
# allocator can release whatever blocks it cached during the read.
|
||||
if has_cpu_offload:
|
||||
state_dict.clear() # drop stale GPU tensor references from dcp_load
|
||||
gc.collect() # break any circular references so tensors are freed
|
||||
torch.cuda.empty_cache() # return freed GPU memory to CUDA
|
||||
state_dict.clear()
|
||||
gc.collect()
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
|
||||
class CheckpointManager:
|
||||
@@ -171,7 +201,12 @@ class CheckpointManager:
|
||||
# Checkpoint the local dataloader
|
||||
if dataloader is not None:
|
||||
dataloader_dir = path / "dataloader"
|
||||
dataloader_dir.mkdir(parents=True, exist_ok=True)
|
||||
# Only the master creates the dir; the rest wait at a barrier. On a
|
||||
# parallel FS (beegfs), concurrent mkdir from every rank can re-raise
|
||||
# FileExistsError (EEXIST + stale is_dir() metadata).
|
||||
if self.world.is_master:
|
||||
dataloader_dir.mkdir(parents=True, exist_ok=True)
|
||||
torch.distributed.barrier()
|
||||
torch.save(dataloader.state_dict(), dataloader_dir / f"rank_{self.world.rank}.pt")
|
||||
|
||||
# Save sharded state
|
||||
@@ -239,7 +274,11 @@ class CheckpointManager:
|
||||
) -> None:
|
||||
"""Save the full checkpoint state for a specified step."""
|
||||
ckpt_path = self.get_ckpt_path(step)
|
||||
ckpt_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Master-only mkdir + barrier: concurrent mkdir from every rank can
|
||||
# re-raise FileExistsError on a parallel FS (see save_to_path).
|
||||
if self.world.is_master:
|
||||
ckpt_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
torch.distributed.barrier()
|
||||
|
||||
self.save_to_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
|
||||
bisect.insort(self.ckpt_steps, step)
|
||||
@@ -390,7 +429,11 @@ class WeightCheckpointManager:
|
||||
):
|
||||
"""Save a HF-compatible weight-only checkpoint for a given step."""
|
||||
step_path = self.get_step_path(step)
|
||||
step_path.mkdir(parents=True, exist_ok=True)
|
||||
# Master-only mkdir + barrier: concurrent mkdir from every rank can
|
||||
# re-raise FileExistsError on a parallel FS (EEXIST + stale is_dir()).
|
||||
if self.world.is_master:
|
||||
step_path.mkdir(parents=True, exist_ok=True)
|
||||
torch.distributed.barrier()
|
||||
|
||||
# Gather all weights on master rank
|
||||
self.logger.debug("Gathering weights on master rank for weight checkpoint")
|
||||
@@ -420,7 +463,6 @@ class WeightCheckpointManager:
|
||||
f"Converted PrimeRL format to HF format in {time.perf_counter() - start_time:.2f} seconds"
|
||||
)
|
||||
else:
|
||||
# For regular transformers models, revert internal format to original HF hub format
|
||||
from transformers.core_model_loading import revert_weight_conversion
|
||||
|
||||
self.logger.debug("Reverting transformers internal format to HF hub format for weight checkpoint")
|
||||
|
||||
@@ -79,7 +79,7 @@ def _patch_qwen3_5_moe_conversion_mapping():
|
||||
incorrectly maps qwen3_5_moe → qwen2_moe, which assumes per-expert 2D checkpoint weights,
|
||||
causing revert_weight_conversion to produce wrong shapes during weight broadcasting.
|
||||
|
||||
Remove once the pinned transformers commit fixes this.
|
||||
Remove once an official Transformers release fixes this.
|
||||
"""
|
||||
from transformers.conversion_mapping import (
|
||||
get_checkpoint_conversion_mapping,
|
||||
@@ -99,7 +99,7 @@ def _patch_qwen3_5_text_position_ids():
|
||||
"""Fix Qwen3.5 passing 3D MRoPE position_ids to decoder layers instead of 2D text_position_ids.
|
||||
|
||||
Upstream fix: https://github.com/huggingface/transformers/pull/44399
|
||||
Remove once the pinned transformers commit includes this fix.
|
||||
Remove once an official Transformers release includes this fix.
|
||||
"""
|
||||
import inspect
|
||||
|
||||
@@ -518,6 +518,15 @@ def get_model(
|
||||
|
||||
logger.debug(f"Loaded model config ({model_config.to_dict()})")
|
||||
|
||||
# NemotronH: transformers' Mamba2 mixer __init__ calls lazy_load_kernel("mamba-ssm" /
|
||||
# "causal-conv1d") whenever config.use_mamba_kernels is set. That hub-kernel path is gated only
|
||||
# by whether the `kernels` package is importable (NOT by USE_HUB_KERNELS) and resolves from the
|
||||
# HF Hub, which hard-crashes under HF_HUB_OFFLINE=1. prime-rl swaps in its own mamba_ssm Triton
|
||||
# SSD kernels via _patch_mamba2_use_triton_ssd, so the hub kernels are redundant; disable them
|
||||
# to keep model init offline-safe.
|
||||
if getattr(model_config, "model_type", "") == "nemotron_h":
|
||||
model_config.use_mamba_kernels = False
|
||||
|
||||
if config.debug.num_layers is not None:
|
||||
# VLM configs nest num_hidden_layers under text_config
|
||||
target_config = getattr(model_config, "text_config", model_config)
|
||||
|
||||
@@ -550,3 +550,71 @@ def per_block_cast_to_fp8_triton(
|
||||
gran_k,
|
||||
)
|
||||
return out[0], sf[0]
|
||||
|
||||
|
||||
def per_block_cast_to_fp8_tp_triton(
|
||||
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Block-fp8 cast of ``x.T`` without materializing the transpose."""
|
||||
assert x.dim() == 2
|
||||
assert gran_k == GROUP_ALIGNMENT
|
||||
rows, cols = x.shape
|
||||
x3 = x.unsqueeze(0)
|
||||
out = torch.empty((cols, rows), device=x.device, dtype=torch.float8_e4m3fn)
|
||||
sf = torch.empty((ceil_div(cols, gran_k), ceil_div(rows, gran_k)), device=x.device, dtype=torch.float32)
|
||||
grid = (1, ceil_div(rows, gran_k), ceil_div(cols, gran_k))
|
||||
_grouped_per_block_fp8_kernel[grid](
|
||||
x3,
|
||||
out,
|
||||
sf,
|
||||
1,
|
||||
rows,
|
||||
cols,
|
||||
x3.stride(0),
|
||||
x3.stride(1),
|
||||
x3.stride(2),
|
||||
# transposed output: x's element (row, col) lands at out[col, row]
|
||||
cols * rows,
|
||||
1,
|
||||
rows,
|
||||
# transposed scales: x's tile (pid_m, pid_n) lands at sf[pid_n, pid_m]
|
||||
ceil_div(cols, gran_k) * ceil_div(rows, gran_k),
|
||||
1,
|
||||
ceil_div(rows, gran_k),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
BLOCK_M=gran_k,
|
||||
BLOCK_N=gran_k,
|
||||
num_warps=8,
|
||||
)
|
||||
return out, sf
|
||||
|
||||
|
||||
def per_token_cast_to_fp8_tp_triton(
|
||||
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Per-token fp8 cast of ``x.T`` without materializing the transpose."""
|
||||
assert x.dim() == 2
|
||||
assert gran_k == GROUP_ALIGNMENT
|
||||
rows, cols = x.shape
|
||||
out = torch.empty((cols, rows), device=x.device, dtype=torch.float8_e4m3fn)
|
||||
sf = torch.empty((cols, ceil_div(rows, gran_k)), device=x.device, dtype=torch.float32)
|
||||
grid = lambda meta: (ceil_div(cols, meta["BLOCK_M"]), ceil_div(rows, meta["BLOCK_K"]))
|
||||
_per_token_fp8_kernel[grid](
|
||||
x,
|
||||
out,
|
||||
sf,
|
||||
cols,
|
||||
rows,
|
||||
# transposed read: the kernel's per-row amax reduces over x's rows
|
||||
x.stride(1),
|
||||
x.stride(0),
|
||||
out.stride(0),
|
||||
out.stride(1),
|
||||
sf.stride(0),
|
||||
sf.stride(1),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
BLOCK_M=8,
|
||||
BLOCK_K=gran_k,
|
||||
num_warps=4,
|
||||
)
|
||||
return out, sf
|
||||
|
||||
@@ -12,7 +12,9 @@ import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_utils import (
|
||||
per_block_cast_to_fp8_tp_triton,
|
||||
per_block_cast_to_fp8_triton,
|
||||
per_token_cast_to_fp8_tp_triton,
|
||||
per_token_cast_to_fp8_triton,
|
||||
)
|
||||
from prime_rl.utils.logger import get_logger
|
||||
@@ -43,8 +45,7 @@ class _FP8BlockwiseMM(torch.autograd.Function):
|
||||
grad_x = grad_weight = None
|
||||
if ctx.needs_input_grad[0]:
|
||||
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, False, block_size)
|
||||
weight_t = weight.transpose(0, 1).contiguous()
|
||||
weight_dx_fp8 = per_block_cast_to_fp8_triton(weight_t, False, block_size)
|
||||
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, False, block_size)
|
||||
grad_x_2d = torch.empty_like(x_2d)
|
||||
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
|
||||
grad_x = grad_x_2d.reshape(ctx.x_shape)
|
||||
@@ -62,10 +63,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
|
||||
else:
|
||||
grad_output_2d_padded = grad_output_2d
|
||||
x_2d_padded = x_2d
|
||||
grad_output_t = grad_output_2d_padded.transpose(0, 1).contiguous()
|
||||
x_t = x_2d_padded.transpose(0, 1).contiguous()
|
||||
grad_output_t_fp8 = per_token_cast_to_fp8_triton(grad_output_t, False, block_size)
|
||||
x_t_fp8 = per_token_cast_to_fp8_triton(x_t, False, block_size)
|
||||
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, False, block_size)
|
||||
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, False, block_size)
|
||||
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
|
||||
deep_gemm.fp8_gemm_nt(
|
||||
grad_output_t_fp8,
|
||||
|
||||
@@ -955,32 +955,44 @@ class NemotronHRouter(nn.Module):
|
||||
self.norm_topk_prob = norm_topk_prob
|
||||
|
||||
def forward(
|
||||
self, x: torch.Tensor, expert_bias: torch.Tensor | None = None
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
expert_bias: torch.Tensor | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
scores = F.linear(x.float(), self.gate.float()).sigmoid()
|
||||
scores_for_choice = scores + self.e_score_correction_bias
|
||||
|
||||
if expert_bias is not None:
|
||||
scores_for_choice = scores_for_choice + expert_bias
|
||||
if routed_experts is not None:
|
||||
# Router replay: reuse the inference engine's expert selection and
|
||||
# only recompute the gating weights from the trainer's scores. The
|
||||
# correction/load-balancing biases only affect selection, so they
|
||||
# are intentionally skipped here.
|
||||
selected_experts_indices = routed_experts
|
||||
else:
|
||||
scores_for_choice = scores + self.e_score_correction_bias
|
||||
|
||||
# Group-based routing
|
||||
if self.n_group > 1:
|
||||
group_scores = (
|
||||
scores_for_choice.view(-1, self.n_group, self.num_experts // self.n_group)
|
||||
.topk(2, dim=-1)[0]
|
||||
.sum(dim=-1)
|
||||
)
|
||||
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
|
||||
group_mask = torch.zeros_like(group_scores)
|
||||
group_mask.scatter_(1, group_idx, 1)
|
||||
score_mask = (
|
||||
group_mask.unsqueeze(-1)
|
||||
.expand(-1, self.n_group, self.num_experts // self.n_group)
|
||||
.reshape(-1, self.num_experts)
|
||||
)
|
||||
scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), 0.0)
|
||||
if expert_bias is not None:
|
||||
scores_for_choice = scores_for_choice + expert_bias
|
||||
|
||||
# Group-based routing
|
||||
if self.n_group > 1:
|
||||
group_scores = (
|
||||
scores_for_choice.view(-1, self.n_group, self.num_experts // self.n_group)
|
||||
.topk(2, dim=-1)[0]
|
||||
.sum(dim=-1)
|
||||
)
|
||||
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
|
||||
group_mask = torch.zeros_like(group_scores)
|
||||
group_mask.scatter_(1, group_idx, 1)
|
||||
score_mask = (
|
||||
group_mask.unsqueeze(-1)
|
||||
.expand(-1, self.n_group, self.num_experts // self.n_group)
|
||||
.reshape(-1, self.num_experts)
|
||||
)
|
||||
scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), 0.0)
|
||||
|
||||
selected_experts_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
|
||||
|
||||
selected_experts_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
|
||||
top_scores = scores.gather(1, selected_experts_indices)
|
||||
routing_confidence_sum = _selected_probability_mass_sum(scores, top_scores, "sigmoid")
|
||||
|
||||
@@ -1181,8 +1193,13 @@ class LatentMoE(nn.Module):
|
||||
bs, slen, dim = x.shape
|
||||
x_flat = x.view(-1, dim)
|
||||
|
||||
if routed_experts is not None:
|
||||
# Flatten to (bs * slen, top_k); reshape (not view) since the slice is non-contiguous.
|
||||
_, _, top_k = routed_experts.shape
|
||||
routed_experts = routed_experts.reshape(-1, top_k)
|
||||
|
||||
top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum = self.router(
|
||||
x_flat, self.expert_bias
|
||||
x_flat, self.expert_bias, routed_experts=routed_experts
|
||||
)
|
||||
|
||||
with torch.no_grad():
|
||||
|
||||
@@ -223,6 +223,7 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
@@ -266,10 +267,11 @@ class NemotronHMoELayer(GradientCheckpointingLayer):
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states, routed_experts=routed_experts)
|
||||
return residual + hidden_states
|
||||
|
||||
|
||||
@@ -298,6 +300,7 @@ class NemotronHAttentionLayer(GradientCheckpointingLayer):
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
@@ -498,7 +501,13 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
) -> BaseModelOutputWithPast:
|
||||
"""
|
||||
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
|
||||
Routed experts for each token, indexed by global layer index. Only used for router replay; slots
|
||||
for non-MoE (Mamba/attention) layers are ignored.
|
||||
"""
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
|
||||
@@ -516,12 +525,15 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids) if self.rotary_emb is not None else None
|
||||
|
||||
for decoder_layer in self.layers:
|
||||
for layer_idx, decoder_layer in enumerate(self.layers):
|
||||
# routed_experts is indexed by global layer index; non-MoE layers ignore it.
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
routed_experts=routed_experts_layer,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
@@ -550,6 +562,7 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
|
||||
labels: Optional[torch.LongTensor] = None,
|
||||
logits_to_keep: int = 0,
|
||||
temperature: Optional[torch.Tensor] = None,
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
**kwargs,
|
||||
) -> PrimeLmOutput:
|
||||
if position_ids is None:
|
||||
@@ -562,6 +575,7 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
|
||||
input_ids=input_ids,
|
||||
position_ids=position_ids,
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
|
||||
@@ -46,7 +46,6 @@ class FileSystemWeightBroadcast(WeightBroadcast):
|
||||
if isinstance(model, PreTrainedModelPrimeRL) and model.is_prime_state_dict(state_dict):
|
||||
model.convert_to_hf(state_dict)
|
||||
else:
|
||||
# For regular transformers models, revert internal format to original HF hub format
|
||||
from transformers.core_model_loading import revert_weight_conversion
|
||||
|
||||
state_dict = revert_weight_conversion(model, state_dict)
|
||||
|
||||
@@ -247,7 +247,12 @@ class MultiRunManager:
|
||||
|
||||
# Run registered validation hooks
|
||||
for hook in self._config_validation_hooks:
|
||||
is_valid, error_message = hook(config)
|
||||
try:
|
||||
is_valid, error_message = hook(config)
|
||||
except Exception as e:
|
||||
hook_name = getattr(hook, "__name__", type(hook).__name__)
|
||||
is_valid = False
|
||||
error_message = f"Validation hook {hook_name} crashed: {e}"
|
||||
if not is_valid:
|
||||
self.logger.error(f"Run {run_id}: {error_message}")
|
||||
if error_path.parent.exists():
|
||||
@@ -510,6 +515,8 @@ def setup_multi_run_manager(
|
||||
trainer_lora = lora_config
|
||||
|
||||
def validate_lora_rank(orch_config: "OrchestratorConfig") -> tuple[bool, str]:
|
||||
if orch_config.student.model.lora is None:
|
||||
return False, "student.model.lora is required when trainer is configured with LoRA"
|
||||
# Default to trainer's rank/alpha if not specified
|
||||
if orch_config.student.model.lora.rank is None:
|
||||
orch_config.student.model.lora.rank = trainer_lora.rank
|
||||
|
||||
@@ -2,6 +2,7 @@ from pathlib import Path
|
||||
from time import time
|
||||
|
||||
import zmq
|
||||
import zmq.asyncio
|
||||
|
||||
from prime_rl.configs.shared import ZMQTransportConfig
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
@@ -20,8 +21,10 @@ class ZMQTrainingBatchSender(TrainingBatchSender):
|
||||
def __init__(self, output_dir: Path, transport: ZMQTransportConfig):
|
||||
super().__init__(output_dir)
|
||||
|
||||
self.context = zmq.Context.instance()
|
||||
self.socket: zmq.Socket = self.context.socket(zmq.PUSH)
|
||||
# Async context so ``send`` yields instead of blocking the orchestrator
|
||||
# event loop when the trainer is slow and we hit SNDHWM.
|
||||
self.context = zmq.asyncio.Context.instance()
|
||||
self.socket: zmq.asyncio.Socket = self.context.socket(zmq.PUSH)
|
||||
self.socket.setsockopt(zmq.SNDHWM, transport.hwm)
|
||||
self.socket.connect(f"tcp://{transport.host}:{transport.port}")
|
||||
|
||||
@@ -35,7 +38,7 @@ class ZMQTrainingBatchSender(TrainingBatchSender):
|
||||
async def send(self, batch: TrainingBatch) -> None:
|
||||
payload = self.encoder.encode(batch)
|
||||
self.logger.debug(f"Sending batch {batch.step} to {self.sender_id}")
|
||||
self.socket.send_multipart([self.sender_id, payload], copy=False)
|
||||
await self.socket.send_multipart([self.sender_id, payload], copy=False)
|
||||
|
||||
def close(self) -> None:
|
||||
try:
|
||||
|
||||
@@ -12,7 +12,7 @@ import verifiers as vf
|
||||
from httpx import AsyncClient
|
||||
from openai import NotFoundError
|
||||
from renderers import RendererConfig
|
||||
from tenacity import retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
|
||||
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
@@ -303,8 +303,8 @@ async def check_health(
|
||||
NCCL_READY_MARKER = "NCCL_READY"
|
||||
|
||||
|
||||
def _is_retryable_pause_error(exception: BaseException) -> bool:
|
||||
"""Check if an exception should trigger a retry for pausing engines."""
|
||||
def _is_retryable_admin_error(exception: BaseException) -> bool:
|
||||
"""Check if an exception should trigger a retry for an admin op (pause/resume/update_weights)."""
|
||||
if isinstance(exception, httpx.HTTPStatusError):
|
||||
# Retry on transient server errors (5xx, e.g. engine briefly unresponsive);
|
||||
# client errors (4xx) won't fix themselves on retry.
|
||||
@@ -317,47 +317,55 @@ def _is_retryable_pause_error(exception: BaseException) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
# Per-attempt and total bounds for `/pause`. Pausing drains in-flight requests
|
||||
# (mode="keep"), so a single attempt can legitimately take a while, but the global
|
||||
# admin AsyncClient uses `timeout=None`, so a stuck server would hang the weight
|
||||
# update forever. `_READ_TIMEOUT` converts a hang into a TimeoutException so
|
||||
# tenacity retries; `_TOTAL` is the wall-clock budget across all retries.
|
||||
PAUSE_READ_TIMEOUT_S = 120.0
|
||||
PAUSE_TOTAL_TIMEOUT_S = 300.0
|
||||
# Per-attempt read timeout for admin ops, overridable per call. The admin
|
||||
# AsyncClient uses `timeout=None`, so without this a stuck server would hang the
|
||||
# weight update forever: the read timeout converts a hang into a TimeoutException
|
||||
# that tenacity retries. Sized for `/pause`, which drains in-flight requests
|
||||
# (mode="keep") and so can legitimately take a while.
|
||||
ADMIN_TIMEOUT_S = 300.0
|
||||
# `/update_weights` runs a collective NCCL receive across all DP workers, which
|
||||
# can take longer than the other admin ops.
|
||||
UPDATE_WEIGHTS_TIMEOUT_S = 720.0
|
||||
|
||||
|
||||
async def _admin_post(client: AsyncClient, path: str, *, timeout_s: float = ADMIN_TIMEOUT_S, **kwargs) -> None:
|
||||
"""POST an admin op with a bounded per-attempt timeout, retrying transient errors.
|
||||
|
||||
The total wall-clock budget across all retries is twice the per-attempt timeout.
|
||||
"""
|
||||
async for attempt in AsyncRetrying(
|
||||
retry=retry_if_exception(_is_retryable_admin_error),
|
||||
stop=stop_after_delay(2 * timeout_s) | stop_after_attempt(10),
|
||||
wait=wait_exponential(multiplier=1, min=1, max=10),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
response = await client.post(
|
||||
path,
|
||||
timeout=httpx.Timeout(connect=10.0, read=timeout_s, write=60.0, pool=10.0),
|
||||
**kwargs,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
|
||||
async def _pause_engines(admin_clients: list[AsyncClient], *, step: int) -> None:
|
||||
"""Pause all inference engines, waiting for in-flight requests to drain."""
|
||||
logger = get_logger()
|
||||
logger.info(f"Updating policy in-flight to v{step}")
|
||||
|
||||
@retry(
|
||||
retry=retry_if_exception(_is_retryable_pause_error),
|
||||
stop=stop_after_delay(PAUSE_TOTAL_TIMEOUT_S) | stop_after_attempt(10),
|
||||
wait=wait_exponential(multiplier=1, min=1, max=10),
|
||||
reraise=True,
|
||||
await asyncio.gather(
|
||||
*[_admin_post(client, "/pause", params={"mode": "keep", "clear_cache": "false"}) for client in admin_clients]
|
||||
)
|
||||
async def _pause(client: AsyncClient) -> None:
|
||||
response = await client.post(
|
||||
"/pause",
|
||||
params={"mode": "keep", "clear_cache": "false"},
|
||||
timeout=httpx.Timeout(connect=10.0, read=PAUSE_READ_TIMEOUT_S, write=60.0, pool=10.0),
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
await asyncio.gather(*[_pause(client) for client in admin_clients])
|
||||
logger.debug("All inference engines paused")
|
||||
|
||||
|
||||
async def _resume_engines(admin_clients: list[AsyncClient]) -> None:
|
||||
"""Resume all inference engines after weight update."""
|
||||
"""Resume all inference engines after weight update.
|
||||
|
||||
Resuming is idempotent (it just clears the paused flag), so retrying transient
|
||||
failures is safe; a dropped /resume would leave engines paused indefinitely.
|
||||
"""
|
||||
logger = get_logger()
|
||||
|
||||
async def _resume(client: AsyncClient) -> None:
|
||||
response = await client.post("/resume")
|
||||
response.raise_for_status()
|
||||
|
||||
await asyncio.gather(*[_resume(client) for client in admin_clients])
|
||||
await asyncio.gather(*[_admin_post(client, "/resume") for client in admin_clients])
|
||||
logger.debug("All inference engines resumed")
|
||||
|
||||
|
||||
@@ -383,11 +391,6 @@ async def update_weights(
|
||||
if lora_name is not None and weight_dir is not None:
|
||||
await load_lora_adapter(admin_clients, lora_name, weight_dir)
|
||||
else:
|
||||
|
||||
async def _update_weights(admin_client: AsyncClient, weight_dir: str | None) -> None:
|
||||
response = await admin_client.post("/update_weights", json={"weight_dir": weight_dir})
|
||||
response.raise_for_status()
|
||||
|
||||
# Pause engines so all DP workers drain in-flight work and can join the NCCL broadcast
|
||||
await _pause_engines(admin_clients, step=step)
|
||||
|
||||
@@ -399,7 +402,17 @@ async def update_weights(
|
||||
nccl_ready_file.touch()
|
||||
logger.debug(f"Created NCCL_READY marker at {nccl_ready_file}")
|
||||
|
||||
await asyncio.gather(*[_update_weights(admin_client, weight_dir_posix) for admin_client in admin_clients])
|
||||
await asyncio.gather(
|
||||
*[
|
||||
_admin_post(
|
||||
admin_client,
|
||||
"/update_weights",
|
||||
json={"weight_dir": weight_dir_posix},
|
||||
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
|
||||
)
|
||||
for admin_client in admin_clients
|
||||
]
|
||||
)
|
||||
finally:
|
||||
await _resume_engines(admin_clients)
|
||||
|
||||
|
||||
@@ -406,7 +406,7 @@ def test_reward_in_range(multi_run_result: dict[str, ProcessResult], output_dir:
|
||||
with open(log_file, "r") as f:
|
||||
lines = strip_escape_codes(f.read()).splitlines()
|
||||
if name in ["beta", "gamma"]:
|
||||
check_reward_in_range(lines, step=7, min_threshold=0.2, max_threshold=0.6)
|
||||
check_reward_in_range(lines, step=7, min_threshold=0.2)
|
||||
check_reward_in_range(lines, min_threshold=0.65)
|
||||
elif name in ["alpha_resume", "beta_resume"]:
|
||||
check_reward_in_range(lines, min_threshold=0.65)
|
||||
|
||||
@@ -349,7 +349,7 @@ def test_branching_equivalent_multi_step_trajectory(multi_step_trajectory_extens
|
||||
assert rollout.completion_ids == [3, 4]
|
||||
assert rollout.completion_mask == [True, True]
|
||||
assert rollout.completion_logprobs == [-0.1, -0.2]
|
||||
assert rollout.completion_temperatures == [1.0, 1.0]
|
||||
assert rollout.completion_temperatures == []
|
||||
|
||||
# second step
|
||||
rollout = rollouts[1]
|
||||
@@ -358,7 +358,7 @@ def test_branching_equivalent_multi_step_trajectory(multi_step_trajectory_extens
|
||||
assert rollout.completion_ids == [7, 8]
|
||||
assert rollout.completion_mask == [True, True]
|
||||
assert rollout.completion_logprobs == [-0.3, -0.4]
|
||||
assert rollout.completion_temperatures == [1.0, 1.0]
|
||||
assert rollout.completion_temperatures == []
|
||||
|
||||
|
||||
def test_branching_equivalent_multi_step_trajectory_with_tool_calls(
|
||||
@@ -376,7 +376,7 @@ def test_branching_equivalent_multi_step_trajectory_with_tool_calls(
|
||||
assert rollout.completion_ids == [3, 4]
|
||||
assert rollout.completion_mask == [True, True]
|
||||
assert rollout.completion_logprobs == [-0.1, -0.2]
|
||||
assert rollout.completion_temperatures == [1.0, 1.0]
|
||||
assert rollout.completion_temperatures == []
|
||||
|
||||
# second step
|
||||
rollout = rollouts[1]
|
||||
@@ -385,7 +385,7 @@ def test_branching_equivalent_multi_step_trajectory_with_tool_calls(
|
||||
assert rollout.completion_ids == [7, 8]
|
||||
assert rollout.completion_mask == [True, True]
|
||||
assert rollout.completion_logprobs == [-0.3, -0.4]
|
||||
assert rollout.completion_temperatures == [1.0, 1.0]
|
||||
assert rollout.completion_temperatures == []
|
||||
|
||||
|
||||
def test_interleave_rollout_single_step_trajectory(single_step_trajectory_output):
|
||||
@@ -400,7 +400,7 @@ def test_interleave_rollout_single_step_trajectory(single_step_trajectory_output
|
||||
assert rollout.completion_ids == [3, 4]
|
||||
assert rollout.completion_mask == [True, True]
|
||||
assert rollout.completion_logprobs == [-0.1, -0.2]
|
||||
assert rollout.completion_temperatures == [1.0, 1.0]
|
||||
assert rollout.completion_temperatures == []
|
||||
assert rollout.env_name == "test-env"
|
||||
|
||||
|
||||
@@ -415,8 +415,8 @@ def test_interleave_rollout_multi_step_trajectory(multi_step_trajectory_output):
|
||||
assert rollout.completion_ids == [3, 4, 5, 6, 7, 8]
|
||||
assert rollout.completion_mask == [True, True, False, False, True, True]
|
||||
assert rollout.completion_logprobs == [-0.1, -0.2, 0, 0, -0.3, -0.4]
|
||||
# Temperatures: 2 completion tokens at temp 1.0, then 2 prompt tokens at temp 1.0, then 2 completion tokens at temp 1.0
|
||||
assert rollout.completion_temperatures == [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
|
||||
# ``completion_temperatures`` is filled by the orchestrator post-interleave; empty here.
|
||||
assert rollout.completion_temperatures == []
|
||||
|
||||
|
||||
def test_interleave_rollout_multi_step_trajectory_with_tool_calls(multi_step_trajectory_with_tool_calls_output):
|
||||
@@ -430,8 +430,8 @@ def test_interleave_rollout_multi_step_trajectory_with_tool_calls(multi_step_tra
|
||||
assert rollout.completion_ids == [3, 4, 5, 6, 7, 8]
|
||||
assert rollout.completion_mask == [True, True, False, False, True, True]
|
||||
assert rollout.completion_logprobs == [-0.1, -0.2, 0, 0, -0.3, -0.4]
|
||||
# Temperatures: 2 completion tokens at temp 1.0, then 2 prompt tokens at temp 1.0, then 2 completion tokens at temp 1.0
|
||||
assert rollout.completion_temperatures == [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
|
||||
# ``completion_temperatures`` is filled by the orchestrator post-interleave; empty here.
|
||||
assert rollout.completion_temperatures == []
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -952,9 +952,9 @@ def test_interleave_rollout_error_masks_all_false():
|
||||
# Extension holds so tokens merge, but ALL completion_mask should be False
|
||||
assert rollout.completion_ids == [3, 4, 5, 6, 7, 8]
|
||||
assert rollout.completion_mask == [False, False, False, False, False, False]
|
||||
# Logprobs and temperatures still present
|
||||
# Logprobs preserved; ``completion_temperatures`` is filled by the orchestrator post-interleave.
|
||||
assert rollout.completion_logprobs == [-0.1, -0.2, 0.0, 0.0, -0.3, -0.4]
|
||||
assert rollout.completion_temperatures == [0.8] * 6
|
||||
assert rollout.completion_temperatures == []
|
||||
|
||||
|
||||
def test_align_routed_experts_none():
|
||||
|
||||
@@ -26,9 +26,8 @@ CONFIG_CLASSES = [
|
||||
|
||||
|
||||
def get_config_files() -> list[Path]:
|
||||
"""Any TOML file inside `configs/` or `examples/` (skips the configs/private/ submodule)."""
|
||||
private = Path("configs/private")
|
||||
config_files = [p for p in Path("configs").rglob("*.toml") if private not in p.parents]
|
||||
"""Any TOML file inside `configs/` or `examples/`."""
|
||||
config_files = list(Path("configs").rglob("*.toml"))
|
||||
example_files = list(Path("examples").rglob("*.toml"))
|
||||
|
||||
return config_files + example_files
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_utils import (
|
||||
per_block_cast_to_fp8_tp_triton,
|
||||
per_block_cast_to_fp8_triton,
|
||||
per_token_cast_to_fp8_tp_triton,
|
||||
per_token_cast_to_fp8_triton,
|
||||
)
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.gpu,
|
||||
pytest.mark.skipif(
|
||||
not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] < 9,
|
||||
reason="block-fp8 cast kernels use Triton fp8e4nv (e4m3), only supported on Hopper (SM90) and newer",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rows,cols", [(256, 256), (256, 512), (512, 256), (1024, 768), (384, 128)])
|
||||
def test_block_tp_cast_matches_materialized_transpose(rows, cols):
|
||||
"""The fused transpose+cast is *bit-identical* to unfused."""
|
||||
torch.manual_seed(rows + cols)
|
||||
x = torch.randn(rows, cols, device="cuda", dtype=torch.bfloat16) * 0.3
|
||||
|
||||
ref_q, ref_s = per_block_cast_to_fp8_triton(x.transpose(0, 1).contiguous(), False)
|
||||
tp_q, tp_s = per_block_cast_to_fp8_tp_triton(x, False)
|
||||
|
||||
assert tp_q.shape == ref_q.shape == (cols, rows)
|
||||
assert tp_s.shape == ref_s.shape
|
||||
assert tp_q.is_contiguous()
|
||||
assert torch.equal(tp_q.view(torch.uint8), ref_q.view(torch.uint8))
|
||||
assert torch.equal(tp_s, ref_s)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rows,cols", [(256, 512), (512, 256), (128, 1024), (1024, 768), (384, 512)])
|
||||
def test_token_tp_cast_matches_materialized_transpose(rows, cols):
|
||||
"""The fused transpose+cast is *bit-identical* to unfused."""
|
||||
torch.manual_seed(rows + cols)
|
||||
x = torch.randn(rows, cols, device="cuda", dtype=torch.bfloat16) * 0.3
|
||||
|
||||
ref_q, ref_s = per_token_cast_to_fp8_triton(x.transpose(0, 1).contiguous(), False)
|
||||
tp_q, tp_s = per_token_cast_to_fp8_tp_triton(x, False)
|
||||
|
||||
assert tp_q.shape == ref_q.shape == (cols, rows)
|
||||
assert tp_s.shape == ref_s.shape
|
||||
assert tp_q.is_contiguous()
|
||||
assert torch.equal(tp_q.view(torch.uint8), ref_q.view(torch.uint8))
|
||||
assert torch.equal(tp_s, ref_s)
|
||||
Reference in New Issue
Block a user