Compare commits
58
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f04c8d988c | ||
|
|
4d361adacc | ||
|
|
7f77713886 | ||
|
|
efeddae6bb | ||
|
|
8dfe8734e3 | ||
|
|
fa21395a68 | ||
|
|
b5daec1cbb | ||
|
|
b452660025 | ||
|
|
060f25bb3a | ||
|
|
77af037537 | ||
|
|
9281c5589a | ||
|
|
9dbb523933 | ||
|
|
5789850d4d | ||
|
|
146fcd0136 | ||
|
|
b0612a0e1f | ||
|
|
c0a026c0d4 | ||
|
|
7c9c1308dc | ||
|
|
941019f2e3 | ||
|
|
9e1f0521e3 | ||
|
|
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 |
+3
-2
@@ -23,7 +23,8 @@ configs/endpoints.py
|
||||
final_summary.json
|
||||
.pydantic_config
|
||||
.chroma_db
|
||||
|
||||
deps/nixl_*
|
||||
nixl_workspace/*
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
@@ -202,4 +203,4 @@ debug_I2_zero_band
|
||||
|
||||
outputs/
|
||||
|
||||
third_party/
|
||||
third_party/
|
||||
|
||||
@@ -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,9 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`orchestrator.advantage` length-penalty overhaul + length-weighted baseline**: `length_penalty` is now a single shape — a linear penalty that subtracts `coef * pass_rate * (model completion tokens / orchestrator.seq_len)` from each reward before the baseline subtraction (`pass_rate` = group mean reward, so solved-often problems get the strongest concision pressure and never-solved groups get none), with an optional `gate_by_correctness` flag (default `false`) that restricts the penalty to correct rollouts (`reward == 1`). The previous discriminated `type = "tokens" | "turns"` efficiency-shaping variants and the per-penalty `max_length` field have been removed — configure `[orchestrator.advantage.length_penalty]` with `coef` (and optionally `gate_by_correctness`) instead; the denominator is always `orchestrator.seq_len`. Also adds `orchestrator.advantage.length_weighted_baseline` (default `false`): when enabled, the GRPO baseline is the token-length-weighted mean reward (`sum(len_i * reward_i) / sum(len_i)`) instead of the plain mean. (2026-06-03)
|
||||
- **`trainer.experimental.token_export` removed → `trainer.enable_token_export`**: `TrainerExperimentalConfig` and the `[trainer.experimental] token_export = true` setting have been removed with no migration alias. Existing trainer configs must delete the `[trainer.experimental]` block and set the new top-level trainer flag instead: `enable_token_export = true` in a trainer config file, or `trainer.enable_token_export = true` when nested under `[trainer]` in an RL config. The trainer entrypoint CLI flag is `--enable-token-export`. (2026-06-10)
|
||||
- **`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.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Trainer config for multi-run RL integration test
|
||||
max_concurrent_runs = 2
|
||||
enable_token_export = true
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
@@ -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...841f9a54df
Vendored
+1
-1
Submodule deps/verifiers updated: 43016ea6e4...78c1b3c545
+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'
|
||||
```
|
||||
|
||||
+29
-3
@@ -136,10 +136,20 @@ The default advantage is per-group reward minus per-group baseline (DR-GRPO with
|
||||
|
||||
This is intentionally simple — it does the right thing for most envs. Switch to a [custom advantage](#custom-advantage) when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …).
|
||||
|
||||
Two built-in **length penalties** can be layered on top of any advantage to discourage rambling:
|
||||
A **length penalty** can be layered on top of the default advantage to discourage rambling. Configured under `[orchestrator.advantage.length_penalty]`, it subtracts a `coef * pass_rate * (completion tokens / orchestrator.seq_len)` term from every reward before the baseline subtraction, where `pass_rate` is the problem's mean reward across the group. The pass-rate factor means problems the model already solves reliably get the strongest push toward concise outputs, while rarely-solved problems are barely penalized (a never-solved group, mean reward 0, gets none). Set `gate_by_correctness = true` to apply the penalty only to correct rollouts (`reward == 1`), leaving incorrect ones untouched:
|
||||
|
||||
- `[orchestrator.length_penalty] type = "tokens"` — penalizes long completions in tokens, with configurable target and slope.
|
||||
- `[orchestrator.length_penalty] type = "turns"` — penalizes long multi-turn rollouts by turn count.
|
||||
```toml
|
||||
[orchestrator.advantage.length_penalty]
|
||||
coef = 0.25 # effective penalty is coef * pass_rate * (completion_tokens / seq_len)
|
||||
gate_by_correctness = false # when true, only penalize rollouts with reward == 1
|
||||
```
|
||||
|
||||
By default the baseline is the plain group mean reward. Set `length_weighted_baseline = true` to instead use the token-length-weighted mean — `sum(len_i * reward_i) / sum(len_i)` — which centers advantages by per-token expected reward when rollouts vary a lot in length:
|
||||
|
||||
```toml
|
||||
[orchestrator.advantage]
|
||||
length_weighted_baseline = true
|
||||
```
|
||||
|
||||
|
||||
### Custom Advantage
|
||||
@@ -167,6 +177,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):
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
|
||||
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `token_export` flag) that aren't surfaced here.
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
|
||||
@@ -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,40 @@ class EvalSamplingConfig(BaseConfig):
|
||||
return data
|
||||
|
||||
|
||||
class LinearLengthPenaltyConfig(BaseConfig):
|
||||
coef: float = Field(0.25, ge=0, allow_inf_nan=False)
|
||||
"""Scale on the linear length penalty. Each reward is reduced by ``coef * pass_rate * (model completion tokens / orchestrator.seq_len)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative."""
|
||||
|
||||
gate_by_correctness: bool = False
|
||||
"""When True, scale each rollout's penalty by its reward (``penalty * reward``), so correct rollouts (``reward == 1``) are penalized and incorrect ones (``reward == 0``) are not. When False, every rollout is penalized equally."""
|
||||
|
||||
|
||||
class DefaultAdvantageConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
length_penalty: LinearLengthPenaltyConfig | None = None
|
||||
"""Length penalty applied during advantage computation. Subtracts a ``coef * pass_rate * (completion tokens / orchestrator.seq_len)`` term from each reward (``pass_rate`` = group mean reward) before the baseline subtraction, so solved-often problems get the strongest concision pressure and never-solved groups get none. None disables the penalty."""
|
||||
|
||||
length_weighted_baseline: bool = False
|
||||
"""When True, the GRPO baseline is the token-length-weighted mean reward (``sum(len_i * reward_i) / sum(len_i)``) instead of the plain group mean, centering advantages by per-token expected reward."""
|
||||
|
||||
|
||||
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 +248,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 +413,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 +513,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 +750,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 +763,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 +871,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):
|
||||
@@ -167,6 +167,9 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Training nodes per FSDP island. Auto-sets ``trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
|
||||
|
||||
orchestrator_on_inference: bool = False
|
||||
"""Run the orchestrator on the last inference node instead of trainer rank 0 (frees host RAM on the trainer node)."""
|
||||
|
||||
@property
|
||||
def total_infer_nodes(self) -> int:
|
||||
return self.num_infer_nodes * self.num_infer_replicas
|
||||
@@ -448,6 +451,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 +551,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 +586,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"
|
||||
@@ -580,16 +606,20 @@ class RLConfig(BaseConfig):
|
||||
def auto_setup_inference_client(self):
|
||||
"""Auto-configure orchestrator student client from the inference server config.
|
||||
|
||||
For all modes, sets dp_rank_count from inference DP size. For SFT mode,
|
||||
also sets base_url - rl/opd rely on the ClientConfig default
|
||||
(``["http://localhost:8000/v1"]``) which already matches the auto-launched
|
||||
student vLLM at inference.server.port = 8000.
|
||||
Direct single-node runs expose all local DP ranks behind one base URL,
|
||||
so pin logical clients with ``X-data-parallel-rank``. Multi-node SLURM
|
||||
runs expose a vllm-router URL instead; the router balances across
|
||||
per-rank backend URLs and forwards request headers, so the orchestrator
|
||||
must not inject a DP-rank header there.
|
||||
"""
|
||||
if self.inference is None:
|
||||
return self
|
||||
client = self.orchestrator.student.client
|
||||
if "dp_rank_count" not in client.model_fields_set:
|
||||
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
|
||||
if self.deployment.type == "multi_node":
|
||||
client.dp_rank_count = 1
|
||||
else:
|
||||
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
|
||||
if self.orchestrator.training_mode == "sft" and "base_url" not in client.model_fields_set:
|
||||
host = self.inference.server.host or "localhost"
|
||||
port = self.inference.server.port
|
||||
|
||||
@@ -425,6 +425,18 @@ class DefaultLossConfig(BaseConfig):
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class IPOLossConfig(BaseConfig):
|
||||
type: Literal["ipo"] = "ipo"
|
||||
ipo_threshold: float = Field(0.1, ge=0)
|
||||
"""Upper DPPO masking threshold."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
kl_tau: float = Field(1e-3, ge=0)
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class CustomLossConfig(BaseConfig):
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
@@ -435,7 +447,7 @@ class CustomLossConfig(BaseConfig):
|
||||
"""Kwargs forwarded to the loss function."""
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
@@ -490,15 +502,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class TokenExportConfig(BaseConfig):
|
||||
"""Configures per-token rollout exports from the RL trainer."""
|
||||
|
||||
|
||||
class TrainerExperimentalConfig(BaseConfig):
|
||||
token_export: TokenExportConfig | None = None
|
||||
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
|
||||
|
||||
|
||||
class TrainerConfig(BaseConfig):
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
@@ -562,7 +565,8 @@ class TrainerConfig(BaseConfig):
|
||||
max_concurrent_runs: int = Field(1, ge=1)
|
||||
"""Maximum number of concurrent runs to allow. If 1, only one run may run at a time."""
|
||||
|
||||
experimental: TrainerExperimentalConfig = TrainerExperimentalConfig()
|
||||
enable_token_export: bool = False
|
||||
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
|
||||
@@ -22,6 +22,8 @@ REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
(re.compile(r"^zai-org/GLM-"), "glm45"),
|
||||
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
|
||||
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Super"), "nemotron_v3"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Nano"), "nano_v3"),
|
||||
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
|
||||
# Only Qwen3 Thinking models reason — Instruct/base models do not.
|
||||
(re.compile(r"^Qwen/Qwen3-.*Thinking"), "deepseek_r1"),
|
||||
|
||||
@@ -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
|
||||
|
||||
+52
-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",
|
||||
@@ -85,10 +87,13 @@ envs = [
|
||||
"opencode-swe",
|
||||
"reverse-text",
|
||||
"rlm-swe",
|
||||
"rlm-search",
|
||||
"rlm-uuid-ctf",
|
||||
"science-env",
|
||||
"simpleqa-verified",
|
||||
"tau2-bench",
|
||||
"wiki-search",
|
||||
"wordle",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
@@ -127,44 +132,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 +150,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 +188,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 +199,53 @@ 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 }
|
||||
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
|
||||
rlm-uuid-ctf = { path = "deps/research-environments/environments/rlm_uuid_ctf", 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 +276,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!"
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,19 @@ PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
VENV_BIN="$PROJECT_DIR/.venv/bin"
|
||||
PYTHON="$VENV_BIN/python"
|
||||
|
||||
# UCX's --with-verbs silently disables IB/RoCE support when the rdma-core *dev*
|
||||
# headers (verbs.h / rdma_cma.h) are missing, yielding a TCP-only build. On hosts
|
||||
# with RDMA devices, require the headers up front instead of failing at runtime.
|
||||
HAVE_RDMA=0
|
||||
if compgen -G "/sys/class/infiniband/*" > /dev/null; then
|
||||
HAVE_RDMA=1
|
||||
if [ ! -f /usr/include/infiniband/verbs.h ] || [ ! -f /usr/include/rdma/rdma_cma.h ]; then
|
||||
echo "ERROR: host has RDMA devices but the rdma-core dev headers are missing." >&2
|
||||
echo "Install them first, e.g.: apt-get install -y libibverbs-dev librdmacm-dev" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
WORKSPACE="$PROJECT_DIR/nixl_workspace"
|
||||
mkdir -p "$WORKSPACE"
|
||||
UCX_SRC="$WORKSPACE/ucx_source"
|
||||
@@ -40,11 +53,23 @@ if [ ! -f "$UCX_INSTALL/lib/libucs.so" ]; then
|
||||
--enable-devel-headers \
|
||||
--enable-mt \
|
||||
--with-verbs \
|
||||
--with-rdmacm \
|
||||
--with-cuda="$CUDA_PATH" \
|
||||
--with-ze=no
|
||||
make -j"$NPROC"
|
||||
make install
|
||||
echo "=== UCX installed to $UCX_INSTALL ==="
|
||||
|
||||
# Fail loudly if the IB transports didn't make it into the build.
|
||||
if [ "$HAVE_RDMA" = 1 ]; then
|
||||
ucx_transports=$(LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:-}" \
|
||||
"$UCX_INSTALL/bin/ucx_info" -d)
|
||||
if ! grep -q "Transport: rc_verbs" <<< "$ucx_transports"; then
|
||||
echo "ERROR: UCX built without IB (rc_verbs) transport despite RDMA devices being present." >&2
|
||||
echo "Check that libibverbs-dev / librdmacm-dev were present at configure time." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
echo "=== UCX already built, skipping ==="
|
||||
fi
|
||||
|
||||
@@ -62,10 +62,10 @@ In TOML, an empty section header (`[ckpt]`) does the same.
|
||||
|
||||
## RL trainer token exports
|
||||
|
||||
For rollout debugging, enable trainer-side token export under `trainer.experimental.token_export` (or `experimental.token_export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Single-run/fallback exports go under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`; multi-run trainer exports with packer metadata go under the owning run directory, `output_dir/<run_id>/token_exports/step_<run_step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
|
||||
```toml
|
||||
[trainer.experimental.token_export]
|
||||
enable_token_export = true
|
||||
```
|
||||
|
||||
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
|
||||
@@ -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
|
||||
@@ -29,7 +27,7 @@ uv sync --group dev # + pytest, ruff, pre-commit
|
||||
uv sync --all-extras # recommended: envs, flash-attn, flash-attn-cute, etc.
|
||||
```
|
||||
|
||||
The `envs` extra installs every env workspace listed in `[tool.uv.workspace]`. Adding a new env means adding it to `members`, the `envs` extra, and `[tool.uv.sources]`.
|
||||
The `envs` extra installs environments listed under `[project.optional-dependencies].envs`, resolved through `[tool.uv.sources]`. Adding a new env means adding its package name to `envs` and its editable source path to `[tool.uv.sources]`.
|
||||
|
||||
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
|
||||
|
||||
|
||||
@@ -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,12 +380,10 @@ 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)),
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
)
|
||||
else:
|
||||
script = template.render(
|
||||
@@ -389,15 +397,16 @@ 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)),
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -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
|
||||
@@ -17,13 +17,29 @@ def transformers_v5_compat():
|
||||
|
||||
_patch_qwen35_lora()
|
||||
_patch_lora_key_prefix()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
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()
|
||||
|
||||
|
||||
def monkey_patch_nano_v3_reasoning_parser():
|
||||
from vllm.reasoning.abs_reasoning_parsers import ReasoningParserManager
|
||||
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
|
||||
|
||||
class NanoV3ReasoningParser(DeepSeekR1ReasoningParser):
|
||||
def extract_reasoning(self, model_output, request):
|
||||
reasoning_content, final_content = super().extract_reasoning(model_output, request)
|
||||
chat_template_kwargs = getattr(request, "chat_template_kwargs", None)
|
||||
|
||||
if chat_template_kwargs and chat_template_kwargs.get("enable_thinking") is False and final_content is None:
|
||||
reasoning_content, final_content = final_content, reasoning_content
|
||||
|
||||
return reasoning_content, final_content
|
||||
|
||||
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm import envs
|
||||
from vllm.config.vllm import VllmConfig
|
||||
@@ -68,36 +84,42 @@ 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.
|
||||
def monkey_patch_strip_routed_experts_from_chat():
|
||||
"""Drop routed_experts from chat-completions responses.
|
||||
|
||||
routed_experts are only consumed via the serialized ``/generate``
|
||||
(serving_tokens) path used for router-replay training, which encodes them as a
|
||||
``{data, shape, start}`` object the PD router can merge. The stock
|
||||
chat-completions path instead encodes them as a base64 ``np.save`` *string*,
|
||||
which the PD router rejects ("prefill routed_experts must be an object with
|
||||
base64 data and shape") and fails every eval rollout (evals go through chat
|
||||
completions). ``enable_return_routed_experts`` is a server-wide model-config
|
||||
flag with no per-request toggle, so strip the field on the chat path here.
|
||||
"""
|
||||
from vllm.entrypoints.openai.chat_completion.serving import OpenAIServingChat
|
||||
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))
|
||||
if getattr(OpenAIServingChat.chat_completion_full_generator, "_prime_rl_strips_routed_experts", False):
|
||||
return
|
||||
|
||||
reload_layerwise._place_kernel_tensors(layer, info)
|
||||
_original = OpenAIServingChat.chat_completion_full_generator
|
||||
|
||||
reload_layerwise._copy_and_restore_kernel_tensors = _copy_and_restore_kernel_tensors
|
||||
logger.warning("Enabled vLLM layerwise reload alias-buffer patch.")
|
||||
async def _strip(result_generator):
|
||||
async for res in result_generator:
|
||||
for output in res.outputs:
|
||||
output.routed_experts = None
|
||||
yield res
|
||||
|
||||
async def _patched(self, request, result_generator, *args, **kwargs):
|
||||
return await _original(self, request, _strip(result_generator), *args, **kwargs)
|
||||
|
||||
_patched._prime_rl_strips_routed_experts = True
|
||||
OpenAIServingChat.chat_completion_full_generator = _patched
|
||||
logger.info(
|
||||
"Stripped routed_experts from chat-completions responses (PD router merges only the /generate object form)."
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
@@ -782,87 +804,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.
|
||||
|
||||
@@ -951,3 +892,36 @@ def monkey_patch_fp32_lm_head():
|
||||
LogitsProcessor.__init__ = _patched_init
|
||||
LogitsProcessor._get_logits = _patched_get_logits
|
||||
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
|
||||
|
||||
|
||||
def monkey_patch_dp_coordinator_startup_timeout():
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 30s.
|
||||
|
||||
The coordinator child process is spawned on the DP-rank-0 API server while
|
||||
every engine-core rank on the node is importing and loading weights, so its
|
||||
own spawn-time re-import can take well over 30s under that CPU/IO
|
||||
contention (seen on multi-node disaggregated GLM-5.1 launches). Configurable
|
||||
via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT (seconds, default 300).
|
||||
"""
|
||||
import multiprocessing.connection
|
||||
import os
|
||||
|
||||
from vllm.v1.engine.coordinator import DPCoordinator
|
||||
|
||||
timeout = float(os.environ.get("PRIME_DP_COORDINATOR_STARTUP_TIMEOUT", "300"))
|
||||
|
||||
def _patched_wait_for_zmq_addrs(self, zmq_addr_pipe):
|
||||
try:
|
||||
ready = multiprocessing.connection.wait([zmq_addr_pipe, self.proc.sentinel], timeout=timeout)
|
||||
if not ready:
|
||||
raise RuntimeError(
|
||||
f"DP Coordinator process failed to report ZMQ addresses within {timeout}s during startup."
|
||||
)
|
||||
try:
|
||||
return zmq_addr_pipe.recv()
|
||||
except EOFError:
|
||||
raise RuntimeError("DP Coordinator process failed during startup.") from None
|
||||
finally:
|
||||
zmq_addr_pipe.close()
|
||||
|
||||
DPCoordinator._wait_for_zmq_addrs = _patched_wait_for_zmq_addrs
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -20,8 +20,11 @@ from prime_rl.utils.logger import get_logger
|
||||
|
||||
logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_dp_coordinator_startup_timeout,
|
||||
monkey_patch_harmony_stop_token_propagation,
|
||||
monkey_patch_load_lora_adapter,
|
||||
monkey_patch_nano_v3_reasoning_parser,
|
||||
monkey_patch_strip_routed_experts_from_chat,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
monkey_patch_vllm_padded_input_scrub,
|
||||
)
|
||||
@@ -35,9 +38,22 @@ monkey_patch_load_lora_adapter()
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
# NOTE: Register Nano V3 reasoning parser so configs can use
|
||||
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
# NOTE: Optional mitigation for vLLM padded decode inputs until the native fix
|
||||
# is available in our pinned runtime.
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
# NOTE: routed_experts are consumed only via the serialized /generate path (router
|
||||
# replay). The chat-completions path encodes them as a base64 np.save string the PD
|
||||
# router cannot merge, which fails eval rollouts (they use chat completions). Strip
|
||||
# routed_experts from chat responses since the server-wide enable flag has no
|
||||
# per-request toggle.
|
||||
monkey_patch_strip_routed_experts_from_chat()
|
||||
# NOTE: vLLM hard-codes a 30s DP coordinator startup timeout, which the rank-0
|
||||
# API server blows through when all engine-core ranks on the node are loading
|
||||
# weights concurrently (multi-node disaggregated deployments).
|
||||
monkey_patch_dp_coordinator_startup_timeout()
|
||||
|
||||
logger = init_logger("vllm.entrypoints.openai.api_server")
|
||||
|
||||
|
||||
@@ -30,12 +30,17 @@ delegates to upstream so we track future vLLM changes for free.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncGenerator
|
||||
from collections.abc import AsyncGenerator, AsyncIterable
|
||||
from functools import cached_property
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Request
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, RequestResponseMetadata
|
||||
from vllm.entrypoints.openai.engine.protocol import (
|
||||
ErrorResponse,
|
||||
PromptTokenUsageInfo,
|
||||
RequestResponseMetadata,
|
||||
UsageInfo,
|
||||
)
|
||||
from vllm.entrypoints.serve.disagg.protocol import (
|
||||
GenerateRequest,
|
||||
GenerateResponse,
|
||||
@@ -55,6 +60,12 @@ class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
|
||||
|
||||
class PrimeRlGenerateResponse(GenerateResponse):
|
||||
choices: list[PrimeRlGenerateResponseChoice]
|
||||
# Upstream ``GenerateResponse`` doesn't declare a ``usage`` field, so the
|
||||
# parent ``ServingTokens.serve_tokens_full_generator`` constructs it and
|
||||
# Pydantic silently drops it on serialization. Declare it here so the
|
||||
# router can extract per-run token counts (and cached-prefix tokens) for
|
||||
# platform billing — see https://github.com/PrimeIntellect-ai/router/pull/43.
|
||||
usage: UsageInfo | None = None
|
||||
|
||||
|
||||
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
@@ -74,6 +85,49 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
)
|
||||
|
||||
|
||||
class _FinalOutputCapture:
|
||||
"""Wraps a ``RequestOutput`` async generator to record the last yielded item.
|
||||
|
||||
Needed so the response builder can construct a ``usage`` block from
|
||||
``final_res.prompt_token_ids`` / ``output.token_ids`` / ``num_cached_tokens``
|
||||
after delegating iteration to upstream.
|
||||
"""
|
||||
|
||||
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
|
||||
# ``source`` may be any async-iterable — including
|
||||
# ``_GenerateRoutedExpertsCapture``, which exposes the protocol via
|
||||
# ``async def __aiter__`` (an async generator function) and has no
|
||||
# ``__anext__`` method. Drive it through ``async for`` rather than
|
||||
# poking ``__anext__`` directly so both shapes work.
|
||||
self._source = source
|
||||
self.final_res: RequestOutput | None = None
|
||||
|
||||
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
|
||||
async for item in self._source:
|
||||
self.final_res = item
|
||||
yield item
|
||||
|
||||
|
||||
def _build_usage(final_res: RequestOutput) -> UsageInfo:
|
||||
assert final_res.prompt_token_ids is not None
|
||||
num_prompt_tokens = len(final_res.prompt_token_ids)
|
||||
if final_res.encoder_prompt_token_ids is not None:
|
||||
num_prompt_tokens += len(final_res.encoder_prompt_token_ids)
|
||||
num_generated_tokens = sum(len(output.token_ids) for output in final_res.outputs)
|
||||
usage = UsageInfo(
|
||||
prompt_tokens=num_prompt_tokens,
|
||||
completion_tokens=num_generated_tokens,
|
||||
total_tokens=num_prompt_tokens + num_generated_tokens,
|
||||
)
|
||||
# Always emit cached tokens when vLLM reports any. Upstream gates this on
|
||||
# ``enable_prompt_tokens_details`` (default False) for OpenAI-API compat,
|
||||
# but ``/inference/v1/generate`` is prime-rl internal — the cache-discount
|
||||
# billing pipeline always wants the cached subset surfaced.
|
||||
if final_res.num_cached_tokens:
|
||||
usage.prompt_tokens_details = PromptTokenUsageInfo(cached_tokens=final_res.num_cached_tokens)
|
||||
return usage
|
||||
|
||||
|
||||
async def _client_set_max_tokens(raw_request: Request | None) -> bool:
|
||||
"""Whether the inbound JSON body carried ``sampling_params.max_tokens``.
|
||||
|
||||
@@ -273,11 +327,33 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
)
|
||||
result_generator = capture
|
||||
|
||||
# Always capture the final ``RequestOutput`` so we can attach a
|
||||
# ``usage`` block to the response. The router parses ``usage`` for
|
||||
# per-run billing metrics; without it the cache-discount counter
|
||||
# (``vllm_router_run_cached_prompt_tokens_total``) stays at zero.
|
||||
final_capture = _FinalOutputCapture(result_generator)
|
||||
result_generator = final_capture
|
||||
|
||||
response = await super().serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
)
|
||||
|
||||
if capture is not None and isinstance(response, GenerateResponse):
|
||||
if not isinstance(response, GenerateResponse):
|
||||
return response
|
||||
|
||||
if capture is not None:
|
||||
response = capture.post_process(response)
|
||||
elif not isinstance(response, PrimeRlGenerateResponse):
|
||||
# Upgrade to the prime-rl subclass so the declared ``usage`` field
|
||||
# actually surfaces in JSON (the parent class would drop it).
|
||||
response = PrimeRlGenerateResponse(
|
||||
request_id=response.request_id,
|
||||
choices=[PrimeRlGenerateResponseChoice(**choice.model_dump()) for choice in response.choices],
|
||||
prompt_logprobs=response.prompt_logprobs,
|
||||
kv_transfer_params=response.kv_transfer_params,
|
||||
)
|
||||
|
||||
if final_capture.final_res is not None:
|
||||
response.usage = _build_usage(final_capture.final_res)
|
||||
|
||||
return response
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -5,8 +5,6 @@ from typing import TYPE_CHECKING, Callable
|
||||
|
||||
import torch
|
||||
import verifiers as vf
|
||||
from jaxtyping import Float
|
||||
from torch import Tensor
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import TrainRollout
|
||||
@@ -14,11 +12,9 @@ if TYPE_CHECKING:
|
||||
from prime_rl.configs.orchestrator import (
|
||||
AdvantageConfig,
|
||||
CustomAdvantageConfig,
|
||||
LengthPenaltyConfig,
|
||||
TokensLengthPenaltyConfig,
|
||||
TurnsLengthPenaltyConfig,
|
||||
LinearLengthPenaltyConfig,
|
||||
)
|
||||
from prime_rl.orchestrator.utils import get_model_completion_len, get_tool_response_len
|
||||
from prime_rl.orchestrator.utils import get_model_completion_len
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -50,68 +46,36 @@ entry per rollout. `assign_advantages` calls it on one already-grouped cohort.
|
||||
|
||||
def default_advantage_fn(
|
||||
inputs: AdvantageInputs,
|
||||
length_penalty: LengthPenaltyConfig | None = None,
|
||||
length_penalty: LinearLengthPenaltyConfig | None = None,
|
||||
max_seq_len: int | None = None,
|
||||
length_weighted_baseline: bool = False,
|
||||
) -> AdvantageOutputs:
|
||||
"""Default GRPO advantage for a single group: reward minus per-group baseline.
|
||||
|
||||
`length_penalty` enables correctness-gated efficiency shaping over a per-rollout
|
||||
cost: tokens (weighted completion + tool-response) or trajectory turn count.
|
||||
``length_penalty`` subtracts ``coef * pass_rate * (completion tokens / max_seq_len)``
|
||||
from each reward (``pass_rate`` = group mean reward), optionally gated to correct
|
||||
(``reward == 1``) rollouts. ``length_weighted_baseline`` uses the token-length-weighted
|
||||
mean reward as the baseline instead of the plain mean.
|
||||
"""
|
||||
rewards = torch.tensor([r["reward"] for r in inputs.rollouts], dtype=torch.float32)
|
||||
lengths = torch.tensor([get_model_completion_len(r) for r in inputs.rollouts], dtype=rewards.dtype)
|
||||
|
||||
if isinstance(length_penalty, TokensLengthPenaltyConfig):
|
||||
w_c = length_penalty.completion_weight
|
||||
w_t = length_penalty.tool_response_weight
|
||||
costs = torch.tensor(
|
||||
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in inputs.rollouts],
|
||||
dtype=rewards.dtype,
|
||||
)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
|
||||
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
|
||||
costs = torch.tensor([len(r["trajectory"]) for r in inputs.rollouts], dtype=rewards.dtype)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
|
||||
if length_penalty is not None:
|
||||
if max_seq_len is None:
|
||||
raise ValueError("max_seq_len is required when length_penalty is enabled")
|
||||
penalty = length_penalty.coef * rewards.mean() * (lengths / max_seq_len)
|
||||
if length_penalty.gate_by_correctness:
|
||||
penalty = penalty * rewards
|
||||
rewards = rewards - penalty
|
||||
|
||||
return AdvantageOutputs(advantages=(rewards - rewards.mean()).tolist())
|
||||
if length_weighted_baseline:
|
||||
baseline = (lengths * rewards).sum() / lengths.sum()
|
||||
else:
|
||||
baseline = rewards.mean()
|
||||
return AdvantageOutputs(advantages=(rewards - baseline).tolist())
|
||||
|
||||
|
||||
def _efficiency_shaping(
|
||||
rewards: Float[Tensor, "group_size"],
|
||||
costs: Float[Tensor, "group_size"],
|
||||
) -> Float[Tensor, "group_size"]:
|
||||
"""Correctness-gated efficiency shaping with bounded advantages.
|
||||
|
||||
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
|
||||
preserving zero-mean advantages within the group. `costs` is a per-rollout cost
|
||||
(e.g., completion length in tokens or number of turns).
|
||||
|
||||
Correct rollouts get reward amplified by up to 2x based on relative efficiency.
|
||||
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
|
||||
"""
|
||||
max_reward = rewards.max()
|
||||
correct_mask = rewards >= max_reward
|
||||
num_correct = correct_mask.sum()
|
||||
|
||||
# No shaping when max reward is 0 — no correct rollouts to differentiate
|
||||
if max_reward <= 0:
|
||||
return rewards - rewards.mean()
|
||||
|
||||
# Mean cost of correct rollouts
|
||||
mean_correct_cost = (costs * correct_mask).sum() / num_correct.clamp(min=1)
|
||||
|
||||
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
|
||||
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
|
||||
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
|
||||
if mean_correct_cost <= 0:
|
||||
return rewards - rewards.mean()
|
||||
|
||||
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
|
||||
|
||||
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
|
||||
shaped_rewards = rewards * (1 + bonus * correct_mask)
|
||||
return shaped_rewards - shaped_rewards.mean()
|
||||
|
||||
|
||||
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
def setup_advantage_fn(config: AdvantageConfig, max_seq_len: int | None = None) -> AdvantageFn:
|
||||
"""Setup advantage function from config."""
|
||||
if isinstance(config, CustomAdvantageConfig):
|
||||
custom_fn = import_object(config.import_path)
|
||||
@@ -123,7 +87,12 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
return advantage_fn
|
||||
|
||||
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
|
||||
return default_advantage_fn(inputs, length_penalty=config.length_penalty)
|
||||
return default_advantage_fn(
|
||||
inputs,
|
||||
length_penalty=config.length_penalty,
|
||||
max_seq_len=max_seq_len,
|
||||
length_weighted_baseline=config.length_weighted_baseline,
|
||||
)
|
||||
|
||||
return advantage_fn
|
||||
|
||||
|
||||
@@ -11,8 +11,11 @@
|
||||
schedule next. Transitions are level-triggered (driven by the eval
|
||||
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``.
|
||||
- ``on_version_pending`` (called by the watcher before the engines pause for
|
||||
the weight update) bumps ``off_policy_steps`` on 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.
|
||||
"""
|
||||
@@ -114,7 +117,7 @@ class RolloutDispatcher:
|
||||
"""``await dispatcher.start()`` runs the dispatch loop until ``stop()``.
|
||||
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules
|
||||
rollouts under shared capacity, and emits ``FinishedRollout``\\ s to
|
||||
``out_q``. The watcher drives ``on_new_version`` for off-policy
|
||||
``out_q``. The watcher drives ``on_version_pending`` for off-policy
|
||||
cancellation; the orchestrator triggers eval epochs."""
|
||||
|
||||
def __init__(
|
||||
@@ -131,6 +134,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 +146,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
|
||||
@@ -259,35 +264,44 @@ class RolloutDispatcher:
|
||||
await safe_cancel(self.task)
|
||||
self.task = None
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
async def on_version_pending(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.
|
||||
|
||||
Runs *before* the inference engines are paused for the weight update so
|
||||
the resulting aborts are processed while the engine is still stepping —
|
||||
otherwise the orphaned KV transfers crash the decode engine on resume
|
||||
(see ``WeightWatcher.apply_policy_update``)."""
|
||||
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 on_new_version(self, step: int) -> None:
|
||||
"""No-op: the dispatcher drains in ``on_version_pending`` (pre-pause)."""
|
||||
|
||||
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 +322,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 +424,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
|
||||
@@ -592,7 +611,7 @@ class RolloutDispatcher:
|
||||
# markers for those too so the sink hits ``target_rollouts``
|
||||
#
|
||||
# ``last_meta`` can be ``None`` if the only inflight task for this
|
||||
# group completed naturally between ``on_new_version``'s snapshot
|
||||
# group completed naturally between ``on_version_pending``'s snapshot
|
||||
# and us reaching it — synthesize a stand-in from the group state
|
||||
unscheduled_cancelled = 0
|
||||
if group is not None and group.rollouts_to_schedule > 0:
|
||||
|
||||
@@ -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(
|
||||
@@ -165,9 +162,14 @@ class Env:
|
||||
class TrainEnv(Env):
|
||||
config: TrainEnvConfig
|
||||
|
||||
def __init__(self, config: TrainEnvConfig):
|
||||
def __init__(self, config: TrainEnvConfig, max_seq_len: int):
|
||||
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, max_seq_len=max_seq_len) 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)
|
||||
|
||||
@@ -385,10 +246,10 @@ class Envs(Generic[EnvT]):
|
||||
class TrainEnvs(Envs[TrainEnv]):
|
||||
"""Collection of training environments."""
|
||||
|
||||
def __init__(self, configs: Sequence[TrainEnvConfig]):
|
||||
def __init__(self, configs: Sequence[TrainEnvConfig], max_seq_len: int):
|
||||
self._envs: dict[str, TrainEnv] = {}
|
||||
for config in configs:
|
||||
env = TrainEnv(config)
|
||||
env = TrainEnv(config, max_seq_len=max_seq_len)
|
||||
self._envs[env.name] = env
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
"""MetricsBuilder: assembles the per-step W&B dict. No I/O, no side effects."""
|
||||
"""MetricsBuilder: assembles the per-step W&B dict.
|
||||
|
||||
The only I/O / state is the trainer's token-export metrics, which lag the
|
||||
orchestrator: ``build`` folds in the oldest unlogged stable step it finds on
|
||||
disk and tracks the last step logged so it never re-logs one.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,12 +12,16 @@ from typing import Any
|
||||
import pandas as pd
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.token_export_metrics import collect_next_token_export_metrics
|
||||
from prime_rl.orchestrator.types import Progress, TrainBatchMetrics, TrainRollout
|
||||
|
||||
|
||||
class MetricsBuilder:
|
||||
def __init__(self, config: OrchestratorConfig) -> None:
|
||||
def __init__(self, config: OrchestratorConfig, start_step: int = 0) -> None:
|
||||
self.config = config
|
||||
# Token exports are read back one step behind the orchestrator; track the
|
||||
# last run step whose metrics we've folded in so we never re-log a step.
|
||||
self._last_token_export_step_logged = start_step - 1
|
||||
|
||||
def build(
|
||||
self,
|
||||
@@ -179,8 +188,29 @@ class MetricsBuilder:
|
||||
for name, count in pre_filter_dropped_by_name.items():
|
||||
to_log[f"pre_filters/all/{name}/rate"] = count / pre_filter_seen
|
||||
|
||||
# Fold in the trainer's token-export metrics for the oldest unlogged stable
|
||||
# step (exports always lag the orchestrator, so this is a past step).
|
||||
to_log.update(self.next_token_export_metrics())
|
||||
|
||||
return to_log
|
||||
|
||||
@property
|
||||
def last_token_export_step_logged(self) -> int:
|
||||
return self._last_token_export_step_logged
|
||||
|
||||
def next_token_export_metrics(self) -> dict[str, float | int]:
|
||||
"""Log-ready token-export metrics for the next unlogged stable step (empty if
|
||||
none), advancing the cursor. They arrive under trainer/, including trainer/step
|
||||
(the run step they belong to) for plotting against a lag-corrected axis. Shared
|
||||
by build() and the orchestrator's end-of-run drain."""
|
||||
token_export = collect_next_token_export_metrics(
|
||||
self.config.output_dir,
|
||||
last_logged_step=self._last_token_export_step_logged,
|
||||
)
|
||||
if token_export:
|
||||
self._last_token_export_step_logged = token_export["trainer/step"]
|
||||
return token_export
|
||||
|
||||
@staticmethod
|
||||
def timing_df(rollouts: list[TrainRollout]) -> pd.DataFrame:
|
||||
return pd.DataFrame(
|
||||
|
||||
@@ -108,6 +108,11 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
|
||||
# resumed when the watcher advances ``policy.version``.
|
||||
TARGET_LAG = 1
|
||||
|
||||
# After max_steps, how long to wait for the trainer to finalize the trailing
|
||||
# token-export steps it hadn't flushed yet, and how often to poll for them.
|
||||
TOKEN_EXPORT_DRAIN_TIMEOUT_S = 300.0
|
||||
TOKEN_EXPORT_DRAIN_POLL_S = 2.0
|
||||
|
||||
|
||||
class Orchestrator:
|
||||
# Set in ``__init__``
|
||||
@@ -263,7 +268,7 @@ class Orchestrator:
|
||||
post_filters = setup_filters(config.post_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="post-batch")
|
||||
|
||||
get_logger().info("Loading training environments")
|
||||
self.train_envs = TrainEnvs(config.train.env)
|
||||
self.train_envs = TrainEnvs(config.train.env, max_seq_len=config.seq_len)
|
||||
if config.training_mode == "sft":
|
||||
for env in self.train_envs:
|
||||
env.sampling_args.pop("logprobs", None)
|
||||
@@ -345,13 +350,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,8 +385,9 @@ 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.metrics = MetricsBuilder(config, start_step=self.progress.step)
|
||||
self.train_sink = TrainSink(
|
||||
config,
|
||||
tokenizer=self.tokenizer,
|
||||
@@ -389,7 +396,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,
|
||||
)
|
||||
@@ -459,6 +465,7 @@ class Orchestrator:
|
||||
clean_exit = False
|
||||
try:
|
||||
await self.main_loop()
|
||||
await self._drain_token_export_metrics()
|
||||
clean_exit = True
|
||||
finally:
|
||||
elapsed = format_time(time.perf_counter() - start_time)
|
||||
@@ -499,7 +506,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)
|
||||
@@ -509,6 +516,35 @@ class Orchestrator:
|
||||
if train_batch is not None and not self.draining and not self.stopped.is_set():
|
||||
await self.finalize_train_batch(train_batch)
|
||||
|
||||
async def _drain_token_export_metrics(self) -> None:
|
||||
"""Token exports lag the orchestrator, so once the loop ends the trainer is
|
||||
still finalizing the last shipped steps and ``build`` no longer runs to pick
|
||||
them up. Poll for the remaining stable steps up to ``max_steps - 1`` and log
|
||||
each under its own ``trainer/step`` (a local W&B step axis, so the final
|
||||
checkpoint's ``progress.step`` is untouched)."""
|
||||
if self.config.max_steps is None:
|
||||
return
|
||||
if not (self.config.output_dir / "token_exports").exists():
|
||||
return # token export not enabled for this run — don't block shutdown
|
||||
target = self.config.max_steps - 1
|
||||
if self.metrics.last_token_export_step_logged >= target:
|
||||
return # build() already kept up — nothing trailing to flush
|
||||
wandb_step = self.progress.step
|
||||
deadline = time.perf_counter() + TOKEN_EXPORT_DRAIN_TIMEOUT_S
|
||||
while time.perf_counter() < deadline:
|
||||
token_export = self.metrics.next_token_export_metrics()
|
||||
if not token_export:
|
||||
await asyncio.sleep(TOKEN_EXPORT_DRAIN_POLL_S)
|
||||
continue
|
||||
self.monitor.log(token_export, step=wandb_step)
|
||||
wandb_step += 1
|
||||
if self.metrics.last_token_export_step_logged >= target:
|
||||
return
|
||||
get_logger().warning(
|
||||
f"Token-export drain timed out before step {target} "
|
||||
f"(last logged {self.metrics.last_token_export_step_logged})"
|
||||
)
|
||||
|
||||
async def finalize_train_batch(self, batch: TrainBatch) -> None:
|
||||
"""Ship one ``TrainBatch`` out to the trainer and handle the I/O
|
||||
side-effects (ckpt, save_rollouts, teacher logprobs, sender.send,
|
||||
@@ -761,7 +797,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 +806,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%}"
|
||||
)
|
||||
|
||||
@@ -832,6 +876,10 @@ class Orchestrator:
|
||||
get_logger().info("Resuming dispatcher")
|
||||
gate.set()
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""No-op: the dispatch gate is re-evaluated in ``on_new_version`` once
|
||||
the new policy version is live."""
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""``VersionObserver`` hook: the watcher just advanced ``policy.version``;
|
||||
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
TOKEN_EXPORT_METRIC_FIELDS = ("mismatch_kl", "entropy")
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Stats:
|
||||
total: float = 0.0
|
||||
count: int = 0
|
||||
maximum: float = -math.inf
|
||||
|
||||
def add(self, value: Any) -> None:
|
||||
if not isinstance(value, int | float):
|
||||
return
|
||||
value = float(value)
|
||||
if not math.isfinite(value):
|
||||
return
|
||||
self.total += value
|
||||
self.count += 1
|
||||
self.maximum = max(self.maximum, value)
|
||||
|
||||
def as_metrics(self, prefix: str) -> dict[str, float]:
|
||||
if self.count == 0:
|
||||
return {}
|
||||
return {
|
||||
f"{prefix}/mean": self.total / self.count,
|
||||
f"{prefix}/max": self.maximum,
|
||||
}
|
||||
|
||||
|
||||
def collect_next_token_export_metrics(output_dir: Path, *, last_logged_step: int) -> dict[str, float | int]:
|
||||
"""Log-ready metrics for the oldest unlogged stable step, namespaced under
|
||||
``trainer/`` and stamped with ``trainer/step`` (the run step they belong to).
|
||||
Empty when there is no new stable step."""
|
||||
stable_steps = [step for step in _stable_token_export_steps(output_dir) if step > last_logged_step]
|
||||
if not stable_steps:
|
||||
return {}
|
||||
|
||||
step = min(stable_steps)
|
||||
metrics: dict[str, float | int] = {
|
||||
f"trainer/{key}": value for key, value in collect_token_export_metrics(output_dir, step).items()
|
||||
}
|
||||
metrics["trainer/step"] = step
|
||||
return metrics
|
||||
|
||||
|
||||
def collect_token_export_metrics(output_dir: Path, step: int) -> dict[str, float | int]:
|
||||
step_dir = output_dir / "token_exports" / f"step_{step}"
|
||||
if not (step_dir / "STABLE").exists():
|
||||
return {}
|
||||
|
||||
stats_by_key: dict[str, _Stats] = {}
|
||||
sequence_count = 0
|
||||
skipped_count = 0
|
||||
|
||||
for export_file in sorted(step_dir.glob("rank_*.jsonl")):
|
||||
with export_file.open(encoding="utf-8") as file:
|
||||
for line in file:
|
||||
if not line.strip():
|
||||
continue
|
||||
# Token exports are best-effort monitoring; a malformed line or a
|
||||
# length-mismatched record shouldn't abort the orchestrator step.
|
||||
try:
|
||||
record = json.loads(line)
|
||||
values_by_field = {field: _loss_token_values(record, field) for field in TOKEN_EXPORT_METRIC_FIELDS}
|
||||
except ValueError:
|
||||
skipped_count += 1
|
||||
continue
|
||||
sequence_count += 1
|
||||
for field, values in values_by_field.items():
|
||||
for value in values:
|
||||
stats_by_key.setdefault(field, _Stats()).add(value)
|
||||
|
||||
if skipped_count:
|
||||
get_logger().warning(f"Skipped {skipped_count} malformed token-export record(s) in {step_dir}")
|
||||
|
||||
metrics: dict[str, float | int] = {}
|
||||
if sequence_count == 0:
|
||||
return metrics
|
||||
for key, stats in sorted(stats_by_key.items()):
|
||||
metrics.update(stats.as_metrics(key))
|
||||
return metrics
|
||||
|
||||
|
||||
def _stable_token_export_steps(output_dir: Path) -> list[int]:
|
||||
token_exports_dir = output_dir / "token_exports"
|
||||
if not token_exports_dir.exists():
|
||||
return []
|
||||
|
||||
steps = []
|
||||
for step_dir in token_exports_dir.glob("step_*"):
|
||||
if not (step_dir / "STABLE").exists():
|
||||
continue
|
||||
try:
|
||||
steps.append(int(step_dir.name.removeprefix("step_")))
|
||||
except ValueError:
|
||||
continue
|
||||
return sorted(steps)
|
||||
|
||||
|
||||
def _loss_token_values(record: dict[str, Any], field: str) -> list[Any]:
|
||||
loss_mask = record.get("loss_mask", [])
|
||||
values = record.get(field, [])
|
||||
if len(loss_mask) != len(values):
|
||||
raise ValueError(
|
||||
f"Token export record has mismatched loss_mask and {field} lengths: {len(loss_mask)} != {len(values)}"
|
||||
)
|
||||
return [value for value, keep in zip(values, loss_mask) if keep]
|
||||
@@ -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))
|
||||
|
||||
@@ -202,7 +202,12 @@ class EvalBatch:
|
||||
|
||||
|
||||
class VersionObserver(Protocol):
|
||||
"""Notified after each policy update; walked by the watcher after it
|
||||
mutates ``Policy``."""
|
||||
"""Notified around each policy update; walked by the watcher.
|
||||
|
||||
``on_version_pending`` fires *before* the inference engines are paused for
|
||||
the weight update; ``on_new_version`` fires *after* the new weights are live
|
||||
and ``Policy`` has been mutated."""
|
||||
|
||||
async def on_version_pending(self, step: int) -> None: ...
|
||||
|
||||
async def on_new_version(self, step: int) -> None: ...
|
||||
|
||||
@@ -92,6 +92,24 @@ class WeightWatcher:
|
||||
f"Orchestrator resumed: checkpoint {next_step} ready (after {format_time(self.last_wait_for_ckpt_time)})"
|
||||
)
|
||||
|
||||
# Drain off-policy rollouts BEFORE pausing the inference engines.
|
||||
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
|
||||
# ``_reqs_not_processed``), which is only propagated to the workers
|
||||
# while the engine is stepping. If we drain after resume instead,
|
||||
# the aborts race with the flush of KV transfers that completed
|
||||
# during the pause and trip ``assert req_id in self.requests`` in
|
||||
# the decode scheduler's ``_update_from_kv_xfer_finished`` — killing
|
||||
# the engine and cascading to every DP rank. Draining first lets the
|
||||
# aborts settle under normal stepping. ``on_new_version`` (below)
|
||||
# still runs post-update for observers that need the live version.
|
||||
for observer in self.observers:
|
||||
try:
|
||||
await observer.on_version_pending(next_step)
|
||||
except Exception as exc:
|
||||
get_logger().warning(
|
||||
f"Observer {type(observer).__name__}.on_version_pending({next_step}) raised: {exc!r}"
|
||||
)
|
||||
|
||||
get_logger().debug(f"Updating weights to step {next_step}")
|
||||
t1 = time.perf_counter()
|
||||
await self.inference.update_weights(weights_path, lora_name=self.lora_name, step=next_step)
|
||||
|
||||
@@ -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
|
||||
@@ -50,6 +51,7 @@ export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_PATH={{ config_path }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
mkdir -p $OUTPUT_DIR/logs/inference
|
||||
rm -f $OUTPUT_DIR/logs/inference/*.log
|
||||
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
|
||||
# General
|
||||
@@ -78,26 +80,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 +138,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 +170,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 +195,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 +240,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 +255,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 %}
|
||||
|
||||
@@ -63,6 +57,7 @@ export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export ORCHESTRATOR_OUTPUT_DIR={{ orchestrator_output_dir }}
|
||||
mkdir -p $OUTPUT_DIR/logs/trainer $OUTPUT_DIR/logs/inference
|
||||
rm -f $OUTPUT_DIR/logs/inference/*.log
|
||||
ln -sfn trainer/node_0.log $OUTPUT_DIR/logs/trainer.log
|
||||
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
|
||||
@@ -94,17 +89,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 +118,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 +133,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 +172,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 +217,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 +228,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 +240,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,108 +304,56 @@ 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
|
||||
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
|
||||
|
||||
if [ "$TRAIN_NODE_RANK" -eq 0 ]; then
|
||||
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.base-url $INFER_URLS"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.admin-base-url $ADMIN_URLS"
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
|
||||
fi
|
||||
{%- else %}
|
||||
TRAIN_NODE_RANK=$SLURM_PROCID
|
||||
{%- endif %}
|
||||
@@ -411,6 +380,21 @@ else
|
||||
@ $CONFIG_DIR/trainer.toml \
|
||||
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log &
|
||||
{% if num_infer_nodes > 0 %} fi{% endif %}
|
||||
{% if num_infer_nodes > 0 %}
|
||||
# Launch the orchestrator on one node. Default is trainer rank 0 (SLURM_PROCID ==
|
||||
# NUM_INFER_NODES). With orchestrator_on_inference it moves to the last inference node
|
||||
# (a decode node) to keep its rollout buffer + env workers off host-RAM-saturated
|
||||
# trainer nodes. Top-level (after the role if/else) so the wait -n teardown covers it.
|
||||
{% if orchestrator_on_inference %}ORCH_PROCID=$((NUM_INFER_NODES - 1)){% else %}ORCH_PROCID=$NUM_INFER_NODES{% endif %}
|
||||
if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.base-url $INFER_URLS"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.admin-base-url $ADMIN_URLS"
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
|
||||
fi
|
||||
{% endif %}
|
||||
|
||||
# Wait for the first background job to exit and propagate its exit code. This
|
||||
# turns background process crashes (router, orchestrator) into task failures
|
||||
@@ -426,7 +410,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 }}
|
||||
|
||||
+185
-76
@@ -1,5 +1,8 @@
|
||||
import copy
|
||||
from collections.abc import Callable, Sequence
|
||||
from dataclasses import dataclass
|
||||
|
||||
from prime_rl.trainer.utils import balanced_partition
|
||||
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingSample
|
||||
|
||||
ROUTED_EXPERTS_DTYPE_ITEMSIZE = {
|
||||
@@ -30,17 +33,6 @@ def _slice_routed_experts(routed_experts: RoutedExperts, seq_len: int) -> Routed
|
||||
)
|
||||
|
||||
|
||||
def _append_routed_experts(dst: MicroBatch, src: MicroBatch) -> None:
|
||||
dst_routed = dst.routed_experts
|
||||
src_routed = src.routed_experts
|
||||
assert dst_routed is not None
|
||||
assert src_routed is not None
|
||||
assert dst_routed.dtype == src_routed.dtype
|
||||
assert dst_routed.shape[1:] == src_routed.shape[1:]
|
||||
dst_routed.data += src_routed.data
|
||||
dst_routed.shape[0] += src_routed.shape[0]
|
||||
|
||||
|
||||
def _pad_routed_experts(micro_batch: MicroBatch, padding_size: int) -> None:
|
||||
routed_experts = micro_batch.routed_experts
|
||||
assert routed_experts is not None
|
||||
@@ -125,6 +117,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
loss_mask=loss_mask,
|
||||
position_ids=position_ids,
|
||||
inference_logprobs=inference_logprobs,
|
||||
sequence_lengths=[len(input_ids)],
|
||||
teacher_logprobs=teacher_logprobs,
|
||||
temperatures=temperatures,
|
||||
rewards=rewards,
|
||||
@@ -141,8 +134,149 @@ def _is_multimodal_sample(sample: MicroBatch) -> bool:
|
||||
return sample.mm_kwargs is not None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _MicroBatchBin:
|
||||
samples: list[tuple[int, MicroBatch]]
|
||||
length: int
|
||||
|
||||
@classmethod
|
||||
def from_sample(cls, lora_idx: int, sample: MicroBatch) -> "_MicroBatchBin":
|
||||
return cls(samples=[(lora_idx, sample)], length=len(sample.input_ids))
|
||||
|
||||
@property
|
||||
def first_sample(self) -> MicroBatch:
|
||||
return self.samples[0][1]
|
||||
|
||||
def can_add(self, sample: MicroBatch, max_seq_len: int) -> bool:
|
||||
first_sample = self.first_sample
|
||||
return (
|
||||
not _is_multimodal_sample(first_sample)
|
||||
and not _is_multimodal_sample(sample)
|
||||
and self.length + len(sample.input_ids) <= max_seq_len
|
||||
and first_sample.training_mode == sample.training_mode
|
||||
and (first_sample.routed_experts is None) == (sample.routed_experts is None)
|
||||
)
|
||||
|
||||
def add(self, lora_idx: int, sample: MicroBatch) -> None:
|
||||
self.samples.append((lora_idx, sample))
|
||||
self.length += len(sample.input_ids)
|
||||
|
||||
def workload(self, bin_cost: Callable[[Sequence[int]], int]) -> int:
|
||||
return bin_cost([len(sample.input_ids) for _, sample in self.samples])
|
||||
|
||||
def split_by_workload(self, bin_cost: Callable[[Sequence[int]], int]) -> tuple["_MicroBatchBin", "_MicroBatchBin"]:
|
||||
# Greedily place the heaviest sample on the currently lighter side (longest-processing-time).
|
||||
ranked = sorted(self.samples, key=lambda pair: -bin_cost([len(pair[1].input_ids)]))
|
||||
left: list[tuple[int, MicroBatch]] = []
|
||||
right: list[tuple[int, MicroBatch]] = []
|
||||
left_workload = right_workload = 0
|
||||
for lora_idx, sample in ranked:
|
||||
sample_workload = bin_cost([len(sample.input_ids)])
|
||||
if left_workload <= right_workload:
|
||||
left.append((lora_idx, sample))
|
||||
left_workload += sample_workload
|
||||
else:
|
||||
right.append((lora_idx, sample))
|
||||
right_workload += sample_workload
|
||||
return (
|
||||
_MicroBatchBin(left, sum(len(sample.input_ids) for _, sample in left)),
|
||||
_MicroBatchBin(right, sum(len(sample.input_ids) for _, sample in right)),
|
||||
)
|
||||
|
||||
|
||||
def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
|
||||
has_rewards = any(sample.rewards is not None for _, sample in bin_content.samples)
|
||||
has_teacher_logprobs = any(sample.teacher_logprobs is not None for _, sample in bin_content.samples)
|
||||
has_mm_token_type_ids = any(sample.mm_token_type_ids is not None for _, sample in bin_content.samples)
|
||||
|
||||
input_ids: list[int] = []
|
||||
loss_mask: list[bool] = []
|
||||
advantages: list[float] = []
|
||||
inference_logprobs: list[float] = []
|
||||
position_ids: list[int] = []
|
||||
temperatures: list[float] = []
|
||||
env_names: list[str] = []
|
||||
rewards: list[float] | None = [] if has_rewards else None
|
||||
teacher_logprobs: list[float] | None = [] if has_teacher_logprobs else None
|
||||
mm_token_type_ids: list[int] | None = [] if has_mm_token_type_ids else None
|
||||
routed_experts: RoutedExperts | None = None
|
||||
lora_num_tokens = [0] * num_loras
|
||||
|
||||
for lora_idx, sample in bin_content.samples:
|
||||
sample_len = len(sample.input_ids)
|
||||
input_ids.extend(sample.input_ids)
|
||||
loss_mask.extend(sample.loss_mask)
|
||||
advantages.extend(sample.advantages)
|
||||
inference_logprobs.extend(sample.inference_logprobs)
|
||||
position_ids.extend(sample.position_ids)
|
||||
temperatures.extend(sample.temperatures)
|
||||
env_names.extend(sample.env_names)
|
||||
if rewards is not None:
|
||||
rewards.extend(sample.rewards if sample.rewards is not None else [float("nan")] * sample_len)
|
||||
if teacher_logprobs is not None:
|
||||
teacher_logprobs.extend(
|
||||
sample.teacher_logprobs if sample.teacher_logprobs is not None else [0.0] * sample_len
|
||||
)
|
||||
if mm_token_type_ids is not None:
|
||||
mm_token_type_ids.extend(
|
||||
sample.mm_token_type_ids if sample.mm_token_type_ids is not None else [0] * sample_len
|
||||
)
|
||||
if sample.routed_experts is not None:
|
||||
if routed_experts is None:
|
||||
routed_experts = _copy_routed_experts(sample.routed_experts)
|
||||
else:
|
||||
assert routed_experts.dtype == sample.routed_experts.dtype
|
||||
assert routed_experts.shape[1:] == sample.routed_experts.shape[1:]
|
||||
routed_experts.data += sample.routed_experts.data
|
||||
routed_experts.shape[0] += sample.routed_experts.shape[0]
|
||||
lora_num_tokens[lora_idx] += sample_len
|
||||
|
||||
sequence_lengths = [len(sample.input_ids) for _, sample in bin_content.samples]
|
||||
assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids))
|
||||
first_sample = bin_content.first_sample
|
||||
|
||||
return MicroBatch(
|
||||
input_ids=input_ids,
|
||||
advantages=advantages,
|
||||
loss_mask=loss_mask,
|
||||
position_ids=position_ids,
|
||||
inference_logprobs=inference_logprobs,
|
||||
sequence_lengths=sequence_lengths,
|
||||
teacher_logprobs=teacher_logprobs,
|
||||
temperatures=temperatures,
|
||||
rewards=rewards,
|
||||
lora_num_tokens=lora_num_tokens,
|
||||
routed_experts=routed_experts,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
env_names=env_names,
|
||||
mm_kwargs=first_sample.mm_kwargs if _is_multimodal_sample(first_sample) else None,
|
||||
training_mode=first_sample.training_mode,
|
||||
)
|
||||
|
||||
|
||||
def _expand_bins_by_splitting(
|
||||
bins: list[_MicroBatchBin], target_count: int, bin_cost: Callable[[Sequence[int]], int]
|
||||
) -> None:
|
||||
while len(bins) < target_count:
|
||||
candidates = [
|
||||
(bin_content.workload(bin_cost), idx)
|
||||
for idx, bin_content in enumerate(bins)
|
||||
if len(bin_content.samples) > 1
|
||||
]
|
||||
if not candidates:
|
||||
break
|
||||
_, idx = max(candidates)
|
||||
left, right = bins[idx].split_by_workload(bin_cost)
|
||||
bins[idx] = left
|
||||
bins.append(right)
|
||||
|
||||
|
||||
def packed_samples_into_micro_bs(
|
||||
samples: list[tuple[int, MicroBatch]], max_seq_len: int, num_loras: int
|
||||
samples: list[tuple[int, MicroBatch]],
|
||||
max_seq_len: int,
|
||||
num_loras: int,
|
||||
num_train_workers: int,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
) -> list[MicroBatch]:
|
||||
"""
|
||||
Pack samples into micro_batch efficiently.
|
||||
@@ -155,63 +289,40 @@ def packed_samples_into_micro_bs(
|
||||
# Sort by (lora_idx, -length) for packing efficiency
|
||||
samples.sort(key=lambda x: (x[0], -len(x[1].input_ids)))
|
||||
|
||||
## we create bins
|
||||
micro_batches: list[MicroBatch] = []
|
||||
bins: list[_MicroBatchBin] = []
|
||||
|
||||
for idx, sample in samples:
|
||||
# Multimodal samples cannot be packed - each becomes its own micro batch
|
||||
if _is_multimodal_sample(sample):
|
||||
sample.lora_num_tokens = [0] * num_loras
|
||||
sample.lora_num_tokens[idx] = len(sample.input_ids)
|
||||
micro_batches.append(sample)
|
||||
continue
|
||||
|
||||
# Try to find a bin that can fit this sequence (only pack text-only samples)
|
||||
for bin_content in micro_batches:
|
||||
# Don't pack into multimodal micro batches
|
||||
if _is_multimodal_sample(bin_content):
|
||||
continue
|
||||
# Check if sequence fits in this bin
|
||||
if (
|
||||
len(bin_content.input_ids) + len(sample.input_ids) <= max_seq_len
|
||||
and bin_content.training_mode == sample.training_mode
|
||||
):
|
||||
existing_len = len(bin_content.input_ids)
|
||||
bin_content.input_ids.extend(sample.input_ids)
|
||||
bin_content.loss_mask.extend(sample.loss_mask)
|
||||
bin_content.advantages.extend(sample.advantages)
|
||||
if sample.rewards is not None:
|
||||
if bin_content.rewards is None:
|
||||
bin_content.rewards = [float("nan")] * existing_len
|
||||
bin_content.rewards.extend(sample.rewards)
|
||||
elif bin_content.rewards is not None:
|
||||
bin_content.rewards.extend([float("nan")] * len(sample.input_ids))
|
||||
bin_content.inference_logprobs.extend(sample.inference_logprobs)
|
||||
bin_content.temperatures.extend(sample.temperatures)
|
||||
if sample.teacher_logprobs is not None:
|
||||
if bin_content.teacher_logprobs is None:
|
||||
bin_content.teacher_logprobs = []
|
||||
bin_content.teacher_logprobs.extend(sample.teacher_logprobs)
|
||||
assert (bin_content.routed_experts is None) == (sample.routed_experts is None)
|
||||
if sample.routed_experts is not None:
|
||||
if bin_content.routed_experts is None:
|
||||
bin_content.routed_experts = _copy_routed_experts(sample.routed_experts)
|
||||
else:
|
||||
_append_routed_experts(bin_content, sample)
|
||||
if sample.mm_token_type_ids is not None:
|
||||
if bin_content.mm_token_type_ids is None:
|
||||
bin_content.mm_token_type_ids = []
|
||||
bin_content.mm_token_type_ids.extend(sample.mm_token_type_ids)
|
||||
bin_content.env_names.extend(sample.env_names)
|
||||
bin_content.position_ids.extend(sample.position_ids)
|
||||
bin_content.lora_num_tokens[idx] += len(sample.input_ids)
|
||||
for bin_content in bins:
|
||||
if bin_content.can_add(sample, max_seq_len):
|
||||
bin_content.add(idx, sample)
|
||||
break
|
||||
else:
|
||||
sample.lora_num_tokens = [0] * num_loras
|
||||
sample.lora_num_tokens[idx] = len(sample.input_ids)
|
||||
micro_batches.append(sample)
|
||||
bins.append(_MicroBatchBin.from_sample(idx, sample))
|
||||
|
||||
return micro_batches
|
||||
if num_train_workers > 1:
|
||||
target_count = max(
|
||||
((len(bins) + num_train_workers - 1) // num_train_workers) * num_train_workers,
|
||||
num_train_workers,
|
||||
)
|
||||
_expand_bins_by_splitting(bins, target_count, bin_cost)
|
||||
|
||||
return [_materialize_bin(bin_content, num_loras) for bin_content in bins]
|
||||
|
||||
|
||||
def _distribute_group(
|
||||
group: list[MicroBatch],
|
||||
num_train_workers: int,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
) -> list[list[MicroBatch]]:
|
||||
# Callers pad each group to a positive multiple of num_train_workers first.
|
||||
assert len(group) % num_train_workers == 0, "Number of micro batches is not divisible by number of data ranks"
|
||||
if not group:
|
||||
return [[] for _ in range(num_train_workers)]
|
||||
|
||||
weights = [bin_cost(micro_batch.sequence_lengths) for micro_batch in group]
|
||||
partitions = balanced_partition(weights, num_train_workers)
|
||||
return [[group[i] for i in partition] for partition in partitions]
|
||||
|
||||
|
||||
def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBatch:
|
||||
@@ -242,14 +353,16 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
|
||||
micro_batch.rewards.extend([float("nan")] * padding_size)
|
||||
micro_batch.loss_mask.extend([False] * padding_size)
|
||||
micro_batch.position_ids.extend(list(range(padding_size)))
|
||||
micro_batch.sequence_lengths.append(padding_size)
|
||||
micro_batch.inference_logprobs.extend([0.0] * padding_size)
|
||||
# Use temperature 1.0 for padding tokens (doesn't matter since loss_mask is False)
|
||||
micro_batch.temperatures.extend([1.0] * padding_size)
|
||||
if micro_batch.teacher_logprobs is not None:
|
||||
micro_batch.teacher_logprobs.extend([0.0] * padding_size)
|
||||
micro_batch.lora_num_tokens[-1] += (
|
||||
padding_size # We send padding to the last lora so that tokens have ascending lora idx
|
||||
)
|
||||
if micro_batch.lora_num_tokens is not None:
|
||||
micro_batch.lora_num_tokens[-1] += (
|
||||
padding_size # We send padding to the last lora so that tokens have ascending lora idx
|
||||
)
|
||||
if micro_batch.mm_token_type_ids is not None:
|
||||
micro_batch.mm_token_type_ids.extend([0] * padding_size)
|
||||
if micro_batch.routed_experts is not None:
|
||||
@@ -282,6 +395,7 @@ def prepare_batch(
|
||||
num_train_workers: int,
|
||||
idxs: list[int],
|
||||
num_loras: int,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
pad_to_multiple_of: int = 1,
|
||||
) -> list[list[MicroBatch]]:
|
||||
"""
|
||||
@@ -295,7 +409,7 @@ def prepare_batch(
|
||||
"""
|
||||
all_samples = [(idx, prepare_sample(rollout, seq_len)) for idx, rollout in zip(idxs, rollouts)]
|
||||
|
||||
micro_batches = packed_samples_into_micro_bs(all_samples, seq_len, num_loras)
|
||||
micro_batches = packed_samples_into_micro_bs(all_samples, seq_len, num_loras, num_train_workers, bin_cost)
|
||||
micro_batches = [pad_micro_batch(micro_batch, pad_to_multiple_of) for micro_batch in micro_batches]
|
||||
|
||||
# Separate by modality so each step index has uniform modality across all ranks
|
||||
@@ -306,15 +420,10 @@ def prepare_batch(
|
||||
mm_batches = _pad_group_for_distribution(mm_batches, num_train_workers)
|
||||
text_batches = _pad_group_for_distribution(text_batches, num_train_workers)
|
||||
|
||||
# Combine: all multimodal first, then all text-only. Since each group's length is
|
||||
# divisible by num_train_workers, the modality boundary aligns with distribution rows.
|
||||
ordered = mm_batches + text_batches
|
||||
|
||||
assert len(ordered) % num_train_workers == 0, "Number of micro batches is not divisible by number of data ranks"
|
||||
|
||||
# Distribute in strided order so each step index has the same modality across ranks
|
||||
batches_per_gpu: list[list[MicroBatch]] = [[] for _ in range(num_train_workers)]
|
||||
for i, batch in enumerate(ordered):
|
||||
batches_per_gpu[i % num_train_workers].append(batch)
|
||||
for group in (mm_batches, text_batches):
|
||||
group_batches_per_gpu = _distribute_group(group, num_train_workers, bin_cost)
|
||||
for worker_idx, worker_batches in enumerate(group_batches_per_gpu):
|
||||
batches_per_gpu[worker_idx].extend(worker_batches)
|
||||
|
||||
return batches_per_gpu
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -37,6 +37,7 @@ from prime_rl.trainer.models import (
|
||||
get_custom_vlm_cls,
|
||||
supports_custom_impl,
|
||||
)
|
||||
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import Indexer
|
||||
from prime_rl.trainer.models.layers.checkpointing import (
|
||||
get_supported_targets,
|
||||
set_selective_activation_checkpointing,
|
||||
@@ -79,7 +80,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 +100,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
|
||||
|
||||
@@ -350,6 +351,29 @@ def freeze_moe_router(model: nn.Module) -> None:
|
||||
logger.info(f"Froze {num_frozen} MoE router parameters")
|
||||
|
||||
|
||||
def freeze_sparse_indexer(model: nn.Module) -> None:
|
||||
"""Freeze DSA sparse-attention indexer parameters.
|
||||
|
||||
The indexer's `compute_sparse_indices` forward runs under `torch.no_grad()`, so its
|
||||
params never receive a gradient and cannot be trained. Left with requires_grad=True
|
||||
they stay stateless in the optimizer, which breaks strict checkpoint resume: DCP
|
||||
materializes optimizer state for every requires_grad param at load time, but the
|
||||
stateless params were never saved -> "Missing key in checkpoint state_dict". Freezing
|
||||
them keeps the saved and loaded optimizer state symmetric.
|
||||
"""
|
||||
logger = get_logger()
|
||||
num_frozen = 0
|
||||
|
||||
for module in model.modules():
|
||||
if isinstance(module, Indexer):
|
||||
for param in module.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
|
||||
if num_frozen > 0:
|
||||
logger.info(f"Froze {num_frozen} sparse indexer parameters")
|
||||
|
||||
|
||||
def apply_force_balanced_routing(model: nn.Module) -> None:
|
||||
"""Force MoE token-choice routers into round-robin assignment for fake-data smoke tests."""
|
||||
logger = get_logger()
|
||||
@@ -518,6 +542,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)
|
||||
@@ -1066,6 +1099,11 @@ def setup_model(
|
||||
if config.freeze_moe_router:
|
||||
freeze_moe_router(model)
|
||||
|
||||
# The DSA sparse-attention indexer runs its forward under torch.no_grad(), so it is
|
||||
# never trainable. Freeze it so optimizer state stays symmetric across checkpoint
|
||||
# save/resume. No-op for models without a sparse indexer.
|
||||
freeze_sparse_indexer(model)
|
||||
|
||||
if config.debug.force_balanced_routing:
|
||||
apply_force_balanced_routing(model)
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -8,6 +8,7 @@ import torch.nn as nn
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.vlm import get_final_logit_softcapping
|
||||
|
||||
FUSED_CE_IGNORE_INDEX = -100
|
||||
|
||||
@@ -299,8 +300,8 @@ def inject_prime_lm_head(
|
||||
|
||||
logger = get_logger()
|
||||
|
||||
# Check for Gemma-style softcapping - dispatch to specialized implementation
|
||||
final_logit_softcapping = getattr(model.config, "final_logit_softcapping", None)
|
||||
# Check for Gemma-style softcapping - dispatch to specialized implementation.
|
||||
final_logit_softcapping = get_final_logit_softcapping(model.config)
|
||||
if final_logit_softcapping:
|
||||
if fused_cross_entropy == "quack":
|
||||
raise ValueError(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -149,10 +149,15 @@ def _create_optimizer(
|
||||
"""Create optimizer. If lr is None, uses config.lr."""
|
||||
if lr is None:
|
||||
lr = config.lr
|
||||
# Only hand trainable params to the optimizer. Frozen params (e.g. the DSA sparse
|
||||
# indexer, which runs under no_grad) carry no optimizer state, and including them
|
||||
# breaks strict checkpoint resume (DCP materializes state for every requires_grad
|
||||
# param at load time, mismatching the saved state). Muon filters internally below.
|
||||
trainable_params = [p for _, p in named_params if p.requires_grad]
|
||||
match config.type:
|
||||
case "sgd":
|
||||
return SGD(
|
||||
params=[p for _, p in named_params],
|
||||
params=trainable_params,
|
||||
lr=lr,
|
||||
weight_decay=config.weight_decay,
|
||||
momentum=config.momentum,
|
||||
@@ -160,7 +165,7 @@ def _create_optimizer(
|
||||
)
|
||||
case "adamw":
|
||||
return AdamW(
|
||||
params=[p for _, p in named_params],
|
||||
params=trainable_params,
|
||||
lr=lr,
|
||||
weight_decay=config.weight_decay,
|
||||
betas=(config.betas1, config.betas2),
|
||||
@@ -169,7 +174,7 @@ def _create_optimizer(
|
||||
return _create_muon_optimizer(config, named_params, parallel_dims, lr)
|
||||
case "sign_sgd":
|
||||
return SignSGD(
|
||||
params=[p for _, p in named_params],
|
||||
params=trainable_params,
|
||||
lr=lr,
|
||||
weight_decay=config.weight_decay,
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from collections.abc import Callable, Sequence
|
||||
from pathlib import Path
|
||||
from typing import TypedDict
|
||||
|
||||
@@ -10,7 +11,12 @@ from prime_rl.configs.trainer import FakeDataLoaderConfig
|
||||
from prime_rl.trainer.rl.packer import BasePacker, setup_packer
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.transport import MicroBatch, MicroBatchReceiver, TransportConfig, setup_micro_batch_receiver
|
||||
from prime_rl.transport import (
|
||||
MicroBatch,
|
||||
MicroBatchReceiver,
|
||||
TransportConfig,
|
||||
setup_micro_batch_receiver,
|
||||
)
|
||||
|
||||
|
||||
class TensorMicroBatch(TypedDict):
|
||||
@@ -26,6 +32,7 @@ class TensorMicroBatch(TypedDict):
|
||||
loss_mask: Bool[Tensor, "batch seq"]
|
||||
temperatures: Float[Tensor, "batch seq"] # Per-token temperatures
|
||||
env_names: list[str]
|
||||
sequence_lengths: list[int]
|
||||
|
||||
# Batch level
|
||||
lora_num_tokens: Int[Tensor, "n_loras"]
|
||||
@@ -46,6 +53,10 @@ class TensorMicroBatch(TypedDict):
|
||||
# sft → sft loss). All samples in a micro batch share the same mode.
|
||||
training_mode: str
|
||||
|
||||
# Packer-derived metadata used for run-local debug exports.
|
||||
run_id: str | None
|
||||
run_step: int | None
|
||||
|
||||
|
||||
class FakeDataLoader:
|
||||
def __init__(self, config: FakeDataLoaderConfig, seq_len: int, dp_world_size: int):
|
||||
@@ -84,6 +95,7 @@ class FakeDataLoader:
|
||||
total_seq_len = 0
|
||||
input_ids = []
|
||||
position_ids = []
|
||||
sequence_lengths = []
|
||||
|
||||
while total_seq_len < self.seq_len:
|
||||
# Generate reasonably long documents
|
||||
@@ -91,6 +103,7 @@ class FakeDataLoader:
|
||||
if seq_len_to_generate + total_seq_len > self.seq_len:
|
||||
seq_len_to_generate = self.seq_len - total_seq_len
|
||||
total_seq_len += seq_len_to_generate
|
||||
sequence_lengths.append(seq_len_to_generate)
|
||||
tmp_input_ids = torch.randint(0, 120000, (seq_len_to_generate,), generator=generator).long()
|
||||
tmp_position_ids = torch.arange(seq_len_to_generate).long()
|
||||
|
||||
@@ -114,12 +127,15 @@ class FakeDataLoader:
|
||||
"teacher_logprobs": None,
|
||||
"temperatures": torch.ones(input_ids.shape[0]).unsqueeze(0),
|
||||
"env_names": ["fake"] * input_ids.shape[0],
|
||||
"sequence_lengths": sequence_lengths,
|
||||
"loss_mask": loss_mask.unsqueeze(0),
|
||||
"lora_num_tokens": lora_num_tokens,
|
||||
"routed_experts": None,
|
||||
"mm_kwargs": None,
|
||||
"mm_token_type_ids": None,
|
||||
"training_mode": "rl",
|
||||
"run_id": None,
|
||||
"run_step": None,
|
||||
}
|
||||
|
||||
def _get_micro_batch(self, generator: torch.Generator) -> TensorMicroBatch:
|
||||
@@ -142,12 +158,15 @@ class FakeDataLoader:
|
||||
"teacher_logprobs": None,
|
||||
"temperatures": torch.ones(self.seq_len).unsqueeze(0),
|
||||
"env_names": ["fake"] * self.seq_len,
|
||||
"sequence_lengths": [self.seq_len],
|
||||
"loss_mask": torch.ones(self.seq_len, dtype=torch.bool).unsqueeze(0),
|
||||
"lora_num_tokens": lora_num_tokens,
|
||||
"routed_experts": None,
|
||||
"mm_kwargs": None,
|
||||
"mm_token_type_ids": None,
|
||||
"training_mode": "rl",
|
||||
"run_id": None,
|
||||
"run_step": None,
|
||||
}
|
||||
|
||||
|
||||
@@ -162,6 +181,7 @@ class DataLoader:
|
||||
seq_len: int,
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
config: TransportConfig,
|
||||
):
|
||||
self.world = get_world()
|
||||
@@ -173,6 +193,7 @@ class DataLoader:
|
||||
tokenizer=tokenizer,
|
||||
transport_config=config,
|
||||
pad_to_multiple_of=pad_to_multiple_of,
|
||||
bin_cost=bin_cost,
|
||||
start_step=start_step,
|
||||
)
|
||||
|
||||
@@ -236,6 +257,7 @@ class DataLoader:
|
||||
loss_mask=torch.tensor(micro_batch.loss_mask, dtype=torch.bool).unsqueeze(0),
|
||||
temperatures=torch.tensor(micro_batch.temperatures, dtype=torch.float).unsqueeze(0),
|
||||
env_names=micro_batch.env_names,
|
||||
sequence_lengths=micro_batch.sequence_lengths,
|
||||
lora_num_tokens=torch.tensor(micro_batch.lora_num_tokens, dtype=torch.int32),
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_token_type_ids=torch.tensor(micro_batch.mm_token_type_ids, dtype=torch.long).unsqueeze(0)
|
||||
@@ -243,6 +265,8 @@ class DataLoader:
|
||||
else None,
|
||||
routed_experts=routed_experts,
|
||||
training_mode=micro_batch.training_mode,
|
||||
run_id=micro_batch.run_id,
|
||||
run_step=micro_batch.run_step,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ from beartype import beartype as typechecker
|
||||
from jaxtyping import Bool, Float, Int, jaxtyped
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, LossConfig
|
||||
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, IPOLossConfig, LossConfig
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -165,6 +165,35 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
|
||||
def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
advantages = inputs.advantages
|
||||
loss_mask = inputs.loss_mask
|
||||
|
||||
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs, inference_logprobs
|
||||
)
|
||||
|
||||
abs_probs_diff = torch.abs(torch.exp(trainer_logprobs) - torch.exp(inference_logprobs))
|
||||
|
||||
is_masked = abs_probs_diff > loss_config.ipo_threshold
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
|
||||
advantages = loss_config.adv_tau * advantages
|
||||
pg_loss = keep_mask * advantages * importance_ratio
|
||||
kl_loss = loss_mask * log_importance_ratio**2
|
||||
loss = (-pg_loss + loss_config.kl_tau * kl_loss).sum()
|
||||
|
||||
metrics = {
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
|
||||
"is_masked": _safe_mean(is_masked, loss_mask),
|
||||
}
|
||||
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
|
||||
def opd_loss_fn(inputs: LossInputs) -> LossOutputs:
|
||||
"""
|
||||
On-policy distillation loss: the default DPPO+KL math with the tau knobs
|
||||
@@ -240,7 +269,8 @@ def setup_loss_fns(loss_config: LossConfig) -> dict[str, LossFn]:
|
||||
- ``"opd"`` → ``opd_loss_fn`` (teacher KL as gradient signal, hardcoded
|
||||
DPPO + KL knobs)
|
||||
- ``"rl"`` → ``default_loss_fn(loss_config)`` for ``DefaultLossConfig``,
|
||||
or the imported function for ``CustomLossConfig``.
|
||||
``ipo_loss_fn(loss_config)`` for ``IPOLossConfig``, or the imported
|
||||
function for ``CustomLossConfig``.
|
||||
|
||||
``trainer.loss`` only affects the rl path - opd and sft are independent.
|
||||
"""
|
||||
@@ -250,6 +280,10 @@ def setup_loss_fns(loss_config: LossConfig) -> dict[str, LossFn]:
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return custom_fn(inputs, **kwargs)
|
||||
elif isinstance(loss_config, IPOLossConfig):
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return ipo_loss_fn(inputs, loss_config)
|
||||
else:
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
|
||||
@@ -4,6 +4,7 @@ import threading
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from collections import deque
|
||||
from collections.abc import Callable, Sequence
|
||||
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
@@ -32,6 +33,7 @@ class BasePacker(ABC):
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: TransportConfig,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
start_step: int = 0,
|
||||
):
|
||||
self.logger = get_logger()
|
||||
@@ -40,6 +42,7 @@ class BasePacker(ABC):
|
||||
self.seq_len = seq_len
|
||||
self.pad_to_multiple_of = pad_to_multiple_of
|
||||
self.tokenizer = tokenizer
|
||||
self.bin_cost = bin_cost
|
||||
self.receiver = setup_training_batch_receiver(config)
|
||||
shutil.rmtree(get_rollout_dir(self.multi_run_manager.output_dir), ignore_errors=True)
|
||||
self.sender: MicroBatchSender = setup_micro_batch_sender(
|
||||
@@ -84,9 +87,10 @@ class SinglePacker(BasePacker):
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: TransportConfig,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
start_step: int = 0,
|
||||
):
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, start_step)
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
|
||||
assert self.multi_run_manager.max_runs == 1, "SinglePacker only supports one run"
|
||||
|
||||
def pack(self):
|
||||
@@ -110,7 +114,14 @@ class SinglePacker(BasePacker):
|
||||
num_train_workers=self.dp_world_size,
|
||||
idxs=[0] * len(batch.examples),
|
||||
num_loras=self.multi_run_manager.max_runs,
|
||||
bin_cost=self.bin_cost,
|
||||
)
|
||||
# The receiver always stamps run_idx from used_idxs (a key of idx_2_id).
|
||||
run_id = self.multi_run_manager.idx_2_id[batch.run_idx]
|
||||
for worker_batches in micro_batch_grid:
|
||||
for micro_batch in worker_batches:
|
||||
micro_batch.run_id = run_id
|
||||
micro_batch.run_step = batch.step
|
||||
|
||||
self.sender.send(micro_batch_grid)
|
||||
|
||||
@@ -123,9 +134,10 @@ class MultiPacker(BasePacker):
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
config: TransportConfig,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
start_step: int = 0,
|
||||
):
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, start_step)
|
||||
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
|
||||
# Per-run buffer: stores (TrainingSample, step) tuples
|
||||
self.buffers: list[deque[tuple[TrainingSample, int]]] = [
|
||||
deque() for _ in range(self.multi_run_manager.max_runs)
|
||||
@@ -300,10 +312,14 @@ class MultiPacker(BasePacker):
|
||||
# Group samples by run_idx - each microbatch must contain samples from only ONE run
|
||||
# because MultiLoRAGroupedExperts (MoE) only supports one adapter per microbatch
|
||||
samples_by_run: dict[int, list[TrainingSample]] = {}
|
||||
steps_by_run: dict[int, int] = {}
|
||||
per_run_stats: dict[int, tuple[int, int]] = {}
|
||||
for run_idx, sample, step in selected_samples:
|
||||
if run_idx not in samples_by_run:
|
||||
samples_by_run[run_idx] = []
|
||||
steps_by_run[run_idx] = step
|
||||
else:
|
||||
assert steps_by_run[run_idx] == step, "Micro batches for a run must come from a single run step"
|
||||
samples_by_run[run_idx].append(sample)
|
||||
|
||||
num_tokens = len(sample.prompt_ids) + len(sample.completion_ids)
|
||||
@@ -327,9 +343,15 @@ class MultiPacker(BasePacker):
|
||||
num_train_workers=self.dp_world_size,
|
||||
idxs=[run_idx] * len(run_samples),
|
||||
num_loras=self.multi_run_manager.max_runs,
|
||||
bin_cost=self.bin_cost,
|
||||
)
|
||||
run_id = self.multi_run_manager.idx_2_id[run_idx]
|
||||
run_step = steps_by_run[run_idx]
|
||||
# Merge into combined grid
|
||||
for worker_idx, worker_batches in enumerate(run_micro_batch_grid):
|
||||
for micro_batch in worker_batches:
|
||||
micro_batch.run_id = run_id
|
||||
micro_batch.run_step = run_step
|
||||
all_micro_batches[worker_idx].extend(worker_batches)
|
||||
|
||||
self.sender.send(all_micro_batches)
|
||||
@@ -341,10 +363,15 @@ def setup_packer(
|
||||
pad_to_multiple_of: int,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
transport_config: TransportConfig,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
start_step: int = 0,
|
||||
) -> BasePacker:
|
||||
multi_run_manager = get_multi_run_manager()
|
||||
if multi_run_manager.max_runs == 1:
|
||||
return SinglePacker(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, start_step)
|
||||
return SinglePacker(
|
||||
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
|
||||
)
|
||||
else:
|
||||
return MultiPacker(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, start_step)
|
||||
return MultiPacker(
|
||||
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
|
||||
)
|
||||
|
||||
@@ -18,6 +18,9 @@ class DisabledTokenExporter:
|
||||
def export(self, *args: Any, **kwargs: Any) -> None:
|
||||
return
|
||||
|
||||
def mark_stable(self, ready_run_ids: set[str] | None = None) -> None:
|
||||
return
|
||||
|
||||
def close(self) -> None:
|
||||
return
|
||||
|
||||
@@ -30,10 +33,10 @@ class TokenExporter:
|
||||
) -> None:
|
||||
self.rank = rank
|
||||
self.output_dir = output_dir / "token_exports"
|
||||
self._file: Any | None = None
|
||||
self._closed = False
|
||||
self._current_step: int | None = None
|
||||
self._sequences_this_step = 0
|
||||
self._initialized_files: set[tuple[str | None, int, int]] = set()
|
||||
self._sequences_by_file: dict[tuple[str | None, int, int], int] = {}
|
||||
self._pending_stable_dirs: dict[str | None, set[Path]] = {}
|
||||
atexit.register(self.close)
|
||||
|
||||
def export(
|
||||
@@ -42,17 +45,17 @@ class TokenExporter:
|
||||
micro_step: int,
|
||||
micro_batch: Mapping[str, Any],
|
||||
model_output: Mapping[str, Tensor],
|
||||
response_lengths: list[int],
|
||||
sequence_lengths: list[int],
|
||||
loss_config: Any,
|
||||
) -> None:
|
||||
if self._current_step != step:
|
||||
self._start_step(step)
|
||||
|
||||
columns = _export_columns(micro_batch, model_output, loss_config)
|
||||
_check_lengths(columns)
|
||||
run_id = micro_batch.get("run_id")
|
||||
export_step = micro_batch.get("run_step") if micro_batch.get("run_step") is not None else step
|
||||
file_key = (run_id, export_step, self.rank)
|
||||
|
||||
start = 0
|
||||
for micro_sequence_idx, length in enumerate(response_lengths):
|
||||
for micro_sequence_idx, length in enumerate(sequence_lengths):
|
||||
raw_end = start + length
|
||||
end = _trim_padding(columns, start, raw_end)
|
||||
if end > start and any(columns["loss_mask"][start:end]):
|
||||
@@ -60,54 +63,73 @@ class TokenExporter:
|
||||
{
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"step": step,
|
||||
"export_step": export_step,
|
||||
"rank": self.rank,
|
||||
"micro_step": micro_step,
|
||||
"micro_sequence_idx": micro_sequence_idx,
|
||||
"export_sequence_idx": self._sequences_this_step,
|
||||
"export_sequence_idx": self._sequences_by_file.get(file_key, 0),
|
||||
"run_id": run_id,
|
||||
"env_name": _first_non_empty(columns["env_names"][start:end]),
|
||||
"training_mode": str(micro_batch["training_mode"]),
|
||||
**_slice_columns(columns, start, end),
|
||||
}
|
||||
},
|
||||
run_id,
|
||||
export_step,
|
||||
)
|
||||
self._sequences_this_step += 1
|
||||
self._sequences_by_file[file_key] = self._sequences_by_file.get(file_key, 0) + 1
|
||||
start = raw_end
|
||||
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._file = None
|
||||
|
||||
def _start_step(self, step: int) -> None:
|
||||
def mark_stable(self, ready_run_ids: set[str] | None = None) -> None:
|
||||
# A single run step's sequences can span multiple trainer steps (the packer
|
||||
# splits a run step across packs when it exceeds the token budget). Only
|
||||
# finalize a run's export dir once that run step is fully consumed — the same
|
||||
# `ready_to_update` signal that gates its optimizer step. ``run_id is None``
|
||||
# is single-run export, where a step never spans trainer steps, so mark it now.
|
||||
# The caller barriers first so a STABLE only lands after every rank flushed.
|
||||
ready_run_ids = ready_run_ids or set()
|
||||
for run_id in [rid for rid in self._pending_stable_dirs if rid is None or rid in ready_run_ids]:
|
||||
for stable_dir in self._pending_stable_dirs.pop(run_id):
|
||||
(stable_dir / "STABLE").touch()
|
||||
|
||||
def _export_dir(self, export_step: int, run_id: str | None) -> Path:
|
||||
if run_id is not None:
|
||||
return self.output_dir.parent / run_id / "token_exports" / f"step_{export_step}"
|
||||
return self.output_dir / f"step_{export_step}"
|
||||
|
||||
def _export_file(self, export_step: int, run_id: str | None) -> Path:
|
||||
if self._closed:
|
||||
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._current_step = step
|
||||
self._sequences_this_step = 0
|
||||
step_dir = self.output_dir / f"step_{step}"
|
||||
|
||||
step_dir = self._export_dir(export_step, run_id)
|
||||
try:
|
||||
step_dir.mkdir(parents=True, exist_ok=True)
|
||||
except FileExistsError:
|
||||
if not step_dir.is_dir():
|
||||
raise
|
||||
self._file = (step_dir / f"rank_{self.rank}.jsonl").open("w", encoding="utf-8")
|
||||
return step_dir / f"rank_{self.rank}.jsonl"
|
||||
|
||||
def _write(self, record: dict[str, Any]) -> None:
|
||||
def _write(self, record: dict[str, Any], run_id: str | None, export_step: int) -> None:
|
||||
if self._closed:
|
||||
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
|
||||
if self._file is None:
|
||||
raise RuntimeError("Token exporter has no active step file")
|
||||
self._file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
|
||||
|
||||
file_key = (run_id, export_step, self.rank)
|
||||
mode = "a" if file_key in self._initialized_files else "w"
|
||||
export_file = self._export_file(export_step, run_id)
|
||||
with export_file.open(mode, encoding="utf-8") as file:
|
||||
file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
|
||||
self._initialized_files.add(file_key)
|
||||
self._pending_stable_dirs.setdefault(run_id, set()).add(export_file.parent)
|
||||
|
||||
|
||||
def setup_token_exporter(
|
||||
config: TrainerConfig, parallel_dims: Any, world: Any, logger: Any
|
||||
) -> TokenExporter | DisabledTokenExporter:
|
||||
token_export_config = config.experimental.token_export
|
||||
if token_export_config is None:
|
||||
if not config.enable_token_export:
|
||||
return DisabledTokenExporter()
|
||||
if parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0:
|
||||
return DisabledTokenExporter()
|
||||
|
||||
@@ -46,6 +46,7 @@ from prime_rl.trainer.model import (
|
||||
from prime_rl.trainer.parallel_dims import get_parallel_dims
|
||||
from prime_rl.trainer.perf import get_perf_counter
|
||||
from prime_rl.trainer.utils import (
|
||||
build_bin_cost,
|
||||
GarbageCollection,
|
||||
MemoryProfiler,
|
||||
Tensors,
|
||||
@@ -55,7 +56,6 @@ from prime_rl.trainer.utils import (
|
||||
get_ckpt_disk_metrics,
|
||||
setup_torch_distributed,
|
||||
print_benchmark,
|
||||
get_response_lengths,
|
||||
)
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.trainer.runs import setup_multi_run_manager, Progress, get_multi_run_manager
|
||||
@@ -237,6 +237,7 @@ def train(config: TrainerConfig):
|
||||
config.model.seq_len,
|
||||
config.model.cp,
|
||||
tokenizer,
|
||||
build_bin_cost(model.config),
|
||||
config.rollout_transport,
|
||||
)
|
||||
|
||||
@@ -472,15 +473,15 @@ def train(config: TrainerConfig):
|
||||
)
|
||||
|
||||
# Compute loss
|
||||
response_lengths = get_response_lengths(position_ids)
|
||||
sequence_lengths = micro_batch["sequence_lengths"]
|
||||
loss, loss_tensors = compute_loss(
|
||||
trainer_logprobs=out["logprobs"].squeeze().split(response_lengths),
|
||||
inference_logprobs=inference_logprobs.squeeze().split(response_lengths),
|
||||
teacher_logprobs=teacher_logprobs.squeeze().split(response_lengths)
|
||||
trainer_logprobs=out["logprobs"].squeeze().split(sequence_lengths),
|
||||
inference_logprobs=inference_logprobs.squeeze().split(sequence_lengths),
|
||||
teacher_logprobs=teacher_logprobs.squeeze().split(sequence_lengths)
|
||||
if teacher_logprobs is not None
|
||||
else None,
|
||||
advantages=advantages.squeeze().split(response_lengths),
|
||||
loss_mask=loss_mask.squeeze().split(response_lengths),
|
||||
advantages=advantages.squeeze().split(sequence_lengths),
|
||||
loss_mask=loss_mask.squeeze().split(sequence_lengths),
|
||||
loss_fns=loss_fns,
|
||||
loss_scale=loss_scale,
|
||||
training_mode=micro_batch["training_mode"],
|
||||
@@ -512,7 +513,14 @@ def train(config: TrainerConfig):
|
||||
for env_name, indices in env_to_indices.items():
|
||||
tensors[f"mismatch_kl/{env_name}"].append(mismatch_kl[indices])
|
||||
|
||||
token_exporter.export(progress.step, micro_step, micro_batch, out, response_lengths, config.loss)
|
||||
token_exporter.export(
|
||||
progress.step,
|
||||
micro_step,
|
||||
micro_batch,
|
||||
out,
|
||||
sequence_lengths,
|
||||
config.loss,
|
||||
)
|
||||
|
||||
if is_tt_moe_model(model):
|
||||
load_balance_stats = get_load_balance_stats(model)
|
||||
@@ -534,6 +542,15 @@ def train(config: TrainerConfig):
|
||||
micro_step_message += f" | Routing Conf. {tensors['routing_confidence'][-1].mean().item():.4f}"
|
||||
logger.debug(micro_step_message)
|
||||
|
||||
if config.enable_token_export:
|
||||
dist.barrier()
|
||||
ready_run_ids = {
|
||||
multi_run_manager.idx_2_id[idx]
|
||||
for idx in multi_run_manager.ready_to_update_idxs
|
||||
if idx in multi_run_manager.idx_2_id
|
||||
}
|
||||
token_exporter.mark_stable(ready_run_ids)
|
||||
|
||||
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
|
||||
# across dp_cp so the final gradient is the true per-token mean over the global batch.
|
||||
for param in model.parameters():
|
||||
|
||||
@@ -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
|
||||
|
||||
+238
-37
@@ -1,10 +1,12 @@
|
||||
import gc
|
||||
import heapq
|
||||
import json
|
||||
import pickle
|
||||
import shutil
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
from collections.abc import Callable, Iterable, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -28,6 +30,241 @@ from prime_rl.utils.utils import format_num, format_time, get_step_path
|
||||
DEFAULT_TIMEOUT = timedelta(seconds=600)
|
||||
|
||||
|
||||
def _text_config(model_config: Any) -> Any:
|
||||
"""Unwrap a multimodal model's text config, else return the config unchanged."""
|
||||
return getattr(model_config, "text_config", model_config)
|
||||
|
||||
|
||||
def _is_mla(config: Any) -> bool:
|
||||
return bool(getattr(config, "multi_latent_attention", False) or hasattr(config, "q_lora_rank"))
|
||||
|
||||
|
||||
def _kv_channels(config: Any) -> int:
|
||||
return getattr(config, "kv_channels", getattr(config, "head_dim", config.hidden_size // config.num_attention_heads))
|
||||
|
||||
|
||||
def _qkv_projection_flops_per_token(config: Any) -> int:
|
||||
"""Linear-in-seqlen FLOPs of the Q/K/V projections (per token)."""
|
||||
hidden_size = config.hidden_size
|
||||
num_attention_heads = config.num_attention_heads
|
||||
kv_channels = _kv_channels(config)
|
||||
is_mla = _is_mla(config)
|
||||
qk_head_dim = getattr(config, "qk_head_dim", 0)
|
||||
qk_pos_emb_head_dim = getattr(config, "qk_pos_emb_head_dim", 0)
|
||||
|
||||
if is_mla and getattr(config, "q_lora_rank", None) is not None:
|
||||
q_flops = 2 * config.q_lora_rank * (hidden_size + num_attention_heads * (qk_head_dim + qk_pos_emb_head_dim))
|
||||
else:
|
||||
q_head_dim = (qk_head_dim + qk_pos_emb_head_dim) if is_mla else kv_channels
|
||||
q_flops = 2 * hidden_size * num_attention_heads * q_head_dim
|
||||
|
||||
if is_mla and getattr(config, "kv_lora_rank", None) is not None:
|
||||
v_head_dim = getattr(config, "v_head_dim", 0)
|
||||
kv_flops = 2 * (
|
||||
config.kv_lora_rank * (hidden_size + num_attention_heads * (qk_head_dim + v_head_dim))
|
||||
+ hidden_size * qk_pos_emb_head_dim
|
||||
)
|
||||
else:
|
||||
num_query_groups = getattr(
|
||||
config, "num_query_groups", getattr(config, "num_key_value_heads", num_attention_heads)
|
||||
)
|
||||
kv_flops = 4 * hidden_size * num_query_groups * kv_channels
|
||||
return q_flops + kv_flops
|
||||
|
||||
|
||||
def _attention_flops_per_token_squared(config: Any) -> int:
|
||||
"""Quadratic-in-seqlen FLOPs of the attention scores and values (per token^2)."""
|
||||
num_attention_heads = config.num_attention_heads
|
||||
kv_channels = _kv_channels(config)
|
||||
if _is_mla(config):
|
||||
qk_head_dim = getattr(config, "qk_head_dim", 0)
|
||||
qk_pos_emb_head_dim = getattr(config, "qk_pos_emb_head_dim", 0)
|
||||
v_head_dim = getattr(config, "v_head_dim", kv_channels)
|
||||
return num_attention_heads * (qk_head_dim + qk_pos_emb_head_dim) + num_attention_heads * v_head_dim
|
||||
return 2 * num_attention_heads * kv_channels
|
||||
|
||||
|
||||
def _ffn_flops_per_token(hidden_size: int, ffn_hidden_size: int) -> int:
|
||||
return 6 * hidden_size * ffn_hidden_size
|
||||
|
||||
|
||||
def _dense_ffn_hidden_size(config: Any) -> int:
|
||||
return getattr(
|
||||
config, "ffn_hidden_size", getattr(config, "intermediate_size", getattr(config, "moe_intermediate_size", 0))
|
||||
)
|
||||
|
||||
|
||||
def _moe_ffn_hidden_size(config: Any) -> int:
|
||||
"""Effective FFN width of an MoE layer: routed experts (topk) plus shared experts."""
|
||||
dense_ffn = _dense_ffn_hidden_size(config)
|
||||
routed_topk = getattr(config, "moe_router_topk", getattr(config, "num_experts_per_tok", 1))
|
||||
moe_ffn = getattr(config, "moe_ffn_hidden_size", getattr(config, "moe_intermediate_size", dense_ffn))
|
||||
return moe_ffn * routed_topk + (getattr(config, "moe_shared_expert_intermediate_size", None) or 0)
|
||||
|
||||
|
||||
def _count_dense_and_moe_layers(config: Any) -> tuple[int, int]:
|
||||
"""Split the model's layers into (dense, moe) counts."""
|
||||
num_experts = getattr(config, "num_experts", getattr(config, "n_routed_experts", None))
|
||||
if num_experts is None:
|
||||
return config.num_hidden_layers, 0
|
||||
|
||||
moe_layer_freq = getattr(config, "moe_layer_freq", None)
|
||||
if isinstance(moe_layer_freq, list):
|
||||
num_dense = sum(1 for freq in moe_layer_freq if freq == 0)
|
||||
num_moe = sum(1 for freq in moe_layer_freq if freq > 0)
|
||||
elif isinstance(moe_layer_freq, int):
|
||||
num_dense = sum(1 for i in range(config.num_hidden_layers) if i % moe_layer_freq != 0)
|
||||
num_moe = config.num_hidden_layers - num_dense
|
||||
elif getattr(config, "first_k_dense_replace", None) is not None:
|
||||
num_dense = config.first_k_dense_replace
|
||||
num_moe = config.num_hidden_layers - num_dense
|
||||
else:
|
||||
num_dense = 0
|
||||
num_moe = config.num_hidden_layers
|
||||
return num_dense, num_moe
|
||||
|
||||
|
||||
def _packing_cost_coeffs(config: Any) -> tuple[int, int]:
|
||||
"""Return the (linear, quadratic) coefficients of the per-sequence forward FLOPs."""
|
||||
hidden_size = config.hidden_size
|
||||
num_dense_layers, num_moe_layers = _count_dense_and_moe_layers(config)
|
||||
qkv_per_token = _qkv_projection_flops_per_token(config)
|
||||
attn_per_token_squared = _attention_flops_per_token_squared(config)
|
||||
|
||||
def layer_linear(ffn_hidden_size: int) -> int:
|
||||
return qkv_per_token + 2 * hidden_size * hidden_size + _ffn_flops_per_token(hidden_size, ffn_hidden_size)
|
||||
|
||||
linear = (
|
||||
num_dense_layers * layer_linear(_dense_ffn_hidden_size(config))
|
||||
+ num_moe_layers * layer_linear(_moe_ffn_hidden_size(config))
|
||||
+ 2 * hidden_size * config.vocab_size
|
||||
)
|
||||
quadratic = (num_dense_layers + num_moe_layers) * attn_per_token_squared
|
||||
return linear, quadratic
|
||||
|
||||
|
||||
def build_bin_cost(model_config: Any | None) -> Callable[[Sequence[int]], int]:
|
||||
"""Build a closure scoring a packed bin by estimated forward compute.
|
||||
|
||||
With ``model_config=None`` the linear/quadratic coefficients are ``(1, 0)``, so
|
||||
the cost reduces to the token count and balancing falls back to sequence length.
|
||||
"""
|
||||
if model_config is None:
|
||||
linear, quadratic = 1, 0
|
||||
else:
|
||||
linear, quadratic = _packing_cost_coeffs(_text_config(model_config))
|
||||
|
||||
def bin_cost(seqlens: Sequence[int]) -> int:
|
||||
return linear * sum(seqlens) + quadratic * sum(n * n for n in seqlens)
|
||||
|
||||
return bin_cost
|
||||
|
||||
|
||||
@dataclass
|
||||
class _WeightedSet:
|
||||
total: int = 0
|
||||
items: list[int] = field(default_factory=list)
|
||||
|
||||
def add(self, idx: int, weight: int) -> None:
|
||||
self.items.append(idx)
|
||||
self.total += weight
|
||||
|
||||
def merge(self, other: "_WeightedSet") -> None:
|
||||
self.items.extend(other.items)
|
||||
self.total += other.total
|
||||
|
||||
def __lt__(self, other: "_WeightedSet") -> bool:
|
||||
if self.total != other.total:
|
||||
return self.total < other.total
|
||||
return self.items < other.items
|
||||
|
||||
|
||||
class _KKState:
|
||||
def __init__(self, items: list[tuple[int, int]], k: int):
|
||||
self.sets = [_WeightedSet() for _ in range(k)]
|
||||
for set_idx, (idx, weight) in enumerate(items):
|
||||
self.sets[set_idx].add(idx, weight)
|
||||
self.sets.sort(reverse=True)
|
||||
|
||||
@property
|
||||
def spread(self) -> int:
|
||||
return self.sets[0].total - self.sets[-1].total
|
||||
|
||||
def merge(self, other: "_KKState") -> None:
|
||||
k = len(self.sets)
|
||||
for i in range(k):
|
||||
self.sets[i].merge(other.sets[k - 1 - i])
|
||||
self.sets.sort(reverse=True)
|
||||
|
||||
def partitions(self) -> list[list[int]]:
|
||||
return [sorted(weighted_set.items) for weighted_set in self.sets]
|
||||
|
||||
def __lt__(self, other: "_KKState") -> bool:
|
||||
if self.spread != other.spread:
|
||||
return self.spread > other.spread
|
||||
return self.sets[0] > other.sets[0]
|
||||
|
||||
|
||||
def _karmarkar_karp(weights: Sequence[int], num_partitions: int) -> list[list[int]]:
|
||||
assert len(weights) >= num_partitions
|
||||
assert len(weights) % num_partitions == 0
|
||||
weighted_indices = sorted((weight, idx) for idx, weight in enumerate(weights))
|
||||
states: list[_KKState] = []
|
||||
for offset in range(0, len(weighted_indices), num_partitions):
|
||||
items = [(idx, weight) for weight, idx in weighted_indices[offset : offset + num_partitions]]
|
||||
heapq.heappush(states, _KKState(items, num_partitions))
|
||||
|
||||
while len(states) > 1:
|
||||
state = heapq.heappop(states)
|
||||
state.merge(heapq.heappop(states))
|
||||
heapq.heappush(states, state)
|
||||
|
||||
return states[0].partitions()
|
||||
|
||||
|
||||
def _partition_loads(weights: Sequence[int], partitions: list[list[int]]) -> list[int]:
|
||||
return [sum(weights[i] for i in partition) for partition in partitions]
|
||||
|
||||
|
||||
def _refine_by_swapping(weights: Sequence[int], partitions: list[list[int]]) -> list[list[int]]:
|
||||
partitions = [list(partition) for partition in partitions]
|
||||
loads = _partition_loads(weights, partitions)
|
||||
|
||||
while True:
|
||||
best_swap = None
|
||||
best_score = (max(loads), max(loads) - min(loads))
|
||||
for left_rank in range(len(partitions)):
|
||||
for right_rank in range(left_rank + 1, len(partitions)):
|
||||
for left_pos, left_idx in enumerate(partitions[left_rank]):
|
||||
for right_pos, right_idx in enumerate(partitions[right_rank]):
|
||||
new_left = loads[left_rank] - weights[left_idx] + weights[right_idx]
|
||||
new_right = loads[right_rank] - weights[right_idx] + weights[left_idx]
|
||||
new_loads = list(loads)
|
||||
new_loads[left_rank] = new_left
|
||||
new_loads[right_rank] = new_right
|
||||
score = (max(new_loads), max(new_loads) - min(new_loads))
|
||||
if score < best_score:
|
||||
best_score = score
|
||||
best_swap = (left_rank, right_rank, left_pos, right_pos, new_loads)
|
||||
if best_swap is None:
|
||||
return partitions
|
||||
|
||||
left_rank, right_rank, left_pos, right_pos, loads = best_swap
|
||||
partitions[left_rank][left_pos], partitions[right_rank][right_pos] = (
|
||||
partitions[right_rank][right_pos],
|
||||
partitions[left_rank][left_pos],
|
||||
)
|
||||
|
||||
|
||||
def balanced_partition(weights: Sequence[int], num_partitions: int) -> list[list[int]]:
|
||||
"""Partition item indices into ``num_partitions`` groups of near-equal total weight.
|
||||
|
||||
Requires ``len(weights)`` to be a positive multiple of ``num_partitions``.
|
||||
"""
|
||||
partitions = _karmarkar_karp(weights, num_partitions)
|
||||
return _refine_by_swapping(weights, partitions)
|
||||
|
||||
|
||||
class GarbageCollection:
|
||||
"""Controls Python garbage collection to avoid stragglers in distributed training.
|
||||
|
||||
@@ -143,42 +380,6 @@ def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: b
|
||||
dist.init_process_group(backend=backend, timeout=timeout, device_id=device_id)
|
||||
|
||||
|
||||
def get_response_lengths(position_ids: torch.Tensor) -> list[int]:
|
||||
"""
|
||||
Compute lengths of concatenated sequences from position_ids.
|
||||
|
||||
Each sequence starts at 0 and increments. When position_ids resets to 0,
|
||||
it indicates the start of a new sequence. Trailing zeros (padding) are
|
||||
counted as part of the last sequence.
|
||||
|
||||
Args:
|
||||
position_ids: Tensor of shape [total_seqlen]
|
||||
|
||||
Returns:
|
||||
List of sequence lengths
|
||||
"""
|
||||
position_ids = position_ids.flatten()
|
||||
|
||||
boundaries = [0] # Start of first sequence
|
||||
|
||||
for i in range(1, len(position_ids)):
|
||||
if position_ids[i] == 0 and position_ids[i - 1] != 0:
|
||||
# This is a potential sequence boundary (0 after non-zero)
|
||||
# But only if the next element is 1 (indicating a new incrementing sequence)
|
||||
# Otherwise, this 0 is padding and belongs to current sequence
|
||||
if i + 1 < len(position_ids) and position_ids[i + 1] == 1:
|
||||
boundaries.append(i)
|
||||
|
||||
# Calculate lengths based on boundaries
|
||||
lengths = []
|
||||
for i in range(len(boundaries)):
|
||||
start = boundaries[i]
|
||||
end = boundaries[i + 1] if i + 1 < len(boundaries) else len(position_ids)
|
||||
lengths.append(end - start)
|
||||
|
||||
return lengths
|
||||
|
||||
|
||||
def print_sample(input_ids: list[int], loss_mask: list[bool], tokenizer: PreTrainedTokenizer):
|
||||
"""
|
||||
Visualize the loss mask of a tokenized sample using rich.
|
||||
|
||||
@@ -8,7 +8,12 @@ from prime_rl.transport.filesystem import (
|
||||
FileSystemTrainingBatchReceiver,
|
||||
FileSystemTrainingBatchSender,
|
||||
)
|
||||
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingBatch, TrainingSample
|
||||
from prime_rl.transport.types import (
|
||||
MicroBatch,
|
||||
RoutedExperts,
|
||||
TrainingBatch,
|
||||
TrainingSample,
|
||||
)
|
||||
from prime_rl.transport.zmq import (
|
||||
ZMQMicroBatchReceiver,
|
||||
ZMQMicroBatchSender,
|
||||
|
||||
@@ -76,6 +76,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
position_ids: list[int]
|
||||
temperatures: list[float] # Per-token temperatures used during generation
|
||||
env_names: list[str]
|
||||
sequence_lengths: list[int]
|
||||
teacher_logprobs: list[float] | None = None
|
||||
lora_num_tokens: list[int] | None = None
|
||||
routed_experts: RoutedExperts | None = None
|
||||
@@ -89,3 +90,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
# sft → sft loss). All samples packed into a micro batch share the same mode.
|
||||
training_mode: TrainingMode = "rl"
|
||||
rewards: list[float] | None = None
|
||||
|
||||
# Packer-derived metadata used for run-local token exports.
|
||||
run_id: str | None = None
|
||||
run_step: int | None = None
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -16,8 +16,8 @@ import verifiers as vf
|
||||
from prime_cli.core.config import Config as PrimeConfig
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.shared import PrimeMonitorConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor.base import Monitor, sample_items_for_logging
|
||||
|
||||
@@ -112,7 +112,7 @@ class PrimeMonitor(Monitor):
|
||||
config: PrimeMonitorConfig | None,
|
||||
output_dir: Path | None = None,
|
||||
tokenizer: PreTrainedTokenizer | None = None,
|
||||
run_config: BaseConfig | None = None,
|
||||
run_config: OrchestratorConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
):
|
||||
self.config = config
|
||||
@@ -185,7 +185,7 @@ class PrimeMonitor(Monitor):
|
||||
if config.log_extras.distributions:
|
||||
self.last_log_distributions_step = -1
|
||||
|
||||
def _register_run(self, config: PrimeMonitorConfig, run_config: BaseConfig | None) -> str | None:
|
||||
def _register_run(self, config: PrimeMonitorConfig, run_config: OrchestratorConfig | None) -> str | None:
|
||||
"""Register an external run with the platform. Returns run_id on success, None on failure."""
|
||||
prime_config = None
|
||||
team_id = config.team_id
|
||||
@@ -197,22 +197,23 @@ class PrimeMonitor(Monitor):
|
||||
if frontend_url is None:
|
||||
frontend_url = prime_config.frontend_url
|
||||
|
||||
model = getattr(run_config, "model", None) if run_config else None
|
||||
environments = getattr(run_config, "env", None) if run_config else None
|
||||
wandb = getattr(run_config, "wandb", None) if run_config else None
|
||||
|
||||
payload: dict = {
|
||||
"base_model": model.name if model else "unknown",
|
||||
"max_steps": getattr(run_config, "max_steps", None) or 0,
|
||||
payload: dict[str, Any] = {
|
||||
"base_model": run_config.student.model.name if run_config else "unknown",
|
||||
"max_steps": (run_config.max_steps if run_config else None) or 0,
|
||||
}
|
||||
if run_config:
|
||||
if run_config.batch_size is not None:
|
||||
payload["batch_size"] = run_config.batch_size
|
||||
payload["rollouts_per_example"] = run_config.group_size
|
||||
payload["seq_len"] = run_config.seq_len
|
||||
payload["environments"] = [{"id": env.id} for env in run_config.train.env]
|
||||
payload["run_config"] = run_config.model_dump(exclude_none=True, mode="json")
|
||||
if run_config.wandb:
|
||||
payload["wandb_project"] = run_config.wandb.project
|
||||
if config.run_name:
|
||||
payload["name"] = config.run_name
|
||||
if team_id:
|
||||
payload["team_id"] = team_id
|
||||
if environments:
|
||||
payload["environments"] = [{"id": env.id} for env in environments if hasattr(env, "id")]
|
||||
if wandb and getattr(wandb, "project", None):
|
||||
payload["wandb_project"] = wandb.project
|
||||
|
||||
try:
|
||||
response = httpx.post(
|
||||
|
||||
@@ -29,6 +29,7 @@ VLM_REGISTRY: dict[str, VLMModelInfo] = {
|
||||
"qwen3_5": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"qwen3_5_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"qwen3_vl_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"gemma4": VLMModelInfo(vision_encoder_attr="model.vision_tower", language_model_attr="model.language_model"),
|
||||
}
|
||||
|
||||
# Text-only default
|
||||
@@ -86,6 +87,16 @@ def is_vlm_architecture(model_config: PretrainedConfig) -> bool:
|
||||
return _get_model_info_from_config(model_config) is not None
|
||||
|
||||
|
||||
def get_final_logit_softcapping(model_config: PretrainedConfig) -> float | None:
|
||||
"""Read ``final_logit_softcapping`` from the text config.
|
||||
|
||||
For composite VLM configs (e.g. Gemma) the value lives under ``text_config``;
|
||||
``get_text_config()`` returns that for VLMs and the config itself for text-only
|
||||
models, so a plain top-level ``getattr`` would miss it and silently drop softcapping.
|
||||
"""
|
||||
return getattr(model_config.get_text_config(), "final_logit_softcapping", None)
|
||||
|
||||
|
||||
def get_layer_prefix(model_config: PretrainedConfig, override: str | None = None) -> str:
|
||||
"""Return the weight key prefix for language model layers.
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -14,12 +14,17 @@ import asyncio
|
||||
|
||||
import numpy as np
|
||||
import pybase64
|
||||
from vllm.entrypoints.openai.engine.protocol import UsageInfo
|
||||
from vllm.entrypoints.serve.disagg.protocol import GenerateResponse, GenerateResponseChoice
|
||||
|
||||
from prime_rl.inference.vllm.routed_experts import serialize_routed_experts
|
||||
from prime_rl.inference.vllm.serving_tokens import (
|
||||
PrimeRlGenerateResponse,
|
||||
PrimeRlGenerateResponseChoice,
|
||||
PrimeRlServingTokens,
|
||||
_build_usage,
|
||||
_client_set_max_tokens,
|
||||
_FinalOutputCapture,
|
||||
_GenerateRoutedExpertsCapture,
|
||||
)
|
||||
|
||||
@@ -105,6 +110,153 @@ def test_client_set_max_tokens_detects_unset():
|
||||
assert asyncio.run(_client_set_max_tokens(_FakeRawRequest(body_without_sp))) is False
|
||||
|
||||
|
||||
class _FakeOutput:
|
||||
def __init__(self, token_ids):
|
||||
self.token_ids = token_ids
|
||||
|
||||
|
||||
class _FakeRequestOutput:
|
||||
"""Minimal stand-in for ``vllm.outputs.RequestOutput``.
|
||||
|
||||
``_build_usage`` only touches four attributes; constructing a real
|
||||
``RequestOutput`` would require a full ``CompletionOutput`` graph and
|
||||
isn't worth it for a serialization-shape test.
|
||||
"""
|
||||
|
||||
def __init__(self, prompt_token_ids, output_token_ids_list, num_cached_tokens=0, encoder_prompt_token_ids=None):
|
||||
self.prompt_token_ids = prompt_token_ids
|
||||
self.encoder_prompt_token_ids = encoder_prompt_token_ids
|
||||
self.outputs = [_FakeOutput(t) for t in output_token_ids_list]
|
||||
self.num_cached_tokens = num_cached_tokens
|
||||
|
||||
|
||||
def test_prime_rl_generate_response_serializes_usage_block():
|
||||
# Regression for prime-rl PR #2408: parent ``GenerateResponse`` doesn't
|
||||
# declare ``usage``, so the field must be declared on the subclass for
|
||||
# Pydantic to emit it in JSON. Without this the router can't extract
|
||||
# per-run token / cache counts for billing.
|
||||
response = PrimeRlGenerateResponse(
|
||||
request_id="req-1",
|
||||
choices=[PrimeRlGenerateResponseChoice(index=0, token_ids=[1, 2, 3])],
|
||||
usage=UsageInfo(prompt_tokens=4, completion_tokens=3, total_tokens=7),
|
||||
)
|
||||
payload = response.model_dump(mode="json")
|
||||
assert payload["usage"] == {
|
||||
"prompt_tokens": 4,
|
||||
"completion_tokens": 3,
|
||||
"total_tokens": 7,
|
||||
"prompt_tokens_details": None,
|
||||
}
|
||||
|
||||
|
||||
def test_build_usage_sums_prompt_and_completion_tokens():
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3, 4, 5],
|
||||
output_token_ids_list=[[10, 11], [20, 21, 22]],
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens == 5
|
||||
assert usage.completion_tokens == 5 # 2 + 3
|
||||
assert usage.total_tokens == 10
|
||||
assert usage.prompt_tokens_details is None
|
||||
|
||||
|
||||
def test_build_usage_includes_encoder_prompt_tokens():
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3],
|
||||
output_token_ids_list=[[10]],
|
||||
encoder_prompt_token_ids=[100, 101],
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens == 5 # 3 + 2
|
||||
assert usage.total_tokens == 6
|
||||
|
||||
|
||||
def test_build_usage_reports_cached_tokens_unconditionally():
|
||||
# Unlike upstream's ``enable_prompt_tokens_details`` gate, prime-rl always
|
||||
# surfaces cached tokens — the cache-discount billing pipeline needs them.
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3, 4],
|
||||
output_token_ids_list=[[10, 11]],
|
||||
num_cached_tokens=3,
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens_details is not None
|
||||
assert usage.prompt_tokens_details.cached_tokens == 3
|
||||
|
||||
|
||||
def test_build_usage_skips_cached_tokens_when_zero():
|
||||
# Don't emit a details block with cached=0, which would be misleading
|
||||
# to the router's billing extractor.
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3, 4],
|
||||
output_token_ids_list=[[10, 11]],
|
||||
num_cached_tokens=0,
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens_details is None
|
||||
|
||||
|
||||
def test_final_output_capture_records_last_item():
|
||||
async def _gen():
|
||||
for r in [
|
||||
_FakeRequestOutput(prompt_token_ids=[1], output_token_ids_list=[[1]]),
|
||||
_FakeRequestOutput(prompt_token_ids=[1, 2], output_token_ids_list=[[1, 2]]),
|
||||
_FakeRequestOutput(prompt_token_ids=[1, 2, 3], output_token_ids_list=[[1, 2, 3]]),
|
||||
]:
|
||||
yield r
|
||||
|
||||
async def _drain(capture):
|
||||
async for _ in capture:
|
||||
pass
|
||||
|
||||
capture = _FinalOutputCapture(_gen())
|
||||
asyncio.run(_drain(capture))
|
||||
assert capture.final_res is not None
|
||||
assert capture.final_res.prompt_token_ids == [1, 2, 3]
|
||||
|
||||
|
||||
def test_final_output_capture_works_over_async_def_aiter_source():
|
||||
# ``_GenerateRoutedExpertsCapture`` exposes the async-iterator protocol
|
||||
# via ``async def __aiter__`` (an async generator function) and has no
|
||||
# ``__anext__``. The wrapper must drive it through ``async for`` rather
|
||||
# than poking ``__anext__`` directly, or routed-experts runs raise
|
||||
# AttributeError before the response is built.
|
||||
|
||||
class _AsyncGenAiterSource:
|
||||
def __init__(self, items):
|
||||
self._items = items
|
||||
|
||||
async def __aiter__(self):
|
||||
for item in self._items:
|
||||
yield item
|
||||
|
||||
items = [
|
||||
_FakeRequestOutput(prompt_token_ids=[1], output_token_ids_list=[[1]]),
|
||||
_FakeRequestOutput(prompt_token_ids=[1, 2], output_token_ids_list=[[1, 2]]),
|
||||
]
|
||||
capture = _FinalOutputCapture(_AsyncGenAiterSource(items))
|
||||
|
||||
async def _drain():
|
||||
async for _ in capture:
|
||||
pass
|
||||
|
||||
asyncio.run(_drain())
|
||||
assert capture.final_res is not None
|
||||
assert capture.final_res.prompt_token_ids == [1, 2]
|
||||
|
||||
|
||||
def test_final_output_capture_handles_empty_stream():
|
||||
capture = _FinalOutputCapture(_empty_request_outputs())
|
||||
|
||||
async def _drain():
|
||||
async for _ in capture:
|
||||
pass
|
||||
|
||||
asyncio.run(_drain())
|
||||
assert capture.final_res is None
|
||||
|
||||
|
||||
def test_client_set_max_tokens_assumes_set_when_body_unreadable():
|
||||
# No raw_request → can't tell, don't override.
|
||||
assert asyncio.run(_client_set_max_tokens(None)) is True
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import math
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
@@ -6,8 +5,8 @@ import pytest
|
||||
from prime_rl.configs.orchestrator import (
|
||||
CustomAdvantageConfig,
|
||||
DefaultAdvantageConfig,
|
||||
TokensLengthPenaltyConfig,
|
||||
TurnsLengthPenaltyConfig,
|
||||
LinearLengthPenaltyConfig,
|
||||
OrchestratorConfig,
|
||||
)
|
||||
from prime_rl.orchestrator.advantage import (
|
||||
AdvantageInputs,
|
||||
@@ -16,48 +15,29 @@ from prime_rl.orchestrator.advantage import (
|
||||
default_advantage_fn,
|
||||
setup_advantage_fn,
|
||||
)
|
||||
from prime_rl.orchestrator.envs import Env, TrainEnv
|
||||
from prime_rl.orchestrator.types import TrainRollout
|
||||
|
||||
|
||||
def _make_rollout(
|
||||
reward: float,
|
||||
completion_len: int = 0,
|
||||
num_turns: int = 1,
|
||||
env_name: str = "test",
|
||||
example_id: int = 0,
|
||||
) -> dict:
|
||||
"""Create a minimal rollout dict for advantage testing.
|
||||
|
||||
`completion_len` tokens are split across `num_turns` trajectory steps.
|
||||
"""
|
||||
per_turn, rem = divmod(completion_len, max(num_turns, 1))
|
||||
trajectory = [
|
||||
{"tokens": {"prompt_ids": [0], "completion_ids": list(range(per_turn + (rem if i == 0 else 0)))}}
|
||||
for i in range(num_turns)
|
||||
]
|
||||
def _make_rollout(reward: float, completion_len: int = 0) -> dict:
|
||||
"""Minimal single-turn rollout dict with ``completion_len`` completion tokens."""
|
||||
return {
|
||||
"reward": reward,
|
||||
"trajectory": trajectory,
|
||||
"env_name": env_name,
|
||||
"example_id": example_id,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(completion_len))}}],
|
||||
"env_name": "test",
|
||||
"example_id": 0,
|
||||
}
|
||||
|
||||
|
||||
def _make_group(rewards, completion_lengths=None, num_turns=None) -> AdvantageInputs:
|
||||
"""Build single-group AdvantageInputs from 1D arrays of rewards/lengths/turns."""
|
||||
def _make_group(rewards, completion_lengths=None) -> AdvantageInputs:
|
||||
"""Build single-group AdvantageInputs from 1D arrays of rewards/lengths."""
|
||||
rollouts = []
|
||||
for i, reward in enumerate(rewards):
|
||||
cl = int(completion_lengths[i]) if completion_lengths is not None else 0
|
||||
nt = int(num_turns[i]) if num_turns is not None else 1
|
||||
rollouts.append(_make_rollout(float(reward), cl, nt))
|
||||
rollouts.append(_make_rollout(float(reward), cl))
|
||||
return AdvantageInputs(rollouts=rollouts)
|
||||
|
||||
|
||||
# Helper aliases for readability — completion-only and tool-only token shaping.
|
||||
_TOKENS_COMPLETION = TokensLengthPenaltyConfig(completion_weight=1.0, tool_response_weight=0.0)
|
||||
_TOKENS_TOOL_ONLY = TokensLengthPenaltyConfig(completion_weight=0.0, tool_response_weight=1.0)
|
||||
|
||||
|
||||
def test_default_advantage_fn_simple_mean():
|
||||
inputs = _make_group(rewards=[1.0, 0.5, 0.8], completion_lengths=[10, 12, 8])
|
||||
result = default_advantage_fn(inputs)
|
||||
@@ -66,187 +46,141 @@ def test_default_advantage_fn_simple_mean():
|
||||
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_mixed_group():
|
||||
"""Mixed group: reward shaping preserves zero-mean, shorter correct gets higher advantage."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
def test_linear_length_penalty_scales_by_pass_rate():
|
||||
"""Linear penalty subtracts coef * pass_rate * (completion tokens / max_seq_len), then mean-centers.
|
||||
|
||||
# mean_correct_len = (10+30+20)/3 = 20
|
||||
# bonus = clamp(1 - [10,30,20,20]/20, 0, 1) = [0.5, 0, 0, 0]
|
||||
# shaped_rewards = R * (1 + bonus * correct_mask) = [1.5, 1, 0, 1]
|
||||
# baseline = mean(shaped_rewards) = 0.875
|
||||
# A = shaped_rewards - baseline = [0.625, 0.125, -0.875, 0.125]
|
||||
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
|
||||
``pass_rate`` is the group's mean reward, so a half-solved group scales the penalty by 0.5.
|
||||
"""
|
||||
rewards = [1.0, 1.0, 0.0, 0.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 20, 30, 40])
|
||||
result = default_advantage_fn(inputs, length_penalty=LinearLengthPenaltyConfig(coef=2.0), max_seq_len=100)
|
||||
|
||||
# Zero-mean per group
|
||||
pass_rate = sum(rewards) / len(rewards) # 0.5
|
||||
penalized = [r - 2.0 * pass_rate * (length / 100) for r, length in zip(rewards, (10, 20, 30, 40))]
|
||||
mean = sum(penalized) / len(penalized)
|
||||
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
|
||||
|
||||
# Zero-mean per group, and within each reward tier shorter output → higher advantage
|
||||
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
# All correct rollouts have positive advantage
|
||||
for rollout, adv in zip(inputs.rollouts, result.advantages):
|
||||
if rollout["reward"] >= 1.0:
|
||||
assert adv > 0
|
||||
assert result.advantages[0] > result.advantages[1]
|
||||
assert result.advantages[2] > result.advantages[3]
|
||||
|
||||
|
||||
def test_efficiency_all_correct_group():
|
||||
"""All-correct group: zero-mean, shorter gets higher advantage."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 1.0], completion_lengths=[10, 20, 40])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
|
||||
# mean_len = 70/3 ≈ 23.33
|
||||
# bonus = clamp(1 - [10, 20, 40] / (70/3), 0, 1) = [4/7, 1/7, 0]
|
||||
# shaped_rewards = [1+4/7, 1+1/7, 1] = [11/7, 8/7, 1]
|
||||
shaped = [11.0 / 7, 8.0 / 7, 1.0]
|
||||
mean_shaped = sum(shaped) / len(shaped)
|
||||
expected = [s - mean_shaped for s in shaped]
|
||||
assert result.advantages == pytest.approx(expected, abs=1e-6)
|
||||
|
||||
# Zero-mean
|
||||
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
# Shortest has highest advantage
|
||||
assert result.advantages[0] > result.advantages[1] > result.advantages[2]
|
||||
def test_linear_length_penalty_zero_pass_rate_disables_penalty():
|
||||
"""A never-solved group (mean reward 0) gets no length pressure — falls back to plain GRPO."""
|
||||
inputs = _make_group(rewards=[0.0, 0.0, 0.0], completion_lengths=[10, 50, 200])
|
||||
penalized = default_advantage_fn(inputs, length_penalty=LinearLengthPenaltyConfig(coef=5.0), max_seq_len=100)
|
||||
plain = default_advantage_fn(inputs)
|
||||
assert penalized.advantages == pytest.approx(plain.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_all_zero_rewards():
|
||||
"""When all rewards are 0, no length shaping — falls back to standard GRPO."""
|
||||
inputs = _make_group(rewards=[0.0, 0.0, 0.0], completion_lengths=[10, 20, 15])
|
||||
result_with = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
result_without = default_advantage_fn(inputs)
|
||||
def test_linear_length_penalty_gate_by_correctness():
|
||||
"""Gating scales each rollout's penalty by its reward, so reward-0 rollouts are untouched."""
|
||||
rewards = [1.0, 1.0, 0.0, 0.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 20, 30, 40])
|
||||
cfg = LinearLengthPenaltyConfig(coef=2.0, gate_by_correctness=True)
|
||||
result = default_advantage_fn(inputs, length_penalty=cfg, max_seq_len=100)
|
||||
|
||||
assert result_with.advantages == pytest.approx(result_without.advantages, abs=1e-6)
|
||||
pass_rate = sum(rewards) / len(rewards) # 0.5
|
||||
penalized = [r - r * 2.0 * pass_rate * (length / 100) for r, length in zip(rewards, (10, 20, 30, 40))]
|
||||
mean = sum(penalized) / len(penalized)
|
||||
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_single_correct():
|
||||
"""Single correct rollout: bonus=0 (at its own mean), same as standard GRPO."""
|
||||
inputs = _make_group(rewards=[1.0, 0.0, 0.0, 0.0], completion_lengths=[100, 50, 200, 150])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
def test_setup_advantage_fn_threads_max_seq_len():
|
||||
"""``setup_advantage_fn`` threads ``max_seq_len`` into the linear penalty denominator."""
|
||||
rewards = [1.0, 1.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 30])
|
||||
fn = setup_advantage_fn(DefaultAdvantageConfig(length_penalty=LinearLengthPenaltyConfig(coef=1.0)), max_seq_len=100)
|
||||
result = fn(inputs)
|
||||
|
||||
assert result.advantages == pytest.approx([0.75, -0.25, -0.25, -0.25], abs=1e-6)
|
||||
pass_rate = sum(rewards) / len(rewards) # 1.0
|
||||
penalized = [1.0 - 1.0 * pass_rate * (length / 100) for length in (10, 30)]
|
||||
mean = sum(penalized) / len(penalized)
|
||||
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_shorter_correct_higher_advantage():
|
||||
"""Among correct rollouts in a mixed group, shorter always gets higher advantage."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 1.0, 0.0, 0.0], completion_lengths=[50, 100, 200, 80, 120])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
def test_train_env_threads_max_seq_len_into_advantage_fn(monkeypatch):
|
||||
"""TrainEnv-built advantage funcs use orchestrator seq_len for length penalties."""
|
||||
|
||||
advs = result.advantages
|
||||
assert advs[0] > advs[1] > advs[2]
|
||||
assert all(a > 0 for a in advs[:3])
|
||||
assert all(a < 0 for a in advs[3:])
|
||||
def fake_env_init(self, config):
|
||||
self.config = config
|
||||
self._env = None
|
||||
self._env_client = None
|
||||
self._env_server_process = None
|
||||
|
||||
|
||||
def test_efficiency_zero_mean_per_group():
|
||||
"""Reward shaping preserves zero-mean advantages within each group."""
|
||||
mixed = default_advantage_fn(
|
||||
_make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20]),
|
||||
length_penalty=_TOKENS_COMPLETION,
|
||||
)
|
||||
all_correct = default_advantage_fn(
|
||||
_make_group(rewards=[1.0, 1.0, 1.0, 1.0], completion_lengths=[10, 20, 40, 80]),
|
||||
length_penalty=_TOKENS_COMPLETION,
|
||||
monkeypatch.setattr(Env, "__init__", fake_env_init)
|
||||
config = OrchestratorConfig(
|
||||
seq_len=100,
|
||||
advantage={"type": "default", "length_penalty": {"coef": 1.0}},
|
||||
)
|
||||
|
||||
assert sum(mixed.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
assert sum(all_correct.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
env = TrainEnv(config.train.env[0], max_seq_len=config.seq_len)
|
||||
assert env.advantage_fn is not None
|
||||
result = env.advantage_fn(_make_group(rewards=[1.0, 1.0], completion_lengths=[10, 30]))
|
||||
|
||||
assert result.advantages == pytest.approx([0.1, -0.1], abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_amplification_bounded():
|
||||
"""Even with extreme length outliers, reward amplification is capped at 2x."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 0.0], completion_lengths=[1, 10000, 5000])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
|
||||
# Shortest correct gets bonus ≈ 1, so shaped_reward ≈ 2
|
||||
# Standard reward = 1, so amplification ≈ 2x
|
||||
# shaped_rewards ≈ [2, 1, 0], baseline ≈ 1, max advantage ≈ 1
|
||||
assert result.advantages[0] < 1.0 + 1e-3
|
||||
|
||||
|
||||
def test_efficiency_tokens_with_tool_response_weight():
|
||||
"""`tool_response_weight` shifts shaping onto tool-response tokens read from rollout metrics."""
|
||||
rollouts = [
|
||||
{
|
||||
"reward": 1.0,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
|
||||
"metrics": {"rlm_total_tool_response_tokens": 200},
|
||||
def test_per_env_linear_advantage_uses_runtime_schema():
|
||||
config = OrchestratorConfig(
|
||||
seq_len=100,
|
||||
train={
|
||||
"env": [
|
||||
{
|
||||
"advantage": {
|
||||
"type": "default",
|
||||
"length_penalty": {"coef": 1.0},
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"reward": 1.0,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
|
||||
"metrics": {"rlm_total_tool_response_tokens": 0},
|
||||
},
|
||||
{
|
||||
"reward": 1.0,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
|
||||
"metrics": {"rlm_total_tool_response_tokens": 100},
|
||||
},
|
||||
]
|
||||
inputs = AdvantageInputs(rollouts=rollouts)
|
||||
|
||||
# completion tokens identical (10 each) → completion-only shaping is a no-op
|
||||
result_completion_only = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
assert result_completion_only.advantages == pytest.approx([0.0, 0.0, 0.0], abs=1e-6)
|
||||
|
||||
# tool-response only: costs are [200, 0, 100], mean=100, bonus is one-sided
|
||||
# so only the below-mean rollout (idx 1) gets amplified; the at/above-mean tie.
|
||||
result_tool_only = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
|
||||
advs = result_tool_only.advantages
|
||||
assert advs[1] > advs[0]
|
||||
assert advs[1] > advs[2]
|
||||
assert advs[0] == pytest.approx(advs[2], abs=1e-6)
|
||||
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_fractional_weight_with_int_rewards():
|
||||
"""Fractional weights must not truncate when rollout rewards are emitted as ints."""
|
||||
rollouts_int = [
|
||||
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(7))}}]},
|
||||
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(11))}}]},
|
||||
{"reward": 0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(13))}}]},
|
||||
]
|
||||
rollouts_float = [{**r, "reward": float(r["reward"])} for r in rollouts_int]
|
||||
|
||||
fractional = TokensLengthPenaltyConfig(completion_weight=0.3, tool_response_weight=0.0)
|
||||
int_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_int), length_penalty=fractional)
|
||||
float_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_float), length_penalty=fractional)
|
||||
assert int_result.advantages == pytest.approx(float_result.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_zero_costs_falls_back_to_plain_grpo():
|
||||
"""When all effective costs are zero, shaping is a no-op (no NaNs from div-by-zero)."""
|
||||
# tool-only weights but no harness metric → all costs == 0
|
||||
rollouts = [
|
||||
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
|
||||
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
|
||||
{"reward": 0.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
|
||||
]
|
||||
inputs = AdvantageInputs(rollouts=rollouts)
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
|
||||
expected = default_advantage_fn(inputs) # plain GRPO
|
||||
assert not any(math.isnan(a) for a in result.advantages)
|
||||
assert result.advantages == pytest.approx(expected.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_tokens_default_weights_match_completion_when_no_metric():
|
||||
"""Default TokensLengthPenaltyConfig (1,1) reduces to completion-only when rollouts lack the metric."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
|
||||
result_default = default_advantage_fn(inputs, length_penalty=TokensLengthPenaltyConfig())
|
||||
result_completion = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
assert result_default.advantages == pytest.approx(result_completion.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_turns_penalty():
|
||||
"""`TurnsLengthPenaltyConfig` shapes by trajectory turn count rather than token count."""
|
||||
inputs = _make_group(
|
||||
rewards=[1.0, 1.0, 0.0, 1.0],
|
||||
# token counts identical, but turns differ — turns penalty should still differentiate
|
||||
completion_lengths=[100, 100, 100, 100],
|
||||
num_turns=[1, 3, 2, 2],
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_penalty=TurnsLengthPenaltyConfig())
|
||||
|
||||
# mean_correct_turns = (1+3+2)/3 = 2
|
||||
# bonus = clamp(1 - [1,3,2,2]/2, 0, 1) = [0.5, 0, 0, 0]
|
||||
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
|
||||
advantage = config.train.env[0].advantage
|
||||
assert isinstance(advantage, DefaultAdvantageConfig)
|
||||
assert isinstance(advantage.length_penalty, LinearLengthPenaltyConfig)
|
||||
|
||||
fn = setup_advantage_fn(advantage, max_seq_len=config.seq_len)
|
||||
result = fn(_make_group(rewards=[1.0, 1.0], completion_lengths=[10, 30]))
|
||||
|
||||
assert result.advantages == pytest.approx([0.1, -0.1], abs=1e-6)
|
||||
|
||||
|
||||
def test_per_env_custom_advantage_uses_runtime_schema():
|
||||
config = OrchestratorConfig(
|
||||
train={
|
||||
"env": [
|
||||
{
|
||||
"advantage": {
|
||||
"type": "custom",
|
||||
"import_path": "tests.unit.orchestrator.test_advantage._dummy_custom_advantage",
|
||||
"kwargs": {"scale": 3.0},
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
advantage = config.train.env[0].advantage
|
||||
assert isinstance(advantage, CustomAdvantageConfig)
|
||||
|
||||
fn = setup_advantage_fn(advantage)
|
||||
result = fn(_make_group(rewards=[1.0, 0.5], completion_lengths=[10, 20]))
|
||||
|
||||
assert result.advantages == pytest.approx([3.0, 1.5], abs=1e-6)
|
||||
|
||||
|
||||
def test_length_weighted_baseline():
|
||||
"""Length-weighted baseline uses sum(len_i * reward_i) / sum(len_i) instead of the plain mean."""
|
||||
rewards = [1.0, 0.0, 0.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 30, 60])
|
||||
result = default_advantage_fn(inputs, length_weighted_baseline=True)
|
||||
|
||||
baseline = (10 * 1.0 + 30 * 0.0 + 60 * 0.0) / (10 + 30 + 60) # 0.1
|
||||
assert result.advantages == pytest.approx([r - baseline for r in rewards], abs=1e-6)
|
||||
# Token-weighted mean of advantages is zero
|
||||
assert sum(length * adv for length, adv in zip((10, 30, 60), result.advantages)) == pytest.approx(0.0, abs=1e-5)
|
||||
|
||||
|
||||
def _train_rollouts(rewards: list[float]) -> list[TrainRollout]:
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from prime_rl.trainer.batch import prepare_batch, prepare_sample
|
||||
from prime_rl.transport.types import RoutedExperts, TrainingSample
|
||||
from prime_rl.trainer.batch import (
|
||||
pad_micro_batch,
|
||||
prepare_batch,
|
||||
prepare_sample,
|
||||
)
|
||||
from prime_rl.trainer.utils import build_bin_cost
|
||||
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingSample
|
||||
|
||||
|
||||
def _routed_experts(data, dtype=np.uint8):
|
||||
@@ -37,51 +44,80 @@ def make_training_example():
|
||||
return _make_training_example
|
||||
|
||||
|
||||
def test_training_sample_requires_env_name():
|
||||
with pytest.raises(TypeError, match="env_name"):
|
||||
TrainingSample(
|
||||
prompt_ids=[1, 2],
|
||||
prompt_mask=[False, False],
|
||||
completion_ids=[3, 4],
|
||||
completion_mask=[True, True],
|
||||
completion_logprobs=[-0.1, -0.2],
|
||||
completion_temperatures=[1.0, 1.0],
|
||||
advantage=1.0,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("rollout_count", "num_train_workers", "expected_batches_per_worker"), [(4, 2, 2), (5, 2, 3), (7, 1, 7), (11, 4, 3)]
|
||||
)
|
||||
def test_prepare_batch_balances_micro_batches_across_workers(
|
||||
make_training_example, rollout_count, num_train_workers, expected_batches_per_worker
|
||||
):
|
||||
examples = [make_training_example() for i in range(rollout_count)]
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=examples,
|
||||
seq_len=4,
|
||||
num_train_workers=num_train_workers,
|
||||
idxs=[0] * rollout_count,
|
||||
num_loras=1,
|
||||
def make_sized_training_example(length: int, env_name: str = "test-env") -> TrainingSample:
|
||||
assert length >= 1
|
||||
prompt_len = length - 1
|
||||
return TrainingSample(
|
||||
prompt_ids=[1] * prompt_len,
|
||||
prompt_mask=[False] * prompt_len,
|
||||
completion_ids=[2],
|
||||
completion_mask=[True],
|
||||
completion_logprobs=[-0.1],
|
||||
completion_temperatures=[1.0],
|
||||
advantage=1.0,
|
||||
env_name=env_name,
|
||||
)
|
||||
|
||||
assert all(len(worker_batches) == expected_batches_per_worker for worker_batches in batches_per_gpu)
|
||||
|
||||
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
|
||||
assert len(examples) <= len(flat_batches) < len(examples) + num_train_workers
|
||||
print(flat_batches)
|
||||
def _flatten_batches(batches_per_gpu):
|
||||
return [batch for worker_batches in batches_per_gpu for batch in worker_batches]
|
||||
|
||||
# Verify real rollouts have expected non-zero advantages and loss mask
|
||||
for batch in flat_batches[: len(examples)]:
|
||||
print(batch)
|
||||
assert sum(1 for advantage in batch.advantages if advantage != 0.0) == 4
|
||||
assert sum(1 for loss_mask in batch.loss_mask if loss_mask) == 2
|
||||
|
||||
# Verify padded batches have zero advantages and loss mask
|
||||
for batch in flat_batches[len(examples) :]:
|
||||
assert sum(1 for advantage in batch.advantages if advantage != 0.0) == 0
|
||||
assert sum(1 for loss_mask in batch.loss_mask if loss_mask) == 0
|
||||
def _worker_token_sums(batches_per_gpu) -> list[int]:
|
||||
return [sum(len(batch.input_ids) for batch in worker_batches) for worker_batches in batches_per_gpu]
|
||||
|
||||
|
||||
def _has_loss_tokens(batch: MicroBatch) -> bool:
|
||||
return any(batch.loss_mask)
|
||||
|
||||
|
||||
def make_flops_config():
|
||||
return SimpleNamespace(
|
||||
hidden_size=16,
|
||||
num_attention_heads=2,
|
||||
num_key_value_heads=2,
|
||||
vocab_size=32,
|
||||
intermediate_size=64,
|
||||
num_hidden_layers=2,
|
||||
head_dim=8,
|
||||
)
|
||||
|
||||
|
||||
def test_randomized_packing_invariants():
|
||||
rng = np.random.default_rng(0)
|
||||
|
||||
for case_idx in range(80):
|
||||
seq_len = int(rng.choice([8, 16, 32, 64]))
|
||||
num_train_workers = int(rng.choice([1, 2, 4, 8]))
|
||||
num_samples = int(rng.integers(1, 65))
|
||||
lengths = [int(x) for x in rng.integers(1, seq_len + 1, size=num_samples)]
|
||||
examples = [make_sized_training_example(length, env_name=f"env-{case_idx}") for length in lengths]
|
||||
bin_cost = build_bin_cost(make_flops_config() if case_idx % 2 == 0 else None)
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=examples,
|
||||
seq_len=seq_len,
|
||||
num_train_workers=num_train_workers,
|
||||
idxs=[0] * len(examples),
|
||||
num_loras=1,
|
||||
bin_cost=bin_cost,
|
||||
)
|
||||
flat_batches = _flatten_batches(batches_per_gpu)
|
||||
real_batches = [batch for batch in flat_batches if _has_loss_tokens(batch)]
|
||||
dummy_batches = [batch for batch in flat_batches if not _has_loss_tokens(batch)]
|
||||
|
||||
assert all(len(worker_batches) == len(batches_per_gpu[0]) for worker_batches in batches_per_gpu)
|
||||
assert sorted(length for batch in real_batches for length in batch.sequence_lengths) == sorted(lengths)
|
||||
|
||||
for batch in flat_batches:
|
||||
assert len(batch.input_ids) <= seq_len
|
||||
assert sum(batch.sequence_lengths) == len(batch.input_ids)
|
||||
assert sum(batch.lora_num_tokens) == len(batch.input_ids)
|
||||
assert len(batch.env_names) == len(batch.input_ids)
|
||||
|
||||
for batch in dummy_batches:
|
||||
assert not any(batch.loss_mask)
|
||||
assert not any(batch.advantages)
|
||||
|
||||
|
||||
def test_prepare_batch_packs_different_temperatures(make_training_example):
|
||||
@@ -95,9 +131,10 @@ def test_prepare_batch_packs_different_temperatures(make_training_example):
|
||||
num_train_workers=1,
|
||||
idxs=[0, 0],
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
|
||||
flat_batches = _flatten_batches(batches_per_gpu)
|
||||
# With per-token temperatures, samples can now be packed together
|
||||
assert len(flat_batches) == 1
|
||||
# Each sample has 4 tokens (2 prompt + 2 completion), so 8 total tokens
|
||||
@@ -107,14 +144,18 @@ def test_prepare_batch_packs_different_temperatures(make_training_example):
|
||||
# Second sample (4 tokens): all get temp 1.1
|
||||
assert flat_batches[0].temperatures[4:8] == [1.1, 1.1, 1.1, 1.1]
|
||||
assert flat_batches[0].env_names == ["env-a"] * 4 + ["env-b"] * 4
|
||||
assert flat_batches[0].sequence_lengths == [4, 4]
|
||||
|
||||
|
||||
def test_prepare_sample_propagates_training_mode(make_training_example):
|
||||
example = make_training_example(training_mode="sft")
|
||||
def test_pad_micro_batch_preserves_explicit_sequence_lengths(make_training_example):
|
||||
micro_batch = prepare_sample(make_training_example(), seq_len=16)
|
||||
|
||||
micro_batch = prepare_sample(example, seq_len=16)
|
||||
padded = pad_micro_batch(micro_batch, pad_to_multiple_of=6)
|
||||
|
||||
assert micro_batch.training_mode == "sft"
|
||||
assert len(padded.input_ids) == 6
|
||||
assert padded.sequence_lengths == [4, 2]
|
||||
assert sum(padded.sequence_lengths) == len(padded.input_ids)
|
||||
assert padded.loss_mask[-2:] == [False, False]
|
||||
|
||||
|
||||
def test_prepare_batch_does_not_pack_mixed_training_mode(make_training_example):
|
||||
@@ -127,33 +168,80 @@ def test_prepare_batch_does_not_pack_mixed_training_mode(make_training_example):
|
||||
num_train_workers=1,
|
||||
idxs=[0, 0],
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
|
||||
flat_batches = _flatten_batches(batches_per_gpu)
|
||||
assert len(flat_batches) == 2
|
||||
assert {batch.training_mode for batch in flat_batches} == {"rl", "sft"}
|
||||
assert [batch.sequence_lengths for batch in flat_batches] == [[4], [4]]
|
||||
|
||||
|
||||
def test_prepare_sample_with_routed_experts():
|
||||
"""Routed experts are passed through prepare_sample and match input_ids length."""
|
||||
# 2 prompt + 2 completion = 4 tokens, 2 layers, topk=2
|
||||
routed_experts = [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[0, 2], [1, 3]], [[1, 0], [3, 2]]]
|
||||
routed_payload = _routed_experts(routed_experts)
|
||||
sample = TrainingSample(
|
||||
prompt_ids=[1, 2],
|
||||
prompt_mask=[False, False],
|
||||
completion_ids=[3, 4],
|
||||
completion_mask=[True, True],
|
||||
completion_logprobs=[-0.1, -0.2],
|
||||
completion_temperatures=[1.0, 1.0],
|
||||
advantage=1.0,
|
||||
env_name="test-env",
|
||||
routed_experts=routed_payload,
|
||||
def test_split_to_align_avoids_dummy_micro_batches():
|
||||
examples = [make_sized_training_example(length) for length in [6, 6, 5, 5, 4, 4]]
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=examples,
|
||||
seq_len=12,
|
||||
num_train_workers=4,
|
||||
idxs=[0] * len(examples),
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
micro_batch = prepare_sample(sample, seq_len=8)
|
||||
assert micro_batch.routed_experts is not None
|
||||
assert micro_batch.routed_experts == routed_payload
|
||||
assert all(_has_loss_tokens(batch) for batch in _flatten_batches(batches_per_gpu))
|
||||
assert len(_flatten_batches(batches_per_gpu)) == 4
|
||||
|
||||
|
||||
def test_pack_first_then_balance_distributes_micro_batches_by_tokens_without_model_config():
|
||||
examples = [make_sized_training_example(length) for length in [100, 90, 80, 70]]
|
||||
|
||||
balanced = prepare_batch(
|
||||
rollouts=examples,
|
||||
seq_len=100,
|
||||
num_train_workers=2,
|
||||
idxs=[0] * len(examples),
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
assert _worker_token_sums(balanced) == [170, 170]
|
||||
|
||||
|
||||
def test_flop_aware_balancing_pairs_long_and_short_sequence_workloads():
|
||||
examples = [make_sized_training_example(length) for length in [32, 32, 16, 16, 16, 16]]
|
||||
bin_cost = build_bin_cost(make_flops_config())
|
||||
|
||||
balanced = prepare_batch(
|
||||
rollouts=examples,
|
||||
seq_len=32,
|
||||
num_train_workers=2,
|
||||
idxs=[0] * len(examples),
|
||||
num_loras=1,
|
||||
bin_cost=bin_cost,
|
||||
)
|
||||
|
||||
assert sorted([sorted(batch.sequence_lengths) for batch in balanced[0]]) == [[16, 16], [32]]
|
||||
assert sorted([sorted(batch.sequence_lengths) for batch in balanced[1]]) == [[16, 16], [32]]
|
||||
assert bin_cost([32]) > bin_cost([16, 16])
|
||||
|
||||
|
||||
def test_flop_aware_split_to_align_splits_heaviest_flop_bin():
|
||||
examples = [make_sized_training_example(length) for length in [20, 18, 9, 9, 8, 8, 8]]
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=examples,
|
||||
seq_len=64,
|
||||
num_train_workers=4,
|
||||
idxs=[0] * len(examples),
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(make_flops_config()),
|
||||
)
|
||||
|
||||
real_batches = [batch for batch in _flatten_batches(batches_per_gpu) if _has_loss_tokens(batch)]
|
||||
assert len(real_batches) == 4
|
||||
assert sorted(length for batch in real_batches for length in batch.sequence_lengths) == [8, 8, 8, 9, 9, 18, 20]
|
||||
assert sum(len(batch.sequence_lengths) > 1 for batch in real_batches) == 3
|
||||
|
||||
|
||||
def test_prepare_sample_truncates_routed_experts():
|
||||
@@ -177,20 +265,3 @@ def test_prepare_sample_truncates_routed_experts():
|
||||
assert micro_batch.routed_experts is not None
|
||||
assert micro_batch.routed_experts == expected_payload
|
||||
assert micro_batch.env_names == ["test-env"] * 3
|
||||
|
||||
|
||||
def test_prepare_sample_none_routed_experts():
|
||||
"""When routed_experts is None, micro_batch.routed_experts is None."""
|
||||
sample = TrainingSample(
|
||||
prompt_ids=[1, 2],
|
||||
prompt_mask=[False, False],
|
||||
completion_ids=[3, 4],
|
||||
completion_mask=[True, True],
|
||||
completion_logprobs=[-0.1, -0.2],
|
||||
completion_temperatures=[1.0, 1.0],
|
||||
advantage=1.0,
|
||||
env_name="test-env",
|
||||
)
|
||||
|
||||
micro_batch = prepare_sample(sample, seq_len=8)
|
||||
assert micro_batch.routed_experts is None
|
||||
|
||||
@@ -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
|
||||
@@ -168,6 +167,53 @@ def test_removed_fused_lm_head_chunk_size_field_is_rejected():
|
||||
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
|
||||
|
||||
|
||||
def test_trainer_enable_token_export_cli_flag():
|
||||
assert not cli(TrainerConfig, args=[]).enable_token_export
|
||||
assert cli(TrainerConfig, args=["--enable-token-export"]).enable_token_export
|
||||
|
||||
|
||||
def test_single_node_auto_inference_client_dp_rank_count_matches_local_dp():
|
||||
config = RLConfig.model_validate(
|
||||
{
|
||||
"trainer": {},
|
||||
"orchestrator": {},
|
||||
"inference": {"parallel": {"tp": 1}},
|
||||
"deployment": {
|
||||
"type": "single_node",
|
||||
"gpus_per_node": 4,
|
||||
"num_train_gpus": 2,
|
||||
"num_infer_gpus": 2,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
assert config.inference is not None
|
||||
assert config.inference.parallel.dp == 2
|
||||
assert config.orchestrator.student.client.dp_rank_count == 2
|
||||
|
||||
|
||||
def test_multi_node_auto_inference_client_dp_rank_count_uses_router_url():
|
||||
config = RLConfig.model_validate(
|
||||
{
|
||||
"trainer": {},
|
||||
"orchestrator": {},
|
||||
"inference": {"parallel": {"tp": 4}},
|
||||
"deployment": {
|
||||
"type": "multi_node",
|
||||
"gpus_per_node": 8,
|
||||
"num_train_nodes": 1,
|
||||
"num_infer_nodes": 2,
|
||||
},
|
||||
"slurm": {},
|
||||
}
|
||||
)
|
||||
|
||||
assert config.inference is not None
|
||||
assert config.inference.data_parallel_size_local == 2
|
||||
assert config.inference.parallel.dp == 2
|
||||
assert config.orchestrator.student.client.dp_rank_count == 1
|
||||
|
||||
|
||||
def test_orchestrator_vlm_requires_renderer():
|
||||
with pytest.raises(ValidationError, match="orchestrator.renderer must be set when model.vlm is set"):
|
||||
OrchestratorConfig.model_validate(
|
||||
|
||||
@@ -38,8 +38,8 @@ EXPECTED_PARSERS: list[tuple[str, str | None, str | None]] = [
|
||||
("PrimeIntellect/INTELLECT-3-FP8", "qwen3_coder", "deepseek_r1"),
|
||||
("PrimeIntellect/INTELLECT-3.1", "qwen3_coder", "deepseek_r1"),
|
||||
# NemotronH
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "qwen3_coder", None),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "qwen3_coder", None),
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "qwen3_coder", "nemotron_v3"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "qwen3_coder", "nano_v3"),
|
||||
# StepFun
|
||||
("stepfun-ai/Step-3.5-Flash", "step3p5", "step3p5"),
|
||||
# Qwen3 dense
|
||||
|
||||
@@ -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)
|
||||
@@ -10,6 +10,7 @@ import prime_rl.trainer.runs as runs
|
||||
from prime_rl.configs.shared import FileSystemTransportConfig
|
||||
from prime_rl.trainer.rl.packer import MultiPacker
|
||||
from prime_rl.trainer.runs import setup_multi_run_manager
|
||||
from prime_rl.trainer.utils import build_bin_cost
|
||||
from prime_rl.trainer.world import reset_world
|
||||
from prime_rl.transport.types import TrainingSample
|
||||
|
||||
@@ -94,6 +95,7 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
|
||||
pad_to_multiple_of=1,
|
||||
tokenizer=None,
|
||||
config=FileSystemTransportConfig(),
|
||||
bin_cost=build_bin_cost(None),
|
||||
start_step=0,
|
||||
)
|
||||
|
||||
@@ -110,3 +112,6 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
|
||||
sender = sender_holder["sender"]
|
||||
assert len(sender.sent) == 1
|
||||
assert len(sender.sent[0][0]) == 1
|
||||
micro_batch = sender.sent[0][0][0]
|
||||
assert micro_batch.run_id == "run_test123"
|
||||
assert micro_batch.run_step == 0
|
||||
|
||||
Reference in New Issue
Block a user