Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c282262e6e | ||
|
|
289562d2ec | ||
|
|
3ab5e04c4c | ||
|
|
d1046b876c | ||
|
|
381df0a658 | ||
|
|
532d622b4c | ||
|
|
ec92686fbc |
@@ -193,7 +193,11 @@ jobs:
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.cuda
|
||||
push: true
|
||||
# zstd compresses the multi-GB venv layers several times faster than gzip at a
|
||||
# comparable ratio. No `force-compression`, so base-image layers are reused as-is
|
||||
# rather than needlessly recompressed. Pulling zstd layers needs containerd >= 1.5
|
||||
# or Docker >= 23.
|
||||
outputs: type=image,push=true,compression=zstd,compression-level=3
|
||||
platforms: ${{ matrix.platform }}
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
|
||||
|
||||
@@ -84,9 +84,6 @@ jobs:
|
||||
- test: reverse_text_moe
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_moe.py"
|
||||
- test: reverse_text_multi_run
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_reverse_text_multi_run.py"
|
||||
- test: benchmark_regression
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_benchmark_regression.py"
|
||||
|
||||
+21
-7
@@ -1,3 +1,7 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
# ^ `COPY --exclude` (used to split the venv into parallel-compressible layers) needs
|
||||
# Dockerfile syntax >= 1.19; `docker/dockerfile:1` resolves to the latest stable 1.x.
|
||||
|
||||
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
|
||||
|
||||
# Build stage - multi-arch base (supports amd64 + arm64)
|
||||
@@ -128,11 +132,6 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
|
||||
&& rm -rf /tmp/nixl /app/deps/nixl_cu12-*.whl; \
|
||||
fi
|
||||
|
||||
# arm64: build flash-attn from source, fix namespace conflicts, apply workarounds
|
||||
ARG TARGETARCH
|
||||
COPY scripts/docker-arm64-post-install.sh /app/scripts/docker-arm64-post-install.sh
|
||||
RUN if [ "$TARGETARCH" = "arm64" ]; then /app/scripts/docker-arm64-post-install.sh; fi
|
||||
|
||||
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
|
||||
# COPY ships only the trimmed result (~1.5 GB) instead of the full ~6.6 GB. Drops the math
|
||||
# runtime libs (cublas/cusparse/cufft/cusolver/curand/npp/nvjpeg) and big static .a
|
||||
@@ -217,8 +216,23 @@ RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.
|
||||
USER appuser
|
||||
ENV PATH="/usr/local/bin:$PATH"
|
||||
WORKDIR /app
|
||||
# Copy the application from the builder
|
||||
COPY --from=builder --chown=appuser:appuser /app /app
|
||||
# Copy the application from the builder, splitting the venv's largest trees into their
|
||||
# own layers. BuildKit compresses and pushes layers in parallel, so shipping the whole
|
||||
# ~20 GB venv as one layer serialized the export behind a single compressor. Splitting
|
||||
# also lets nodes pull the image in parallel. Keep the excludes below in sync with the
|
||||
# per-tree copies that follow, or the data lands in the image twice.
|
||||
COPY --from=builder --chown=appuser:appuser \
|
||||
--exclude=.venv/lib/python3.12/site-packages/nvidia \
|
||||
--exclude=.venv/lib/python3.12/site-packages/torch \
|
||||
--exclude=.venv/lib/python3.12/site-packages/vllm \
|
||||
--exclude=.venv/lib/python3.12/site-packages/flash_attn \
|
||||
--exclude=.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so \
|
||||
/app /app
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/nvidia /app/.venv/lib/python3.12/site-packages/nvidia
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/torch /app/.venv/lib/python3.12/site-packages/torch
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/vllm /app/.venv/lib/python3.12/site-packages/vllm
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn /app/.venv/lib/python3.12/site-packages/flash_attn
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so /app/.venv/lib/python3.12/site-packages/
|
||||
COPY --from=builder /opt/ucx /opt/ucx
|
||||
|
||||
# Copy and set up entrypoint script
|
||||
|
||||
@@ -113,15 +113,6 @@ uv sync --all-extras
|
||||
|
||||
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
|
||||
|
||||
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.
|
||||
@@ -166,7 +157,7 @@ uv run trainer @ configs/debug/fake/rl.toml
|
||||
5. Check that you can run the inference server (*this requires 1 GPU*)
|
||||
|
||||
```bash
|
||||
uv run inference --model.name Qwen/Qwen3-0.6B
|
||||
uv run inference --vllm.model Qwen/Qwen3-0.6B
|
||||
```
|
||||
|
||||
6. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
|
||||
@@ -227,7 +218,7 @@ Check out the [docs](docs) directory for in-depth guides on how to use prime-rl.
|
||||
- [**Training**](docs/training.md) - RL, SFT, evals, checkpointing, observability, rules of thumb
|
||||
- [**Scaling**](docs/scaling.md) - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
|
||||
- [**Algorithms**](docs/algorithms.md) - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
|
||||
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA, multi-tenant training
|
||||
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA
|
||||
- [**Development**](docs/development.md) - Test suite, pre-commit hooks, adding a new model
|
||||
|
||||
## Contributing
|
||||
|
||||
@@ -36,10 +36,8 @@ type = "subprocess"
|
||||
[trainer.model]
|
||||
seq_len = 16384
|
||||
|
||||
[inference.model]
|
||||
[inference.vllm]
|
||||
max_model_len = 8192
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -54,5 +54,5 @@ type = "subprocess"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference.model]
|
||||
[inference.vllm]
|
||||
tool_call_parser = "hermes"
|
||||
|
||||
@@ -39,10 +39,12 @@ id = "null"
|
||||
type = "subprocess"
|
||||
|
||||
[inference]
|
||||
enable_lora = true
|
||||
gpu_memory_utilization = 0.7
|
||||
|
||||
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
|
||||
# suffix misses the MODEL_RENDERER_MAP exact match).
|
||||
|
||||
[inference.vllm]
|
||||
enable_lora = true
|
||||
gpu_memory_utilization = 0.7
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
@@ -38,10 +38,12 @@ id = "null"
|
||||
type = "subprocess"
|
||||
|
||||
[inference]
|
||||
enable_lora = true
|
||||
gpu_memory_utilization = 0.7
|
||||
|
||||
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
|
||||
# suffix misses the MODEL_RENDERER_MAP exact match).
|
||||
|
||||
[inference.vllm]
|
||||
enable_lora = true
|
||||
gpu_memory_utilization = 0.7
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
@@ -38,11 +38,9 @@ id = "null"
|
||||
type = "subprocess"
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.7
|
||||
|
||||
[inference.model]
|
||||
[inference.vllm]
|
||||
max_model_len = 2048
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
gpu_memory_utilization = 0.7
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
# Env server for the multi-run RL integration test: one per orchestrator, each bound at
|
||||
# its run's base port (the test passes --serve.address).
|
||||
[env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[env.agent.runtime]
|
||||
type = "subprocess"
|
||||
@@ -1,13 +0,0 @@
|
||||
# Inference config for multi-run RL integration test
|
||||
enable_lora = true
|
||||
max_lora_rank = 8
|
||||
max_loras = 4
|
||||
gpu_memory_utilization = 0.7
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
max_model_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
# Orchestrator config for multi-run RL integration test
|
||||
# model.lora.name and output_dir are set via CLI
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
seq_len = 2048
|
||||
max_steps = 20
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[optim]
|
||||
lr = 3e-5
|
||||
|
||||
[train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[ckpt]
|
||||
interval = 10
|
||||
resume_step = -1
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
|
||||
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
|
||||
# suffix misses the MODEL_RENDERER_MAP exact match).
|
||||
[renderer]
|
||||
name = "prime-qwen3"
|
||||
@@ -1,21 +0,0 @@
|
||||
# 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"
|
||||
seq_len = 65536
|
||||
fused_lm_head_token_chunk_size = 8192
|
||||
optim_cpu_offload = false
|
||||
|
||||
[model.lora]
|
||||
rank = 8
|
||||
|
||||
[model.ac]
|
||||
freq = 1
|
||||
|
||||
[model.compile]
|
||||
fullgraph = false
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
@@ -29,7 +29,7 @@ type = "opd"
|
||||
|
||||
[orchestrator.algo.teacher]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
base_url = "http://localhost:8001/v1"
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
@@ -72,4 +72,6 @@ type = "subprocess"
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.4
|
||||
|
||||
@@ -30,7 +30,7 @@ type = "sft"
|
||||
# sft's teacher IS the model it samples from.
|
||||
[orchestrator.algo.sampling.source]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
base_url = "http://localhost:8001/v1"
|
||||
|
||||
# The student's renderer tokenizes the teacher's messages into the student's
|
||||
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
|
||||
@@ -78,4 +78,6 @@ type = "subprocess"
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.4
|
||||
|
||||
@@ -40,5 +40,5 @@ max_completion_tokens = 768
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 4
|
||||
[inference.vllm]
|
||||
data_parallel_size = 4
|
||||
|
||||
@@ -54,12 +54,9 @@ type = "subprocess"
|
||||
seq_len = 16384
|
||||
attn = "flash_attention_2"
|
||||
|
||||
[inference.parallel]
|
||||
dp = 4
|
||||
|
||||
[inference.model]
|
||||
[inference.vllm]
|
||||
max_model_len = 8192
|
||||
|
||||
data_parallel_size = 4
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -40,8 +40,6 @@ max_completion_tokens = 512
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 4
|
||||
|
||||
[inference.model]
|
||||
[inference.vllm]
|
||||
tool_call_parser = "hermes"
|
||||
data_parallel_size = 4
|
||||
|
||||
@@ -35,8 +35,7 @@ max_completion_tokens = 1024
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
|
||||
[inference.vllm]
|
||||
data_parallel_size = 6
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
@@ -24,10 +24,10 @@ Needed for `opd*.toml`, `sft_distill.toml` / `sft_distill_lora.toml`, and `mixed
|
||||
|
||||
```bash
|
||||
CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
--model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
--vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
--server.port 8001 \
|
||||
--gpu-memory-utilization 0.5 \
|
||||
--model.enforce-eager
|
||||
--vllm.gpu-memory-utilization 0.5 \
|
||||
--vllm.enforce-eager
|
||||
```
|
||||
|
||||
## Run the debug configs
|
||||
|
||||
@@ -58,4 +58,6 @@ name = "prime-qwen3"
|
||||
lr = 1e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
@@ -58,4 +58,6 @@ lr = 3e-6
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
@@ -58,4 +58,6 @@ lr = 3e-6
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
# ref_logprobs, GRPO samples don't, and both pack into the same micro batches.
|
||||
# Start the frozen reference server first (on a separate GPU):
|
||||
# CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
|
||||
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/algo/mixed_grpo_opd.toml
|
||||
|
||||
@@ -60,7 +60,7 @@ type = "opd"
|
||||
|
||||
[orchestrator.train.source.algo.teacher]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
base_url = "http://localhost:8001/v1"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
@@ -85,4 +85,6 @@ type = "subprocess"
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Start the frozen reference server first (on a separate GPU):
|
||||
# CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
|
||||
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/algo/opd.toml
|
||||
|
||||
@@ -24,7 +24,7 @@ type = "opd"
|
||||
|
||||
[orchestrator.algo.teacher]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
base_url = "http://localhost:8001/v1"
|
||||
|
||||
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
|
||||
[orchestrator.renderer]
|
||||
@@ -70,4 +70,6 @@ lr = 3e-6
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Start the frozen reference server first (on a separate GPU):
|
||||
# CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
|
||||
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/algo/opd_lora.toml
|
||||
|
||||
@@ -24,7 +24,7 @@ type = "opd"
|
||||
|
||||
[orchestrator.algo.teacher]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
base_url = "http://localhost:8001/v1"
|
||||
|
||||
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
|
||||
[orchestrator.renderer]
|
||||
@@ -76,4 +76,6 @@ save_adapter_separately = true
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
@@ -70,4 +70,6 @@ lr = 3e-6
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
@@ -64,4 +64,6 @@ type = "subprocess"
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Start the frozen reference server first (on a separate GPU):
|
||||
# CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
|
||||
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/algo/sft_distill.toml
|
||||
|
||||
@@ -25,7 +25,7 @@ type = "sft"
|
||||
# sft's teacher IS the model it samples from.
|
||||
[orchestrator.algo.sampling.source]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
base_url = "http://localhost:8001/v1"
|
||||
|
||||
# The student's renderer tokenizes the teacher's messages into the student's
|
||||
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
|
||||
@@ -75,4 +75,6 @@ lr = 3e-6
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Start the frozen reference server first (on a separate GPU):
|
||||
# CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
|
||||
# --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --vllm.gpu-memory-utilization 0.5 --vllm.enforce-eager
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/algo/sft_distill_lora.toml
|
||||
|
||||
@@ -25,7 +25,7 @@ type = "sft"
|
||||
# sft's teacher IS the model it samples from.
|
||||
[orchestrator.algo.sampling.source]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
base_url = "http://localhost:8001/v1"
|
||||
|
||||
# The student's renderer tokenizes the teacher's messages into the student's
|
||||
# token space (backfill). Use `prime-qwen3` — it matches this PrimeIntellect
|
||||
@@ -81,4 +81,6 @@ save_adapter_separately = true
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
@@ -64,4 +64,6 @@ type = "subprocess"
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
Vendored
+1
-1
Submodule deps/renderers updated: d4707862ac...2a7e77eb14
Vendored
+1
-1
Submodule deps/research-environments updated: f9c43a74fe...b10db7640b
Vendored
+1
-1
Submodule deps/verifiers updated: d30a3f48e5...29e3a0f7a3
+1
-8
@@ -1,6 +1,6 @@
|
||||
# Advanced
|
||||
|
||||
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, multi-tenant training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
|
||||
This page covers the specialized features layered on top of the core training stack: our custom model implementations (with EP for MoE families and CP for long-context training), multimodal training, LoRA training, and disaggregated prefill/decode inference. For developer-side workflows (adding new model architectures, debugging modeling code at small scale), see [Development](development.md).
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -11,7 +11,6 @@ This page covers the specialized features layered on top of the core training st
|
||||
- [Enabling VLM Mode](#enabling-vlm-mode)
|
||||
- [Limitations](#limitations)
|
||||
- [LoRA Training](#lora-training)
|
||||
- [Multi-Tenant Training](#multi-tenant-training)
|
||||
- [Disaggregated Prefill/Decode Inference](#disaggregated-prefilldecode-inference)
|
||||
|
||||
## Custom Modeling
|
||||
@@ -123,12 +122,6 @@ LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** su
|
||||
save_adapter_separately = true
|
||||
```
|
||||
|
||||
LoRA pairs naturally with [multi-tenant training](#multi-tenant-training) — each tenant gets its own adapter and the backbone is shared across all of them in trainer memory.
|
||||
|
||||
## 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.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/src/prime_rl/trainer/runs.py).
|
||||
|
||||
## Disaggregated Prefill/Decode Inference
|
||||
|
||||
For large MoE serving, splitting prefill and decode onto separate vLLM groups can substantially improve throughput. Pick the prefill:decode ratio based on workload shape:
|
||||
|
||||
+2
-2
@@ -35,7 +35,7 @@ A training algorithm in `prime-rl` is configured under `[orchestrator.algo]`, wh
|
||||
1. **Sampling** (`algo.sampling`) — how train rollouts are produced: which model generates them. `source` is a [model reference](#model-references): `"policy"` (the live policy, the default) or an inline frozen hosted model. Group sizing stays on the env config (`group_size`).
|
||||
2. **The per-token training signal** — credit assignment and loss routing, fused; the algorithm's own parameters sit directly on `algo`. One mapping from a finalized rollout to per-token *(loss component, weight)* pairs — the credit a token gets and the loss that consumes it are two coordinates of the same output. Group-relative algorithms compute credit on the orchestrator and ship per-token advantage streams; reference-KL algorithms query a reference model at batch-ship time (bounded concurrency) and ship its prefill logprobs for the trainer to evaluate against the live policy. The `type` determines which loss component consumes the action tokens (`rl` / `ce` / `ref_kl`) and what happens to env-provided observation tokens in multi-turn rollouts (masked out by default; `echo` trains on them with weighted CE).
|
||||
|
||||
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, packer, or trainer hot path.
|
||||
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, batch packing, or trainer hot path.
|
||||
|
||||
### Model References
|
||||
|
||||
@@ -47,7 +47,7 @@ type = "opd"
|
||||
|
||||
[orchestrator.algo.teacher] # opd's teacher: the frozen model it scores against
|
||||
name = "Qwen/Qwen3-32B"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
base_url = "http://localhost:8001/v1"
|
||||
```
|
||||
|
||||
Model *roles* are algorithm-local vocabulary — each algorithm names its reference on the field where the model is actually used, and there is no shared `teacher` slot. `opd` declares a `teacher` field (the frozen model whose reverse KL the policy distills toward); `sft`'s teacher *is* its `sampling.source` (the frozen model it imitates); `opsd` self-distills against the live policy and names no model at all. No role exists outside the algorithm that declares it: the dispatcher, sink, and trainer branch on liveness alone, never on what an algorithm calls a model.
|
||||
|
||||
@@ -50,7 +50,7 @@ CLI flags mirror the TOML tree using dots:
|
||||
--max-steps 50 # top-level
|
||||
--model.name Qwen/Qwen3-4B # nested
|
||||
--trainer.optim.lr 1e-5 # double-nested
|
||||
--inference.parallel.tp 4
|
||||
--inference.vllm.tensor-parallel-size 4
|
||||
```
|
||||
|
||||
> Field names are snake_case in TOML (`max_model_len`) and kebab-case on the CLI (`--max-model-len`).
|
||||
@@ -126,11 +126,11 @@ To **disable** a sub-config that's on by default, use `--no-<name>` on the CLI o
|
||||
TOML has no `null`. Use the string `"None"`, which the loader coerces:
|
||||
|
||||
```toml
|
||||
[inference.model]
|
||||
[inference.vllm]
|
||||
max_model_len = "None"
|
||||
```
|
||||
|
||||
On the CLI: `--inference.model.max-model-len None`.
|
||||
On the CLI: `--inference.vllm.max-model-len None`.
|
||||
|
||||
### Discriminated Unions
|
||||
|
||||
|
||||
+3
-3
@@ -42,7 +42,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
|
||||
| Workflow | Trigger | What runs | Where |
|
||||
|---|---|---|---|
|
||||
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
|
||||
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_multi_run`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
|
||||
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
|
||||
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
|
||||
|
||||
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
|
||||
@@ -118,8 +118,8 @@ Then run the full RL stack on reverse-text:
|
||||
uv run rl @ configs/ci/integration/reverse-text-moe/start.toml \
|
||||
--model.name samsja/mini-glm-moe \
|
||||
--trainer.model.impl custom \
|
||||
--inference.gpu-memory-utilization 0.7 \
|
||||
--inference.model.max-model-len 2048
|
||||
--inference.vllm.gpu-memory-utilization 0.7 \
|
||||
--inference.vllm.max-model-len 2048
|
||||
```
|
||||
|
||||
What to look for:
|
||||
|
||||
+23
-26
@@ -42,7 +42,7 @@ 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]
|
||||
[inference.vllm]
|
||||
model = "PrimeIntellect/INTELLECT-3"
|
||||
...
|
||||
```
|
||||
@@ -63,12 +63,10 @@ The launcher starts a `vllm-router` on `inference.server.port` (default `8000`)
|
||||
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]
|
||||
[inference.vllm]
|
||||
enable_expert_parallel = true # defaults to False
|
||||
|
||||
[inference.parallel]
|
||||
tp = 2
|
||||
dp = 4
|
||||
tensor_parallel_size = 2
|
||||
data_parallel_size = 4
|
||||
|
||||
[inference.deployment]
|
||||
type = "single_node"
|
||||
@@ -76,7 +74,7 @@ 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.
|
||||
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.vllm.enable_expert_parallel` or `inference.vllm.tensor_parallel_size` 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.
|
||||
|
||||
@@ -86,7 +84,7 @@ You can also increase the available KV cache memory by enabling `inference.kv_ca
|
||||
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.
|
||||
- [Wide-EP](#wide-ep) - This option is gated behind `inference.vllm.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
|
||||
|
||||
@@ -98,35 +96,31 @@ Parallelism configuration is the same as the single-node deployment. The shape i
|
||||
type = "multi_node"
|
||||
num_nodes = 2
|
||||
|
||||
[inference]
|
||||
[inference.vllm]
|
||||
model = "PrimeIntellect/INTELLECT-3"
|
||||
|
||||
[inference.parallel]
|
||||
tp = 2
|
||||
dp = 4
|
||||
tensor_parallel_size = 2
|
||||
data_parallel_size = 4
|
||||
```
|
||||
|
||||
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a single global router running on the first inference node, fronting the per-rank endpoints of all replicas — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[inference.router]` block. You can read more about the supported routing options in the [router](#router) section.
|
||||
This configuration will run 2 independent vLLM replicas, each with `tensor_parallel_size=2` and `data_parallel_size=4`. Routing is handled by a single global router running on the first inference node, fronting the per-rank endpoints of all replicas — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[inference.router]` block. 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`.
|
||||
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.vllm.enable_expert_parallel = true`.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 2
|
||||
|
||||
[inference]
|
||||
[inference.vllm]
|
||||
model = "PrimeIntellect/INTELLECT-3"
|
||||
enable_expert_parallel = true
|
||||
|
||||
[inference.parallel]
|
||||
tp = 2
|
||||
dp = 8
|
||||
tensor_parallel_size = 2
|
||||
data_parallel_size = 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`.
|
||||
This configuration will run 2 vLLM processes, each with `data_parallel_size_local = 4` and `tensor_parallel_size = 2` and expert parallelism spanning 2 nodes. The requests are again routed to these processes via the `vllm-router`.
|
||||
|
||||
## P/D Disaggregation
|
||||
|
||||
@@ -272,24 +266,27 @@ type = "disaggregated"
|
||||
These are role-specific and layer on top of [`env_vars`](configuration.md#environment-variables) shared by all inference processes regardless of role.
|
||||
|
||||
### 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.
|
||||
The `[inference.vllm]` section is a pass-through: every key is forwarded to the vLLM server under vLLM's own argument name, whether prime-rl types it or not. Anything `vllm serve` accepts can be set here.
|
||||
|
||||
```toml
|
||||
[inference.vllm_extra]
|
||||
[inference.vllm]
|
||||
headless = true
|
||||
max_num_seqs = 256
|
||||
```
|
||||
|
||||
On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (or `--vllm.max-num-seqs 256` for the standalone inference entrypoint); dict-valued arguments take a JSON string, e.g. `--vllm.compilation-config '{"cudagraph_mode": "NONE"}'`.
|
||||
|
||||
### 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`.
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`.
|
||||
|
||||
```toml
|
||||
[trainer]
|
||||
enable_router_replay = true # this will also auto-set the inference.enable_return_routed_experts = true
|
||||
enable_router_replay = true # this will also auto-set inference.vllm.enable_return_routed_experts = true
|
||||
|
||||
[inference]
|
||||
[inference.vllm]
|
||||
enable_return_routed_experts = true
|
||||
```
|
||||
|
||||
|
||||
+2
-2
@@ -10,7 +10,7 @@ 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 `/inference/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). You can read more in the dedicated [training documentation](training.md).
|
||||
- **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+, and LoRA. 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 ZMQ, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap the rollout link to the local filesystem (`rollout_transport.type = "filesystem"`) if you want rollouts persisted to disk. See [Scaling](scaling.md) for the deployment options.
|
||||
|
||||
@@ -41,5 +41,5 @@ The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into
|
||||
- **[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.
|
||||
- **[Advanced](advanced.md)** — Custom modeling, multimodal, LoRA, P/D inference.
|
||||
- **[Development](development.md)** — Test suite, pre-commit hooks, adding a new model.
|
||||
|
||||
+2
-2
@@ -38,7 +38,7 @@ The `rl`, `sft`, and `inference` entrypoints all accept a `[deployment]` block (
|
||||
uv run rl @ rl.toml \
|
||||
--deployment.num-infer-gpus 6 \
|
||||
--deployment.num-train-gpus 2 \
|
||||
--inference.parallel.dp 6
|
||||
--inference.vllm.data-parallel-size 6
|
||||
```
|
||||
|
||||
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
|
||||
@@ -144,7 +144,7 @@ Offloading optimizer states to CPU is enabled by default (`optim_cpu_offload = t
|
||||
optim_cpu_offload = true # already the default
|
||||
```
|
||||
|
||||
Mutually exclusive with `fsdp_cpu_offload`. Also incompatible with `trainer.max_concurrent_runs > 1` (multi-tenant training) — set `optim_cpu_offload = false` for multi-run. Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
|
||||
Mutually exclusive with `fsdp_cpu_offload`. Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
|
||||
|
||||
### LM Head Chunking
|
||||
|
||||
|
||||
+2
-2
@@ -37,7 +37,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover
|
||||
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
|
||||
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
|
||||
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
|
||||
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at the source's derived `serve.address`); only needed when running the orchestrator standalone. |
|
||||
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at a derived loopback address); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
|
||||
|
||||
## RL Trainer
|
||||
|
||||
@@ -103,7 +103,7 @@ Frozen models are declared inline on the algorithm, named where the model is use
|
||||
|
||||
```bash
|
||||
CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
--model.name <frozen-model> --server.port 8001
|
||||
--vllm.model <frozen-model> --server.port 8001
|
||||
```
|
||||
|
||||
The standalone `uv run sft` entrypoint is the more traditional SFT path — pure dataset-based, no orchestrator. Use the `sft` algorithm only when you want a frozen model to generate the supervision on the fly.
|
||||
|
||||
@@ -200,15 +200,13 @@ model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp.
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
tensor_parallel_size = 8
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -142,15 +142,13 @@ rollout = 3600
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
tensor_parallel_size = 8
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -197,15 +197,13 @@ id = "terminal-bench-2-v1"
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp.
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
tensor_parallel_size = 8
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -6,22 +6,9 @@
|
||||
|
||||
output_dir = "/shared/outputs/glm5.2-16node-llmd"
|
||||
|
||||
enable_expert_parallel = true
|
||||
gpu_memory_utilization = 0.75
|
||||
enable_eplb = false
|
||||
use_deep_gemm = true
|
||||
enable_fp32_lm_head = true
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-5.2-FP8"
|
||||
max_model_len = 91000
|
||||
tool_call_parser = "glm47"
|
||||
reasoning_parser = "glm45"
|
||||
|
||||
[vllm_extra]
|
||||
enable_ep_weight_filter = true
|
||||
safetensors_load_strategy = "prefetch"
|
||||
|
||||
[kv_cache_offload]
|
||||
type = "mooncake"
|
||||
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
|
||||
@@ -64,3 +51,14 @@ non_cached_tokens = 128
|
||||
[slurm]
|
||||
job_name = "glm5.2-16node-llmd"
|
||||
partition = "all"
|
||||
|
||||
[vllm]
|
||||
model = "zai-org/GLM-5.2-FP8"
|
||||
max_model_len = 91000
|
||||
tool_call_parser = "glm47"
|
||||
reasoning_parser = "glm45"
|
||||
gpu_memory_utilization = 0.75
|
||||
enable_expert_parallel = true
|
||||
enable_eplb = false
|
||||
enable_ep_weight_filter = true
|
||||
safetensors_load_strategy = "prefetch"
|
||||
|
||||
@@ -1,12 +1,4 @@
|
||||
enable_expert_parallel = true
|
||||
enable_eplb = false
|
||||
use_deep_gemm = true
|
||||
gpu_memory_utilization = 0.85
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-5-FP8"
|
||||
tool_call_parser = "auto"
|
||||
reasoning_parser = "glm45"
|
||||
|
||||
[deployment]
|
||||
type = "disaggregated"
|
||||
@@ -17,3 +9,11 @@ gpus_per_node = 8
|
||||
[slurm]
|
||||
job_name = "glm5"
|
||||
partition = "cluster"
|
||||
|
||||
[vllm]
|
||||
model = "zai-org/GLM-5-FP8"
|
||||
tool_call_parser = "auto"
|
||||
reasoning_parser = "glm45"
|
||||
gpu_memory_utilization = 0.85
|
||||
enable_expert_parallel = true
|
||||
enable_eplb = false
|
||||
|
||||
@@ -48,7 +48,6 @@ num_decode_replicas = 1
|
||||
"max_num_batched_tokens" = 96
|
||||
"max_num_seqs" = 96
|
||||
|
||||
|
||||
[inference.router]
|
||||
type = "llm-d"
|
||||
|
||||
@@ -66,6 +65,16 @@ non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
|
||||
"kv-cache-utilization-scorer" = 4.0
|
||||
"queue-scorer" = 3.0
|
||||
|
||||
[inference.vllm]
|
||||
model = "zai-org/GLM-5.1-FP8"
|
||||
max_model_len = 131072
|
||||
tool_call_parser = "glm47"
|
||||
reasoning_parser = "glm45"
|
||||
gpu_memory_utilization = 0.75
|
||||
enable_expert_parallel = true
|
||||
enable_eplb = false
|
||||
enable_ep_weight_filter = true
|
||||
safetensors_load_strategy = "prefetch"
|
||||
[slurm]
|
||||
job_name = "glm5-llmd"
|
||||
partition = "all" # FILL IN: set to your cluster's partition
|
||||
@@ -118,7 +127,6 @@ temperature = 1.0
|
||||
[orchestrator.train.sampling.extra_body.chat_template_kwargs]
|
||||
clear_thinking = false
|
||||
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "r2e"
|
||||
|
||||
@@ -133,25 +141,10 @@ type = "prime"
|
||||
labels = ["glm5-llmd"]
|
||||
|
||||
[inference]
|
||||
enable_expert_parallel = true
|
||||
# <0.80 because glm5 layers are too large for 0.85
|
||||
gpu_memory_utilization = 0.75
|
||||
enable_eplb = false
|
||||
use_deep_gemm = true
|
||||
enable_fp32_lm_head = true
|
||||
|
||||
[inference.model]
|
||||
name = "zai-org/GLM-5.1-FP8"
|
||||
max_model_len = 131072
|
||||
tool_call_parser = "glm47"
|
||||
reasoning_parser = "glm45"
|
||||
|
||||
# Speed up GLM-5.1 weight load: EP weight filtering + safetensors prefetch.
|
||||
[inference.vllm_extra]
|
||||
enable_ep_weight_filter = true
|
||||
safetensors_load_strategy = "prefetch"
|
||||
|
||||
# Mooncake distributed CPU KV store: 1TB/node shared pool across all inference nodes.
|
||||
[inference.kv_cache_offload]
|
||||
type = "mooncake"
|
||||
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
|
||||
|
||||
@@ -23,10 +23,15 @@ type = "disaggregated"
|
||||
prefill_nodes_per_replica = 4
|
||||
decode_nodes_per_replica = 4
|
||||
|
||||
[inference.vllm]
|
||||
model = "zai-org/GLM-5-FP8"
|
||||
tool_call_parser = "glm47"
|
||||
gpu_memory_utilization = 0.80
|
||||
enable_expert_parallel = true
|
||||
enable_eplb = false
|
||||
[slurm]
|
||||
job_name = "glm5-pd-disag"
|
||||
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
|
||||
@@ -58,7 +63,6 @@ type = "adamw"
|
||||
lr = 1e-6
|
||||
weight_decay = 0.1
|
||||
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 4096
|
||||
group_size = 16
|
||||
@@ -89,12 +93,6 @@ type = "gibberish"
|
||||
enforce = true
|
||||
|
||||
[inference]
|
||||
enable_expert_parallel = true
|
||||
# we need <0.85 bc glm5 layers are too large for 0.85
|
||||
gpu_memory_utilization = 0.80
|
||||
enable_eplb = false
|
||||
use_deep_gemm = true
|
||||
|
||||
[inference.model]
|
||||
name = "zai-org/GLM-5-FP8"
|
||||
tool_call_parser = "glm47"
|
||||
|
||||
@@ -151,9 +151,7 @@ id = "null"
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -48,7 +48,6 @@ batch_size = 2048
|
||||
oversampling_factor = 2
|
||||
max_off_policy_steps = 16
|
||||
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "swe"
|
||||
|
||||
@@ -78,9 +77,7 @@ id = "bash"
|
||||
type = "prime"
|
||||
labels = ["minimax-swe", "swe-bench-verified"]
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
|
||||
# PrimeIntellect/MiniMax-M2.5-bf16 — template-identical to MiniMaxAI/MiniMax-M2.5 (mapped).
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
[orchestrator.renderer]
|
||||
name = "minimax-m2"
|
||||
|
||||
@@ -122,13 +122,11 @@ labels = ["nemotron-3-super-swe"]
|
||||
rollout = 3600
|
||||
|
||||
[inference]
|
||||
# vLLM disables prefix caching by default for hybrid-Mamba models; SWE turns share long prefixes.
|
||||
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
enable_prefix_caching = true
|
||||
enable_expert_parallel = true
|
||||
enable_return_routed_experts = true
|
||||
# vLLM disables prefix caching by default for hybrid-Mamba models; SWE turns share long prefixes.
|
||||
enable_prefix_caching = true
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
|
||||
@@ -75,5 +75,5 @@ id = "null"
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -75,5 +75,5 @@ id = "bash"
|
||||
type = "prime"
|
||||
labels = ["qwen30b-swe", "swe-bench-verified"]
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -51,11 +51,9 @@ id = "null"
|
||||
type = "modal"
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
|
||||
[inference.model]
|
||||
[inference.vllm]
|
||||
max_model_len = 32768
|
||||
|
||||
[inference.parallel]
|
||||
dp = 2
|
||||
tp = 4
|
||||
data_parallel_size = 2
|
||||
tensor_parallel_size = 4
|
||||
gpu_memory_utilization = 0.85
|
||||
|
||||
@@ -32,7 +32,7 @@ We use non-default settings to balance the difficulty: 3 fixed turns (instead of
|
||||
Start the inference server:
|
||||
```bash
|
||||
# In the `Inference` pane
|
||||
uv run inference --enable-lora --model.name Qwen/Qwen3-4B-Instruct-2507
|
||||
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507
|
||||
```
|
||||
|
||||
Evaluate the base model:
|
||||
@@ -110,7 +110,7 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetS
|
||||
Let's see how our final RL checkpoint performs on the eval set.
|
||||
```bash
|
||||
# In the `Inference` pane
|
||||
uv run inference --enable-lora --model.name PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
|
||||
uv run inference --vllm.enable-lora --vllm.model PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
|
||||
```
|
||||
|
||||
```bash
|
||||
|
||||
@@ -49,10 +49,8 @@ type = "subprocess"
|
||||
[trainer.model]
|
||||
seq_len = 16384
|
||||
|
||||
[inference.model]
|
||||
[inference.vllm]
|
||||
max_model_len = 8192
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -22,7 +22,7 @@ Let's check how well `Qwen3-0.6B` does out-of-the-box on the `reverse-text` envi
|
||||
|
||||
```bash
|
||||
# Run this in the `Inference` pane
|
||||
uv run inference --model.name Qwen/Qwen3-0.6B
|
||||
uv run inference --vllm.model Qwen/Qwen3-0.6B
|
||||
```
|
||||
|
||||
```bash
|
||||
@@ -95,7 +95,7 @@ Let's see how our final RL checkpoints perform on the `reverse-text` environment
|
||||
|
||||
```bash
|
||||
# Run this in the `Inference` pane
|
||||
uv run inference --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
|
||||
uv run inference --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
|
||||
```
|
||||
|
||||
```bash
|
||||
@@ -210,7 +210,7 @@ kubectl exec -it my-exp-trainer-0 -- bash
|
||||
|
||||
# If inference server isn't running with the RL model, start it in another terminal:
|
||||
kubectl exec -it my-exp-inference-0 -- bash
|
||||
uv run inference --model.name /data/outputs/weights/step_20
|
||||
uv run inference --vllm.model /data/outputs/weights/step_20
|
||||
|
||||
# Back in trainer pod, run evaluation
|
||||
uv run eval reverse-text-v1 --harness.id null \
|
||||
|
||||
@@ -70,7 +70,7 @@ Start the inference server:
|
||||
|
||||
```bash
|
||||
# In the `Inference` pane
|
||||
uv run inference --enable-lora --model.name Qwen/Qwen3-4B-Instruct-2507 --model.tool_call_parser hermes
|
||||
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507 --vllm.tool-call-parser hermes
|
||||
```
|
||||
|
||||
Evaluate the base model:
|
||||
@@ -114,7 +114,7 @@ Evaluate your trained model:
|
||||
|
||||
```bash
|
||||
# In the `Inference` pane
|
||||
uv run inference --enable-lora --model.name <user>/Qwen3-4B-Instruct-WikiSearch-RL --model.tool_call_parser hermes
|
||||
uv run inference --vllm.enable-lora --vllm.model <user>/Qwen3-4B-Instruct-WikiSearch-RL --vllm.tool-call-parser hermes
|
||||
```
|
||||
|
||||
```bash
|
||||
|
||||
@@ -40,10 +40,6 @@ name = "qwen3-4b-wiki-search"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.pre_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
enforce = true
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
|
||||
@@ -56,7 +52,11 @@ id = "null"
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[[orchestrator.pre_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
enforce = true
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference.model]
|
||||
[inference.vllm]
|
||||
tool_call_parser = "hermes"
|
||||
|
||||
@@ -22,7 +22,7 @@ Before training, we want to get a baseline score and test how well `Qwen3-1.7B`
|
||||
|
||||
```bash
|
||||
# Run this in the `Inference` pane
|
||||
uv run inference --model.name Qwen/Qwen3-1.7B
|
||||
uv run inference --vllm.model Qwen/Qwen3-1.7B
|
||||
```
|
||||
|
||||
Then, use the `eval` entrypoint to evaluate the model in the `wordle` environment. We evaluate on the 20 evaluation examples which are distinct words not appearing in the training set of the environment. We constrain the response length to 1024 tokens as this should be more than enough to play a full game.
|
||||
@@ -98,7 +98,7 @@ Let's see how our final RL checkpoint performs on the eval set.
|
||||
|
||||
```bash
|
||||
# Run this in the `Inference` pane
|
||||
uv run inference --model.name PrimeIntellect/Qwen3-1.7B-Wordle-RL
|
||||
uv run inference --vllm.model PrimeIntellect/Qwen3-1.7B-Wordle-RL
|
||||
```
|
||||
|
||||
```bash
|
||||
|
||||
@@ -35,9 +35,7 @@ max_completion_tokens = 1024
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
|
||||
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
|
||||
[inference.vllm]
|
||||
data_parallel_size = 6
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
@@ -11,7 +11,7 @@ image:
|
||||
orchestrator:
|
||||
enabled: true
|
||||
autoStart: true
|
||||
command: "uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs/run_default --client.base-url $INFERENCE_URL ; sleep infinity"
|
||||
command: "uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL ; sleep infinity"
|
||||
resources:
|
||||
requests:
|
||||
memory: "1Gi"
|
||||
|
||||
@@ -59,9 +59,6 @@ spec:
|
||||
fieldPath: metadata.namespace
|
||||
- name: STATEFUL_REPLICAS
|
||||
value: "{{ .Values.orchestrator.replicas }}"
|
||||
- name: HEADLESS_SERVICE
|
||||
value: "{{ .Release.Name }}-orchestrator-headless.{{ .Values.namespace }}.svc.cluster.local"
|
||||
- name: INFERENCE_URL
|
||||
{{- $releaseName := .Release.Name }}
|
||||
{{- $namespace := .Values.namespace }}
|
||||
{{- $port := int .Values.inference.service.port }}
|
||||
@@ -71,6 +68,9 @@ spec:
|
||||
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
|
||||
{{- $urls = append $urls $url }}
|
||||
{{- end }}
|
||||
- name: INFERENCE_URL
|
||||
value: {{ first $urls | quote }}
|
||||
- name: ADMIN_INFERENCE_URLS
|
||||
value: {{ $urls | join "," | quote }}
|
||||
{{- with .Values.orchestrator.env }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
@@ -163,8 +163,6 @@ spec:
|
||||
fieldPath: metadata.namespace
|
||||
- name: STATEFUL_REPLICAS
|
||||
value: "{{ .Values.inference.replicas }}"
|
||||
- name: HEADLESS_SERVICE
|
||||
value: "{{ .Release.Name }}-inference-headless.{{ .Values.namespace }}.svc.cluster.local"
|
||||
{{- with .Values.inference.env }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
@@ -294,13 +292,10 @@ spec:
|
||||
fieldPath: metadata.namespace
|
||||
- name: STATEFUL_REPLICAS
|
||||
value: "{{ .Values.trainer.replicas }}"
|
||||
- name: HEADLESS_SERVICE
|
||||
value: "{{ .Release.Name }}-trainer-headless.{{ .Values.namespace }}.svc.cluster.local"
|
||||
{{- if .Values.trainer.pytorchCudaAllocConf }}
|
||||
- name: PYTORCH_CUDA_ALLOC_CONF
|
||||
value: {{ .Values.trainer.pytorchCudaAllocConf | quote }}
|
||||
{{- end }}
|
||||
- name: INFERENCE_URL
|
||||
{{- $releaseName := .Release.Name }}
|
||||
{{- $namespace := .Values.namespace }}
|
||||
{{- $port := int .Values.inference.service.port }}
|
||||
@@ -310,6 +305,9 @@ spec:
|
||||
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
|
||||
{{- $urls = append $urls $url }}
|
||||
{{- end }}
|
||||
- name: INFERENCE_URL
|
||||
value: {{ first $urls | quote }}
|
||||
- name: ADMIN_INFERENCE_URLS
|
||||
value: {{ $urls | join "," | quote }}
|
||||
{{- with .Values.trainer.env }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
|
||||
@@ -28,9 +28,12 @@ orchestrator:
|
||||
|
||||
# Auto-start configuration (set to false to use sleep infinity for debugging)
|
||||
autoStart: false
|
||||
# Example command - use $INFERENCE_URL directly (comma-separated list of all inference server URLs)
|
||||
command: "" # e.g., 'uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs/run_default --client.base-url $INFERENCE_URL'
|
||||
# $INFERENCE_URL is auto-set to: 'http://<release>-inference-0...:8000/v1,http://<release>-inference-1...:8000/v1,...'
|
||||
# Example command - use $INFERENCE_URL directly (the first inference server URL)
|
||||
command: "" # e.g., 'uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL'
|
||||
# $INFERENCE_URL is auto-set to 'http://<release>-inference-0...:8000/v1'. With more than one
|
||||
# inference replica, put a router in front and point --client.base-url at it; admin operations
|
||||
# (weight updates, health checks) fan out to every replica via
|
||||
# --client.admin-base-url $ADMIN_INFERENCE_URLS (comma-separated list of all replica URLs).
|
||||
|
||||
resources:
|
||||
requests:
|
||||
|
||||
@@ -7,10 +7,10 @@ requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"pydantic>=1.10.13",
|
||||
"prime-pydantic-config>=0.4.2",
|
||||
"renderers>=0.1.9.dev10",
|
||||
"renderers>=0.1.9",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.2.2.dev76",
|
||||
"verifiers>=0.3.0",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
|
||||
@@ -58,7 +58,7 @@ class FrozenModelConfig(ClientConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_explicit_endpoint(self):
|
||||
if "base_url" not in self.model_fields_set and not self.is_elastic:
|
||||
if "base_url" not in self.model_fields_set:
|
||||
raise ValueError(
|
||||
"a frozen model reference needs base_url — frozen models are externally "
|
||||
"hosted; prime-rl only ever hosts the trainable policy."
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import json
|
||||
from argparse import Namespace
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic import ConfigDict, Field, model_validator
|
||||
from pydantic_config import BaseConfig
|
||||
|
||||
from prime_rl.configs.shared import BaseModelConfig, EnvVars, LogConfig, SlurmConfig
|
||||
from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
|
||||
from prime_rl.configs.shared import EnvVars, LogConfig, SlurmConfig
|
||||
from prime_rl.utils.config import find_package_resource
|
||||
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
|
||||
|
||||
# TODO: Set thinking/ solution budget
|
||||
@@ -23,61 +24,192 @@ class ServerConfig(BaseConfig):
|
||||
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. With Kubernetes liveness probes, keep the probe ``timeoutSeconds`` at least this high."""
|
||||
|
||||
|
||||
class ParallelConfig(BaseConfig):
|
||||
tp: int = 1
|
||||
"""Tensor parallel size. Forwarded to vLLM as ``--tensor-parallel-size``."""
|
||||
# Valid vLLM max_lora_rank values (`vllm.config.lora.MaxLoRARanks`), excluding 1 so
|
||||
# tiny adapters round up to 8. Hardcoded rather than imported: prime-rl-configs does
|
||||
# not depend on vLLM, and importing it costs seconds in every config-parsing process.
|
||||
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
|
||||
|
||||
dp: int = Field(1, ge=1)
|
||||
"""Data parallel size. Forwarded to vLLM as ``--data-parallel-size``."""
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"tp={self.tp} dp={self.dp}"
|
||||
# vLLM all2all backend options for expert-parallel deployments.
|
||||
All2AllBackend = Literal[
|
||||
"allgather_reducescatter",
|
||||
"deepep_high_throughput",
|
||||
"deepep_low_latency",
|
||||
"flashinfer_nvlink_one_sided",
|
||||
"flashinfer_nvlink_two_sided",
|
||||
]
|
||||
|
||||
|
||||
class ModelConfig(BaseModelConfig):
|
||||
"""Configures the inference model. Most arguments are passed directly to the vLLM LLM class (https://docs.vllm.ai/en/latest/api/vllm.LLM.html).
|
||||
class VllmConfig(BaseConfig):
|
||||
"""Arguments forwarded to the vLLM server, under vLLM's own argument names
|
||||
(https://docs.vllm.ai/en/latest/configuration/engine_args.html).
|
||||
|
||||
The fields below are the arguments prime-rl types, defaults, or reads back;
|
||||
any other vLLM argument can be set as well (``[inference.vllm] max_num_seqs = 256``
|
||||
or ``--vllm.max-num-seqs 256``) and passes through to the server verbatim.
|
||||
|
||||
Parser fields (``tool_call_parser``, ``reasoning_parser``) default to ``"auto"``,
|
||||
which resolves to a concrete parser name at validation time from the model name.
|
||||
Set to ``None`` to disable.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
|
||||
model: str = "Qwen/Qwen3-0.6B"
|
||||
"""HF model name or local path."""
|
||||
|
||||
dtype: Literal["auto", "float16", "bfloat16", "float32"] = "auto"
|
||||
"""dtype for model weights and activations. ``auto`` uses FP16 for FP32/FP16 models and BF16 for BF16 models. Forwarded as ``--dtype``."""
|
||||
"""dtype for model weights and activations. ``auto`` uses FP16 for FP32/FP16 models and BF16 for BF16 models."""
|
||||
|
||||
max_model_len: int | None = None
|
||||
"""Maximum model context length. If None, uses the model config's value. Forwarded as ``--max-model-len``."""
|
||||
"""Maximum model context length. If None, uses the model config's value."""
|
||||
|
||||
enforce_eager: bool = False
|
||||
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance. Forwarded as ``--enforce-eager``."""
|
||||
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance."""
|
||||
|
||||
trust_remote_code: bool = False
|
||||
"""Trust remote code. Forwarded to vLLM engine init."""
|
||||
"""Trust remote code when loading the model."""
|
||||
|
||||
chat_template: str | None = None
|
||||
"""Chat template — a Jinja2 template string or path to a template file. Forwarded as ``--chat-template``. If None, uses the model's default."""
|
||||
"""Chat template — a Jinja2 template string or path to a template file. If None, uses the model's default."""
|
||||
|
||||
tool_call_parser: str | None = "auto"
|
||||
"""Tool-call parser. Forwarded as ``--tool-call-parser``. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
|
||||
"""Tool-call parser. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
|
||||
|
||||
reasoning_parser: str | None = "auto"
|
||||
"""Parser for extracting reasoning content from model outputs. Forwarded as ``--reasoning-parser``. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
|
||||
"""Parser for extracting reasoning content from model outputs. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
|
||||
|
||||
rope_scaling: dict[str, Any] | str | None = None
|
||||
"""RoPE scaling configuration as a dict (e.g. ``{rope_type="yarn", factor=4.0, original_max_position_embeddings=32768}``). Forwarded as ``--rope-scaling``."""
|
||||
"""RoPE scaling configuration as a dict (e.g. ``{rope_type="yarn", factor=4.0, original_max_position_embeddings=32768}``)."""
|
||||
|
||||
tensor_parallel_size: int = 1
|
||||
"""Tensor parallel size."""
|
||||
|
||||
data_parallel_size: int = Field(1, ge=1)
|
||||
"""Data parallel size."""
|
||||
|
||||
data_parallel_size_local: int | None = Field(None, ge=1)
|
||||
"""Data parallel replicas to run on this node."""
|
||||
|
||||
data_parallel_rpc_port: int = Field(13345, ge=1, le=65535)
|
||||
"""RPC port for data parallel communication."""
|
||||
|
||||
api_server_count: int = Field(1, ge=0)
|
||||
"""API servers to run. Set to 0 for headless mode."""
|
||||
|
||||
seed: int = 0
|
||||
"""Seed the inference components."""
|
||||
|
||||
gpu_memory_utilization: float = 0.9
|
||||
"""GPU memory utilization."""
|
||||
|
||||
enable_prefix_caching: bool | None = None
|
||||
"""Enable prefix caching."""
|
||||
|
||||
quantization: str | None = None
|
||||
"""Online inference quantization method. If None, vLLM infers it from the checkpoint."""
|
||||
|
||||
enable_lora: bool = False
|
||||
"""Enable LoRA."""
|
||||
|
||||
max_loras: int = 8
|
||||
"""Maximum number of LoRAs."""
|
||||
|
||||
# TODO: The default value is very high because our areal impl for lora isn't ideal
|
||||
# We add a lora with the same name instead of changing weights inplace
|
||||
# Because we dont cancel requests that are past max_async, these requests could be using a LoRA that gets unloaded which will crash the inference server
|
||||
max_cpu_loras: int = 100
|
||||
"""Maximum number of LoRAs on CPU."""
|
||||
|
||||
max_lora_rank: int | None = None
|
||||
"""Maximum LoRA rank. Rounded up to the nearest value vLLM accepts."""
|
||||
|
||||
lora_target_modules: list[str] | None = None
|
||||
"""LoRA target modules."""
|
||||
|
||||
enable_expert_parallel: bool = False
|
||||
"""Enable expert parallelism for MoE models."""
|
||||
|
||||
all2all_backend: All2AllBackend = "allgather_reducescatter"
|
||||
"""All-to-all backend for expert-parallel communication."""
|
||||
|
||||
enable_eplb: bool = False
|
||||
"""Enable expert parallel load balancer (EPLB)."""
|
||||
|
||||
enable_dbo: bool = False
|
||||
"""Enable dual batch overlap (DBO)."""
|
||||
|
||||
enable_return_routed_experts: bool = False
|
||||
"""Return routed experts in responses."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def parse_extra_values(cls, data: dict) -> dict:
|
||||
"""Normalize pass-through (untyped) entries: kebab-case keys become snake_case,
|
||||
and string values — which is how CLI overrides arrive — are JSON-parsed so
|
||||
``--vllm.max-num-seqs 256`` lands as an int and ``--vllm.compilation-config
|
||||
'{"cudagraph_mode": "NONE"}'`` as a dict. Non-JSON strings stay strings."""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
for key in [k for k in data if k not in cls.model_fields]:
|
||||
value = data.pop(key)
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
value = json.loads(value)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
data[key.replace("-", "_")] = value
|
||||
return data
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_resolve_parsers(self):
|
||||
"""Resolve ``"auto"`` parser values to concrete parser names from the model name.
|
||||
|
||||
Runs after ``RLConfig.auto_setup_shared_configs`` (mode=before) has
|
||||
propagated the shared ``[model] name`` into ``inference.model``, so the
|
||||
propagated the shared ``[model] name`` into ``inference.vllm``, so the
|
||||
name is set even when only the shared block specifies it.
|
||||
"""
|
||||
if self.tool_call_parser == "auto":
|
||||
self.tool_call_parser = resolve_tool_call_parser(self.name)
|
||||
self.tool_call_parser = resolve_tool_call_parser(self.model)
|
||||
if self.reasoning_parser == "auto":
|
||||
self.reasoning_parser = resolve_reasoning_parser(self.name)
|
||||
self.reasoning_parser = resolve_reasoning_parser(self.model)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_max_lora_rank(self):
|
||||
"""Auto-setup max_lora_rank by rounding up to the nearest valid vLLM value.
|
||||
|
||||
vLLM only accepts specific values for max_lora_rank: (1, 8, 16, 32, 64, 128, 256, 320, 512).
|
||||
This validator ensures that any configured rank is rounded up to the minimum valid value
|
||||
that can serve adapters of the requested rank.
|
||||
"""
|
||||
if self.max_lora_rank is not None:
|
||||
original_rank = self.max_lora_rank
|
||||
for valid_rank in VALID_VLLM_LORA_RANKS:
|
||||
if valid_rank >= self.max_lora_rank:
|
||||
self.max_lora_rank = valid_rank
|
||||
break
|
||||
else:
|
||||
raise ValueError(f"max_lora_rank={original_rank} exceeds vLLM maximum of {VALID_VLLM_LORA_RANKS[-1]}")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_api_server_count(self):
|
||||
"""
|
||||
Ensures that we have at least as many API servers as data parallel
|
||||
size. Unless LoRA is enabled, in which case only one API server is
|
||||
supported (vLLM limitation).
|
||||
"""
|
||||
if self.model_extra and self.model_extra.get("headless", False):
|
||||
self.api_server_count = 0
|
||||
return self
|
||||
|
||||
if "api_server_count" not in self.model_fields_set:
|
||||
min_api_server_count = self.data_parallel_size_local or self.data_parallel_size
|
||||
if self.api_server_count < min_api_server_count:
|
||||
self.api_server_count = min_api_server_count
|
||||
|
||||
if self.enable_lora:
|
||||
self.api_server_count = 1 # LoRA requires only one API server
|
||||
return self
|
||||
|
||||
|
||||
@@ -153,20 +285,6 @@ KVCacheOffloadConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
# Valid vLLM max_lora_rank values (from vllm/config/lora.py)
|
||||
# TODO: on newer vLLM, can import via `get_args(vllm.config.lora.MaxLoRARanks)`
|
||||
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
|
||||
|
||||
# vLLM all2all backend options for expert-parallel deployments.
|
||||
All2AllBackend = Literal[
|
||||
"allgather_reducescatter",
|
||||
"deepep_high_throughput",
|
||||
"deepep_low_latency",
|
||||
"flashinfer_nvlink_one_sided",
|
||||
"flashinfer_nvlink_two_sided",
|
||||
]
|
||||
|
||||
|
||||
# Known llm-d EPP scorer plugins (used to guard the ``scorers`` map against typos).
|
||||
KNOWN_SCORERS = frozenset(
|
||||
{
|
||||
@@ -325,10 +443,8 @@ class InferenceConfig(BaseConfig):
|
||||
backend_port: int = 8100
|
||||
"""Port for the vLLM engine(s) behind the router. Defaults to ``server.port + 100``. Multi-node deployments start one engine per local DP rank at ``backend_port + rank``."""
|
||||
|
||||
model: ModelConfig = Field(default_factory=ModelConfig)
|
||||
|
||||
parallel: ParallelConfig = ParallelConfig()
|
||||
"""Multi-node and multi-GPU parallelism (TP, DP, PP)."""
|
||||
vllm: VllmConfig = Field(default_factory=VllmConfig)
|
||||
"""vLLM server arguments, under vLLM's own argument names. Unknown fields pass through verbatim."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
"""Logging configuration."""
|
||||
@@ -336,57 +452,6 @@ class InferenceConfig(BaseConfig):
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for the inference server process(es). Merged on top of the launcher defaults."""
|
||||
|
||||
enable_lora: bool = False
|
||||
"""Enable LoRA. Forwarded as ``--enable-lora``."""
|
||||
|
||||
max_loras: int = 8
|
||||
"""Maximum number of LoRAs. Forwarded as ``--max-loras``."""
|
||||
|
||||
# TODO: The default value is very high because our areal impl for lora isn't ideal
|
||||
# We add a lora with the same name instead of changing weights inplace
|
||||
# Because we dont cancel requests that are past max_async, these requests could be using a LoRA that gets unloaded which will crash the inference server
|
||||
max_cpu_loras: int = 100
|
||||
"""Maximum number of LoRAs on CPU. Forwarded as ``--max-cpu-loras``."""
|
||||
|
||||
max_lora_rank: int | None = None
|
||||
"""Maximum LoRA rank. Forwarded as ``--max-lora-rank``."""
|
||||
|
||||
lora_target_modules: list[str] | None = None
|
||||
"""LoRA target modules. Forwarded as ``--lora-target-modules``."""
|
||||
|
||||
enable_prefix_caching: bool | None = None
|
||||
"""Enable prefix caching. Forwarded as ``--enable-prefix-caching``."""
|
||||
|
||||
gpu_memory_utilization: float = 0.9
|
||||
"""GPU memory utilization. Forwarded as ``--gpu-memory-utilization``."""
|
||||
|
||||
quantization: str | None = None
|
||||
"""Online inference quantization method. Forwarded as ``--quantization``."""
|
||||
|
||||
api_server_count: int = Field(1, ge=0)
|
||||
"""API servers to run. Forwarded as ``--api-server-count``. Set to 0 for headless mode."""
|
||||
|
||||
data_parallel_size_local: int | None = Field(None, ge=1)
|
||||
"""Data parallel replicas to run on this node. Forwarded as ``--data-parallel-size-local``."""
|
||||
|
||||
data_parallel_rpc_port: int = Field(13345, ge=1, le=65535)
|
||||
"""RPC port for data parallel communication. Forwarded as ``--data-parallel-rpc-port``."""
|
||||
|
||||
seed: int = 0
|
||||
"""Seed the inference components. Forwarded as ``--seed``."""
|
||||
|
||||
enable_expert_parallel: bool = False
|
||||
"""Enable expert parallelism for MoE models. Forwarded as ``--enable-expert-parallel``."""
|
||||
|
||||
all2all_backend: All2AllBackend = "allgather_reducescatter"
|
||||
"""All-to-all backend for expert-parallel communication. Forwarded as ``--all2all-backend``."""
|
||||
|
||||
enable_eplb: bool = False
|
||||
"""Enable expert parallel load balancer (EPLB). Forwarded as ``--enable-eplb``."""
|
||||
|
||||
enable_dbo: bool = False
|
||||
"""Enable dual batch overlap (DBO). Forwarded as ``--enable-dbo``."""
|
||||
|
||||
use_deep_gemm: bool = False
|
||||
"""Enable vLLM DeepGEMM FP8 kernels ``VLLM_USE_DEEP_GEMM=1``. Only works with block-wise FP8 quantization (e.g. GLM-5-FP8)."""
|
||||
|
||||
@@ -398,18 +463,12 @@ class InferenceConfig(BaseConfig):
|
||||
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 = 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."""
|
||||
|
||||
enable_fp32_router_logits: bool = True
|
||||
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x) by setting ``out_dtype=float32`` on the gate: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented as a monkey-patch over vLLM's DeepseekV2MoE, activated by setting ``additional_config["fp32_router_logits"] = True`` on the vLLM config."""
|
||||
|
||||
vllm_extra: dict[str, Any] = {}
|
||||
"""Extra arguments forwarded to vLLM. Applied as attributes on the vLLM namespace after config translation."""
|
||||
|
||||
# Launcher-only fields
|
||||
|
||||
deployment: InferenceDeploymentConfig = SingleNodeInferenceDeploymentConfig()
|
||||
@@ -432,7 +491,7 @@ class InferenceConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def validate_llmd_no_routed_experts(self):
|
||||
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
|
||||
if self.router is not None and self.router.type == "llm-d" and self.enable_return_routed_experts:
|
||||
if self.router is not None and self.router.type == "llm-d" and self.vllm.enable_return_routed_experts:
|
||||
raise ValueError(
|
||||
"The llm-d router backend does not support routed-expert return "
|
||||
"(enable_return_routed_experts): it breaks P/D and is unverified for multi-node. "
|
||||
@@ -458,10 +517,10 @@ class InferenceConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_kv_cache_offload(self):
|
||||
if self.kv_cache_offload is not None:
|
||||
if self.enable_prefix_caching is False:
|
||||
raise ValueError("KV cache offloading requires inference.enable_prefix_caching to be true.")
|
||||
if "enable_prefix_caching" not in self.model_fields_set:
|
||||
self.enable_prefix_caching = True
|
||||
if self.vllm.enable_prefix_caching is False:
|
||||
raise ValueError("KV cache offloading requires inference.vllm.enable_prefix_caching to be true.")
|
||||
if "enable_prefix_caching" not in self.vllm.model_fields_set:
|
||||
self.vllm.enable_prefix_caching = True
|
||||
|
||||
return self
|
||||
|
||||
@@ -470,19 +529,19 @@ class InferenceConfig(BaseConfig):
|
||||
"""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:
|
||||
self.enable_eplb = False
|
||||
if "enable_expert_parallel" not in self.vllm.model_fields_set:
|
||||
self.vllm.enable_expert_parallel = True
|
||||
if "enable_eplb" not in self.vllm.model_fields_set:
|
||||
self.vllm.enable_eplb = False
|
||||
gpus_per_node = self.deployment.gpus_per_node
|
||||
tp = self.parallel.tp
|
||||
tp = self.vllm.tensor_parallel_size
|
||||
dp_per_node = gpus_per_node // tp
|
||||
if self.data_parallel_size_local is None:
|
||||
self.data_parallel_size_local = dp_per_node
|
||||
if self.parallel.dp == 1:
|
||||
self.parallel.dp = dp_per_node
|
||||
if self.api_server_count == 1:
|
||||
self.api_server_count = dp_per_node
|
||||
if self.vllm.data_parallel_size_local is None:
|
||||
self.vllm.data_parallel_size_local = dp_per_node
|
||||
if self.vllm.data_parallel_size == 1:
|
||||
self.vllm.data_parallel_size = dp_per_node
|
||||
if self.vllm.api_server_count == 1:
|
||||
self.vllm.api_server_count = dp_per_node
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -493,44 +552,6 @@ class InferenceConfig(BaseConfig):
|
||||
self.slurm.template_path = templates_dir / "inference.sbatch.j2"
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_max_lora_rank(self):
|
||||
"""Auto-setup max_lora_rank by rounding up to the nearest valid vLLM value.
|
||||
|
||||
vLLM only accepts specific values for max_lora_rank: (1, 8, 16, 32, 64, 128, 256, 320, 512).
|
||||
This validator ensures that any configured rank is rounded up to the minimum valid value
|
||||
that can serve adapters of the requested rank.
|
||||
"""
|
||||
if self.max_lora_rank is not None:
|
||||
original_rank = self.max_lora_rank
|
||||
for valid_rank in VALID_VLLM_LORA_RANKS:
|
||||
if valid_rank >= self.max_lora_rank:
|
||||
self.max_lora_rank = valid_rank
|
||||
break
|
||||
else:
|
||||
raise ValueError(f"max_lora_rank={original_rank} exceeds vLLM maximum of {VALID_VLLM_LORA_RANKS[-1]}")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_api_server_count(self):
|
||||
"""
|
||||
Ensures that we have at least as many API servers as data parallel
|
||||
size. Unless LoRA is enabled, in which case only one API server is
|
||||
supported (vLLM limitation).
|
||||
"""
|
||||
if self.vllm_extra.get("headless", False):
|
||||
self.api_server_count = 0
|
||||
return self
|
||||
|
||||
if "api_server_count" not in self.model_fields_set:
|
||||
min_api_server_count = self.data_parallel_size_local or self.parallel.dp
|
||||
if self.api_server_count < min_api_server_count:
|
||||
self.api_server_count = min_api_server_count
|
||||
|
||||
if self.enable_lora:
|
||||
self.api_server_count = 1 # LoRA requires only one API server
|
||||
return self
|
||||
|
||||
def build_kv_transfer_config(self) -> dict[str, Any] | None:
|
||||
"""Build the single vLLM ``kv_transfer_config`` from the transfer + offload connectors.
|
||||
|
||||
@@ -560,90 +581,49 @@ class InferenceConfig(BaseConfig):
|
||||
"kv_connector_extra_config": {"connectors": connectors},
|
||||
}
|
||||
|
||||
def to_vllm(self) -> Namespace:
|
||||
"""Convert InferenceConfig to vLLM-compatible Namespace."""
|
||||
namespace = Namespace()
|
||||
to_vllm = {
|
||||
"server.host": "host",
|
||||
"server.port": "port",
|
||||
"server.liveness_timeout_seconds": "liveness_timeout_seconds",
|
||||
"model.name": "model",
|
||||
"model.dtype": "dtype",
|
||||
"model.max_model_len": "max_model_len",
|
||||
"model.enforce_eager": "enforce_eager",
|
||||
"model.trust_remote_code": "trust_remote_code",
|
||||
"model.chat_template": "chat_template",
|
||||
"model.tool_call_parser": "tool_call_parser",
|
||||
"model.reasoning_parser": "reasoning_parser",
|
||||
"model.rope_scaling": "rope_scaling",
|
||||
"parallel.tp": "tensor_parallel_size",
|
||||
"parallel.dp": "data_parallel_size",
|
||||
"data_parallel_size_local": "data_parallel_size_local",
|
||||
"data_parallel_rpc_port": "data_parallel_rpc_port",
|
||||
"enable_lora": "enable_lora",
|
||||
"enable_prefix_caching": "enable_prefix_caching",
|
||||
"max_loras": "max_loras",
|
||||
"max_cpu_loras": "max_cpu_loras",
|
||||
"max_lora_rank": "max_lora_rank",
|
||||
"lora_target_modules": "lora_target_modules",
|
||||
"gpu_memory_utilization": "gpu_memory_utilization",
|
||||
"quantization": "quantization",
|
||||
"api_server_count": "api_server_count",
|
||||
"enable_return_routed_experts": "enable_return_routed_experts",
|
||||
"enable_expert_parallel": "enable_expert_parallel",
|
||||
"all2all_backend": "all2all_backend",
|
||||
"enable_eplb": "enable_eplb",
|
||||
"enable_dbo": "enable_dbo",
|
||||
"seed": "seed",
|
||||
}
|
||||
# Fields vLLM rejects as None — omitted from the namespace so vLLM applies its
|
||||
# own default (e.g. quantization is inferred from the checkpoint).
|
||||
_OMIT_IF_NONE = frozenset(
|
||||
{"chat_template", "tool_call_parser", "reasoning_parser", "lora_target_modules", "quantization", "rope_scaling"}
|
||||
)
|
||||
|
||||
for config_key, vllm_key in to_vllm.items():
|
||||
value = rgetattr(self, config_key.replace("-", "_"))
|
||||
rsetattr(namespace, vllm_key, value)
|
||||
def to_namespace(self) -> Namespace:
|
||||
"""Dump the server + vllm sections into a vLLM-compatible Namespace."""
|
||||
namespace = Namespace(
|
||||
host=self.server.host,
|
||||
port=self.server.port,
|
||||
liveness_timeout_seconds=self.server.liveness_timeout_seconds,
|
||||
)
|
||||
|
||||
# Set `logprobs_mode` to `processed_logprobs` by default
|
||||
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
|
||||
extra_fields = self.vllm.model_extra or {}
|
||||
for key in (*type(self.vllm).model_fields, *extra_fields):
|
||||
value = getattr(self.vllm, key)
|
||||
# None extras are dropped too: `--vllm.foo None` means "use vLLM's default".
|
||||
if value is None and (key in self._OMIT_IF_NONE or key in extra_fields):
|
||||
continue
|
||||
setattr(namespace, key, value)
|
||||
|
||||
# Auto tool choice is gated on a tool-call parser being resolved, unless
|
||||
# explicitly overridden.
|
||||
if "enable_auto_tool_choice" not in extra_fields:
|
||||
namespace.enable_auto_tool_choice = hasattr(namespace, "tool_call_parser")
|
||||
|
||||
# Default `logprobs_mode` to `processed_logprobs`
|
||||
if not hasattr(namespace, "logprobs_mode"):
|
||||
namespace.logprobs_mode = "processed_logprobs"
|
||||
|
||||
kv_transfer_config = self.build_kv_transfer_config()
|
||||
if kv_transfer_config is not None:
|
||||
rsetattr(namespace, "kv_transfer_config", kv_transfer_config)
|
||||
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.
|
||||
additional_config = getattr(namespace, "additional_config", None) or {}
|
||||
if self.enable_fp32_lm_head:
|
||||
existing = getattr(namespace, "additional_config", None) or {}
|
||||
existing["fp32_lm_head"] = True
|
||||
rsetattr(namespace, "additional_config", existing)
|
||||
additional_config["fp32_lm_head"] = True
|
||||
if self.enable_fp32_router_logits:
|
||||
existing = getattr(namespace, "additional_config", None) or {}
|
||||
existing["fp32_router_logits"] = True
|
||||
rsetattr(namespace, "additional_config", existing)
|
||||
|
||||
# Remove chat_template if not set (vLLM doesn't accept None)
|
||||
if namespace.chat_template is None:
|
||||
delattr(namespace, "chat_template")
|
||||
|
||||
# Remove tool_call_parser if not set (vLLM doesn't accept None) and gate
|
||||
# `enable_auto_tool_choice` on its presence.
|
||||
if namespace.tool_call_parser is None:
|
||||
delattr(namespace, "tool_call_parser")
|
||||
namespace.enable_auto_tool_choice = hasattr(namespace, "tool_call_parser")
|
||||
|
||||
# Remove reasoning_parser if not set (vLLM doesn't accept None)
|
||||
if namespace.reasoning_parser is None:
|
||||
delattr(namespace, "reasoning_parser")
|
||||
|
||||
# Remove lora_target_modules if not set (vLLM doesn't accept None)
|
||||
if hasattr(namespace, "lora_target_modules") and namespace.lora_target_modules is None:
|
||||
delattr(namespace, "lora_target_modules")
|
||||
|
||||
# Remove quantization if not set so vLLM can infer it from the checkpoint.
|
||||
if namespace.quantization is None:
|
||||
delattr(namespace, "quantization")
|
||||
|
||||
# Remove rope_scaling if not set (vLLM doesn't accept None)
|
||||
if hasattr(namespace, "rope_scaling"):
|
||||
if namespace.rope_scaling is None:
|
||||
delattr(namespace, "rope_scaling")
|
||||
additional_config["fp32_router_logits"] = True
|
||||
if additional_config:
|
||||
namespace.additional_config = additional_config
|
||||
|
||||
return namespace
|
||||
|
||||
@@ -4,7 +4,6 @@ from typing import Annotated, Any, Literal, TypeAlias
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import Field, SerializeAsAny, model_validator
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
from verifiers.v1.configs.serve import PoolConfig
|
||||
|
||||
from prime_rl.configs.algorithm import (
|
||||
AlgoConfig,
|
||||
@@ -26,11 +25,6 @@ from prime_rl.configs.trainer import TokenizerConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class OptimizerConfig(BaseConfig):
|
||||
lr: float = Field(1e-4, ge=0)
|
||||
"""Learning rate for this run (per-run override for multi-run training)."""
|
||||
|
||||
|
||||
class LoRAConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
"""LoRA adapter name. If None, auto-generated from rank and alpha."""
|
||||
@@ -123,21 +117,6 @@ class EvalSamplingConfig(BaseConfig):
|
||||
return args
|
||||
|
||||
|
||||
class ServeConfig(BaseConfig):
|
||||
"""The subset of verifiers' ``ServeConfig`` a source configures — the worker pool
|
||||
and the per-worker bound. The launcher materializes it into the env server's full
|
||||
``[serve]`` block, filling in the source's derived address
|
||||
(``OrchestratorConfig.env_addresses``)."""
|
||||
|
||||
pool: PoolConfig = Field(default_factory=vf.ElasticPoolConfig)
|
||||
"""Worker-pool sizing. ``elastic`` (default) starts at one worker and scales up on
|
||||
demand; ``static`` pre-spawns a fixed ``num_workers``."""
|
||||
|
||||
max_concurrent: int | None = Field(None, ge=1)
|
||||
"""Episodes in flight per worker (None = unbounded; the dispatcher's
|
||||
``max_inflight_episodes`` is the run's bound)."""
|
||||
|
||||
|
||||
class EnvConfig(BaseConfig):
|
||||
"""One environment a run pulls from: the verifiers blocks it composes (``env`` — what
|
||||
runs, ``serve`` — how it's hosted, ``legacy`` — a classic v0 env instead) plus this
|
||||
@@ -146,8 +125,8 @@ class EnvConfig(BaseConfig):
|
||||
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
|
||||
"""The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
|
||||
|
||||
serve: ServeConfig = ServeConfig()
|
||||
"""How this source's env server is sized. Consumed by the launcher (which writes each source's env-server config), not by the orchestrator — the orchestrator only connects."""
|
||||
serve: vf.ServeConfig = vf.ServeConfig()
|
||||
"""How this source's env server is hosted. The sizing knobs are consumed by the launcher, which writes each source's env-server config with an unset ``address`` filled in as the derived ``tcp://127.0.0.1:<env_server_base_port + index>``. Setting ``address`` marks the server externally managed: the launchers neither write its env-server TOML nor spawn a server for it, and the orchestrator connects to the given address — e.g. a k8s deployment running env servers in their own pods."""
|
||||
|
||||
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
|
||||
"""A classic (v0) environment to run through the bridge instead of ``env``."""
|
||||
@@ -354,7 +333,7 @@ class CheckpointConfig(BaseConfig):
|
||||
"""Step to resume the orchestrator from. None starts from scratch; ``-1`` resumes from the latest checkpoint available."""
|
||||
|
||||
wait_for_weights_timeout: int | None = Field(None, ge=1)
|
||||
"""When resuming, wait up to this many seconds for the weight directory to appear. Useful when the orchestrator restarts while the trainer is still saving weights. If None, fail immediately when weights are not found."""
|
||||
"""Wait up to this many seconds for the startup weight directory to appear (the trainer broadcasts the incoming policy — v0 from scratch, v{resume_step} on resume — before the first step). If None, fall back to a default timeout. Raise this for large models on slow shared filesystems."""
|
||||
|
||||
keep_last: int | None = Field(None, ge=1)
|
||||
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
|
||||
@@ -477,9 +456,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. RL/OPD roll out through the renderer
|
||||
client; SFT uses it to backfill tokens for its chat-completions teacher."""
|
||||
|
||||
optim: OptimizerConfig = OptimizerConfig()
|
||||
"""Per-run optimizer configuration for multi-run training."""
|
||||
|
||||
eval: EvalConfig | None = None
|
||||
"""Evaluation configuration."""
|
||||
|
||||
@@ -528,14 +504,14 @@ class OrchestratorConfig(BaseConfig):
|
||||
rollout_transport: TransportConfig = ZMQTransportConfig()
|
||||
"""Transport used to ship rollouts from orchestrator to trainer."""
|
||||
|
||||
output_dir: Path = Path("outputs/run_default")
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node."""
|
||||
|
||||
tasks_per_minute: int | None = Field(None, ge=1)
|
||||
"""Rate limit per environment worker, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. With multiple workers, the effective total rate is ``workers × this value``. None disables rate limiting."""
|
||||
|
||||
env_server_base_port: int = Field(5000, ge=1, le=65535)
|
||||
"""First port of the env-server port range: the source at position ``i`` (train, then eval) is served at ``tcp://127.0.0.1:<base + i>``. Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
|
||||
"""First port of the env-server port range: the source at position ``i`` (train, then eval) is served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address`` keep it instead, without shifting the other sources' ports (indices stay positional). Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
|
||||
|
||||
batch_size: int | None = Field(None, ge=1)
|
||||
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
|
||||
@@ -555,9 +531,11 @@ class OrchestratorConfig(BaseConfig):
|
||||
seq_len: int = 2048
|
||||
"""Training sequence length. Shorter samples are padded; longer samples are truncated."""
|
||||
|
||||
# TODO(Mika): This should be automatic from the number of ZMQ connections
|
||||
num_train_workers: int = Field(1, ge=1)
|
||||
"""Training workers to use."""
|
||||
"""Trainer data-parallel world size (trainer world size // cp). The orchestrator packs one micro-batch list per DP rank, so this must match the trainer topology. Auto-filled by the ``rl`` entrypoint; set explicitly for standalone orchestrator runs."""
|
||||
|
||||
pad_to_multiple_of: int = Field(1, ge=1)
|
||||
"""Pad each packed micro batch to a multiple of this value (the trainer's cp degree). Auto-filled by the ``rl`` entrypoint; set explicitly for standalone orchestrator runs with cp > 1."""
|
||||
|
||||
max_steps: int | None = None
|
||||
"""Maximum training steps. If None, runs indefinitely."""
|
||||
@@ -746,11 +724,13 @@ class OrchestratorConfig(BaseConfig):
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str]:
|
||||
"""Where each source's env server lives, keyed by ``(split, resolved_name)``:
|
||||
the source's own ``serve.address`` when set (an externally managed server), else
|
||||
``tcp://127.0.0.1:<port>`` with ports from ``env_server_base_port`` in
|
||||
``env_sources`` order. The launcher binds env servers at exactly these addresses
|
||||
and the orchestrator connects to them, so both sides agree from the config
|
||||
alone."""
|
||||
return {
|
||||
(split, source.resolved_name): f"tcp://127.0.0.1:{self.env_server_base_port + index}"
|
||||
(split, source.resolved_name): source.serve.address
|
||||
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
|
||||
for index, (split, source) in enumerate(self.env_sources)
|
||||
}
|
||||
|
||||
@@ -222,7 +222,7 @@ class RLConfig(BaseConfig):
|
||||
orchestrator: OrchestratorConfig
|
||||
|
||||
inference: InferenceConfig | None = None
|
||||
"""Inference server configuration. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."""
|
||||
"""Inference server configuration. If None, the rl entrypoint will not start an inference server (useful for manually started servers)."""
|
||||
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for every launched RL component. Component-specific env_vars override these."""
|
||||
@@ -393,7 +393,11 @@ class RLConfig(BaseConfig):
|
||||
"Set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
if self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
|
||||
inference_world_size = (
|
||||
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
|
||||
if self.inference
|
||||
else 1
|
||||
)
|
||||
common_config = dict(
|
||||
host=self.weight_broadcast.host,
|
||||
port=self.weight_broadcast.port,
|
||||
@@ -446,14 +450,14 @@ class RLConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_eplb_requires_quantized_weight_transfer(self):
|
||||
if self.inference is None or not self.inference.enable_eplb:
|
||||
if self.inference is None or not self.inference.vllm.enable_eplb:
|
||||
return self
|
||||
|
||||
# TODO(matej): check if weight reloading works itself before supporting EPLB without quantized transfer.
|
||||
trainer_weight_broadcast = self.trainer.weight_broadcast
|
||||
if trainer_weight_broadcast.type != "nccl" or not trainer_weight_broadcast.quantize_in_weight_transfer:
|
||||
raise ValueError(
|
||||
"inference.enable_eplb requires weight_broadcast.type = 'nccl' and "
|
||||
"inference.vllm.enable_eplb requires weight_broadcast.type = 'nccl' and "
|
||||
"weight_broadcast.quantize_in_weight_transfer = true."
|
||||
)
|
||||
|
||||
@@ -517,8 +521,8 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
|
||||
if self.inference is not None:
|
||||
self.inference.enable_lora = True
|
||||
self.inference.max_lora_rank = self.trainer.model.lora.rank
|
||||
self.inference.vllm.enable_lora = True
|
||||
self.inference.vllm.max_lora_rank = self.trainer.model.lora.rank
|
||||
else:
|
||||
warnings.warn(
|
||||
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
|
||||
@@ -532,12 +536,12 @@ class RLConfig(BaseConfig):
|
||||
def auto_setup_router_replay(self):
|
||||
if self.trainer.enable_router_replay:
|
||||
if self.inference is not None:
|
||||
if self.inference.enable_return_routed_experts is False:
|
||||
if self.inference.vllm.enable_return_routed_experts is False:
|
||||
warnings.warn(
|
||||
"Router replay is enabled, but inference.enable_return_routed_experts is False. Setting to True.",
|
||||
"Router replay is enabled, but inference.vllm.enable_return_routed_experts is False. Setting to True.",
|
||||
stacklevel=2,
|
||||
)
|
||||
self.inference.enable_return_routed_experts = True
|
||||
self.inference.vllm.enable_return_routed_experts = True
|
||||
else:
|
||||
warnings.warn(
|
||||
"Router replay is enabled, but inference is not configured. When manually starting the inference server, make sure to pass `--enable-return-routed-experts` to the vLLM server.",
|
||||
@@ -553,12 +557,12 @@ class RLConfig(BaseConfig):
|
||||
``trainer.enable_router_replay`` path, which sets the inference flag here
|
||||
(after InferenceConfig's own validators, which therefore miss it).
|
||||
"""
|
||||
if self.inference is not None and self.inference.enable_return_routed_experts:
|
||||
if self.inference is not None and self.inference.vllm.enable_return_routed_experts:
|
||||
router = self.inference.router
|
||||
if router is not None and router.type == "llm-d":
|
||||
raise ValueError(
|
||||
"The llm-d router backend does not support routed-expert return "
|
||||
"(inference.enable_return_routed_experts / trainer.enable_router_replay): it "
|
||||
"(inference.vllm.enable_return_routed_experts / trainer.enable_router_replay): it "
|
||||
"breaks P/D and is unverified for multi-node. Use router type 'vllm-router' "
|
||||
"for router-replay runs."
|
||||
)
|
||||
@@ -599,6 +603,7 @@ class RLConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_deployment(self):
|
||||
self.orchestrator.pad_to_multiple_of = self.trainer.model.cp
|
||||
if self.deployment.type == "single_node": # single-node
|
||||
# set num_train_workers to the number of data replicas
|
||||
non_data_parallel_size = self.trainer.model.cp
|
||||
@@ -608,20 +613,22 @@ class RLConfig(BaseConfig):
|
||||
# fill up inference capacity with dp ranks
|
||||
if self.inference is not None:
|
||||
num_infer_gpus = self.deployment.num_infer_gpus
|
||||
if num_infer_gpus != self.inference.parallel.dp * self.inference.parallel.tp:
|
||||
assert num_infer_gpus % self.inference.parallel.tp == 0, (
|
||||
if num_infer_gpus != self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size:
|
||||
assert num_infer_gpus % self.inference.vllm.tensor_parallel_size == 0, (
|
||||
"Number of inference GPUs must be divisible by the tensor parallel size"
|
||||
)
|
||||
self.inference.parallel.dp = num_infer_gpus // self.inference.parallel.tp
|
||||
self.inference.vllm.data_parallel_size = num_infer_gpus // self.inference.vllm.tensor_parallel_size
|
||||
# Ensure api_server_count matches DP so all workers are created.
|
||||
# Without this, in-memory weight transfer expects dp*tp workers
|
||||
# but only api_server_count*tp exist, causing a deadlock.
|
||||
dp = self.inference.parallel.dp
|
||||
if self.inference.api_server_count < dp and not self.inference.enable_lora:
|
||||
self.inference.api_server_count = dp
|
||||
dp = self.inference.vllm.data_parallel_size
|
||||
if self.inference.vllm.api_server_count < dp and not self.inference.vllm.enable_lora:
|
||||
self.inference.vllm.api_server_count = dp
|
||||
|
||||
elif self.deployment.type == "multi_node": # multi-node
|
||||
self.orchestrator.num_train_workers = self.deployment.num_train_nodes * self.deployment.gpus_per_node
|
||||
self.orchestrator.num_train_workers = (
|
||||
self.deployment.num_train_nodes * self.deployment.gpus_per_node // self.trainer.model.cp
|
||||
)
|
||||
|
||||
if self.deployment.nodes_per_fsdp_group is not None:
|
||||
if self.deployment.num_train_nodes % self.deployment.nodes_per_fsdp_group != 0:
|
||||
@@ -635,35 +642,38 @@ class RLConfig(BaseConfig):
|
||||
|
||||
if (
|
||||
self.inference is not None
|
||||
and self.inference.enable_expert_parallel
|
||||
and self.inference.vllm.enable_expert_parallel
|
||||
and self.inference.deployment.type != "disaggregated"
|
||||
):
|
||||
inference_tp = self.inference.parallel.tp
|
||||
inference_tp = self.inference.vllm.tensor_parallel_size
|
||||
if self.deployment.gpus_per_node % inference_tp != 0:
|
||||
raise ValueError(
|
||||
"deployment.gpus_per_node must be divisible by inference.parallel.tp "
|
||||
"when inference.enable_expert_parallel is enabled in multi-node deployment."
|
||||
"deployment.gpus_per_node must be divisible by inference.vllm.tensor_parallel_size "
|
||||
"when inference.vllm.enable_expert_parallel is enabled in multi-node deployment."
|
||||
)
|
||||
|
||||
inferred_dp_local = self.deployment.gpus_per_node // inference_tp
|
||||
total_infer_gpus = self.deployment.infer_nodes_per_replica * self.deployment.gpus_per_node
|
||||
expected_global_world_size = self.inference.parallel.dp * inference_tp
|
||||
expected_global_world_size = self.inference.vllm.data_parallel_size * inference_tp
|
||||
if expected_global_world_size != total_infer_gpus:
|
||||
raise ValueError(
|
||||
"For multi-node expert parallel inference, inference.parallel.dp * inference.parallel.tp "
|
||||
"For multi-node expert parallel inference, inference.vllm.data_parallel_size * inference.vllm.tensor_parallel_size "
|
||||
f"must match total inference GPUs ({total_infer_gpus}), got {expected_global_world_size}."
|
||||
)
|
||||
|
||||
if self.inference.data_parallel_size_local is None:
|
||||
self.inference.data_parallel_size_local = inferred_dp_local
|
||||
elif self.inference.data_parallel_size_local != inferred_dp_local:
|
||||
if self.inference.vllm.data_parallel_size_local is None:
|
||||
self.inference.vllm.data_parallel_size_local = inferred_dp_local
|
||||
elif self.inference.vllm.data_parallel_size_local != inferred_dp_local:
|
||||
raise ValueError(
|
||||
"inference.data_parallel_size_local must equal deployment.gpus_per_node / inference.parallel.tp "
|
||||
f"({inferred_dp_local}) when inference.enable_expert_parallel is enabled in multi-node deployment."
|
||||
"inference.vllm.data_parallel_size_local must equal deployment.gpus_per_node / inference.vllm.tensor_parallel_size "
|
||||
f"({inferred_dp_local}) when inference.vllm.enable_expert_parallel is enabled in multi-node deployment."
|
||||
)
|
||||
|
||||
if not self.inference.enable_lora and self.inference.api_server_count == self.inference.parallel.dp:
|
||||
self.inference.api_server_count = inferred_dp_local
|
||||
if (
|
||||
not self.inference.vllm.enable_lora
|
||||
and self.inference.vllm.api_server_count == self.inference.vllm.data_parallel_size
|
||||
):
|
||||
self.inference.vllm.api_server_count = inferred_dp_local
|
||||
|
||||
# Auto-infer DP and api_server_count for standard multi-node inference.
|
||||
# Without EP, vLLM only creates api_server_count * tp workers per node,
|
||||
@@ -671,16 +681,16 @@ class RLConfig(BaseConfig):
|
||||
# more workers than exist, deadlocking in-memory transfer initialization.
|
||||
if (
|
||||
self.inference is not None
|
||||
and not self.inference.enable_expert_parallel
|
||||
and not self.inference.vllm.enable_expert_parallel
|
||||
and self.inference.deployment.type != "disaggregated"
|
||||
):
|
||||
dp_per_node = self.deployment.gpus_per_node // self.inference.parallel.tp
|
||||
if self.inference.parallel.dp == 1 and dp_per_node > 1:
|
||||
self.inference.parallel.dp = dp_per_node
|
||||
if self.inference.data_parallel_size_local is None and dp_per_node > 1:
|
||||
self.inference.data_parallel_size_local = dp_per_node
|
||||
if self.inference.api_server_count == 1 and dp_per_node > 1:
|
||||
self.inference.api_server_count = dp_per_node
|
||||
dp_per_node = self.deployment.gpus_per_node // self.inference.vllm.tensor_parallel_size
|
||||
if self.inference.vllm.data_parallel_size == 1 and dp_per_node > 1:
|
||||
self.inference.vllm.data_parallel_size = dp_per_node
|
||||
if self.inference.vllm.data_parallel_size_local is None and dp_per_node > 1:
|
||||
self.inference.vllm.data_parallel_size_local = dp_per_node
|
||||
if self.inference.vllm.api_server_count == 1 and dp_per_node > 1:
|
||||
self.inference.vllm.api_server_count = dp_per_node
|
||||
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
# Every allocated inference GPU is an in-memory transfer worker.
|
||||
@@ -721,7 +731,7 @@ class RLConfig(BaseConfig):
|
||||
# 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
|
||||
stride = self.deployment.gpus_per_node // self.inference.vllm.tensor_parallel_size
|
||||
role_order = ["prefill"] * (infer_deploy.num_prefill_nodes * stride) + ["decode"] * (
|
||||
infer_deploy.num_decode_nodes * stride
|
||||
)
|
||||
@@ -749,7 +759,7 @@ class RLConfig(BaseConfig):
|
||||
if not self.orchestrator.any_policy_sourced and "base_url" not in client.model_fields_set:
|
||||
host = self.inference.server.host or "localhost"
|
||||
port = self.inference.server.port
|
||||
client.base_url = [f"http://{host}:{port}/v1"]
|
||||
client.base_url = f"http://{host}:{port}/v1"
|
||||
if (
|
||||
self.deployment.type == "single_node"
|
||||
and self.inference.router is not None
|
||||
|
||||
@@ -108,23 +108,12 @@ class BaseModelConfig(BaseConfig):
|
||||
"""VLM configuration. Setting this enables vision-language model support."""
|
||||
|
||||
|
||||
class ElasticConfig(BaseConfig):
|
||||
hostname: str
|
||||
"""DNS hostname that resolves to inference server IPs."""
|
||||
|
||||
port: int = 8000
|
||||
"""Port that inference servers listen on."""
|
||||
|
||||
sync_interval: float = 5.0
|
||||
"""Seconds between server discovery checks."""
|
||||
|
||||
|
||||
class ClientConfig(BaseConfig):
|
||||
wait_for_ready_timeout: int = 1800
|
||||
"""Seconds to wait at startup for the inference pool to become ready. Applies to both the static health check and elastic DNS-based discovery."""
|
||||
"""Seconds to wait at startup for the inference pool to become ready."""
|
||||
|
||||
base_url: list[str] = ["http://localhost:8000/v1"]
|
||||
"""Base URLs for the OpenAI API. With more than one URL, the client round-robins (chat) completion requests across all servers. Ignored when ``elastic`` is set."""
|
||||
base_url: str = "http://localhost:8000/v1"
|
||||
"""Base URL for the OpenAI API. For multi-replica deployments, point this at a router in front of the replicas."""
|
||||
|
||||
api_key_var: str = "VLLM_API_KEY"
|
||||
"""Environment variable name containing the API key, resolved via ``os.getenv``. Can be any string when the server is not protected by an API key; the same key is used for every URL."""
|
||||
@@ -142,18 +131,7 @@ class ClientConfig(BaseConfig):
|
||||
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
|
||||
|
||||
admin_base_url: list[str] | None = None
|
||||
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in disaggregated P/D deployments where the router must not handle admin traffic."""
|
||||
|
||||
elastic: ElasticConfig | None = None
|
||||
"""Elastic inference pool config for DNS-based service discovery. When set, ``base_url`` is ignored and inference servers are discovered dynamically via DNS."""
|
||||
|
||||
router_url: str | None = None
|
||||
"""vllm-router URL for load-aware inference routing. With elastic mode, inference requests go through the router while admin ops still hit discovered pods directly."""
|
||||
|
||||
@property
|
||||
def is_elastic(self) -> bool:
|
||||
"""Check if elastic mode is enabled."""
|
||||
return self.elastic is not None
|
||||
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in multi-replica or disaggregated P/D deployments where the router must not handle admin traffic."""
|
||||
|
||||
|
||||
class LogConfig(BaseConfig):
|
||||
|
||||
@@ -625,9 +625,6 @@ class TrainerConfig(BaseConfig):
|
||||
metrics_server: MetricsServerConfig | None = None
|
||||
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
|
||||
|
||||
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."""
|
||||
|
||||
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."""
|
||||
|
||||
@@ -702,12 +699,6 @@ class TrainerConfig(BaseConfig):
|
||||
raise ValueError("Muon optimizer does not support FSDP CPU offload")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_optim_cpu_offload_single_run(self):
|
||||
if self.model.optim_cpu_offload and self.max_concurrent_runs > 1:
|
||||
raise ValueError("Optimizer CPU offload is not supported with max_concurrent_runs > 1")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_broadcast(self):
|
||||
if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
|
||||
@@ -68,13 +68,12 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
propagate(
|
||||
"model.name",
|
||||
"trainer.model.name",
|
||||
"inference.model.name",
|
||||
"inference.vllm.model",
|
||||
"orchestrator.model.name",
|
||||
)
|
||||
propagate(
|
||||
"model.vlm",
|
||||
"trainer.model.vlm",
|
||||
"inference.model.vlm",
|
||||
"orchestrator.model.vlm",
|
||||
)
|
||||
|
||||
@@ -109,7 +108,7 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
# [file_monitor] leaf. (Bare empty ``[file_monitor]`` block enablement is at the end.)
|
||||
propagate("file_monitor.filename", "trainer.file_monitor.filename", "orchestrator.file_monitor.filename")
|
||||
|
||||
# [tokenizer]. ``chat_template`` also flows to ``inference.model`` (vLLM's
|
||||
# [tokenizer]. ``chat_template`` also flows to ``inference.vllm`` (vLLM's
|
||||
# ``--chat-template``); ``name`` and ``trust_remote_code`` can legitimately
|
||||
# differ between sub-configs (auto-derived from model names, which may
|
||||
# differ for FP8-quantized inference variants).
|
||||
@@ -123,7 +122,7 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
"tokenizer.chat_template",
|
||||
"trainer.tokenizer.chat_template",
|
||||
"orchestrator.tokenizer.chat_template",
|
||||
"inference.model.chat_template",
|
||||
"inference.vllm.chat_template",
|
||||
)
|
||||
|
||||
# [rollout_transport] → both sub-configs (host is launcher-injected for zmq multi-node).
|
||||
@@ -139,23 +138,9 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
# 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
|
||||
# the raw shared path, so the materialized config round-trips cleanly.
|
||||
output_dir = get("output_dir")
|
||||
if output_dir is not None:
|
||||
expected = {
|
||||
"trainer.output_dir": output_dir,
|
||||
"orchestrator.output_dir": f"{output_dir}/run_default",
|
||||
}
|
||||
for sub, expected_value in expected.items():
|
||||
sub_value = get(sub)
|
||||
if sub_value is not None and sub_value != expected_value:
|
||||
conflicts.append(("output_dir", sub))
|
||||
fill(sub, expected_value)
|
||||
propagate("output_dir", "trainer.output_dir", "orchestrator.output_dir")
|
||||
|
||||
# Cascade trainer.tokenizer.chat_template → inference.model.chat_template
|
||||
# Cascade trainer.tokenizer.chat_template → inference.vllm.chat_template
|
||||
# (vLLM ``--chat-template``). Read trainer's value *after* the shared
|
||||
# propagation above so we cover both:
|
||||
# - shared ``[tokenizer] chat_template`` (already filled all three above,
|
||||
@@ -165,7 +150,7 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
# would otherwise complain about the missing inference value).
|
||||
trainer_chat_template = get("trainer.tokenizer.chat_template")
|
||||
if trainer_chat_template is not None:
|
||||
fill("inference.model.chat_template", trainer_chat_template)
|
||||
fill("inference.vllm.chat_template", trainer_chat_template)
|
||||
|
||||
# Bare ``[ckpt]`` / ``[wandb]`` block: presence-only signal that enables
|
||||
# the section with defaults on both sub-configs. Necessary because
|
||||
@@ -225,9 +210,9 @@ def validate_shared_model_name(
|
||||
) -> None:
|
||||
# Orchestrator must match inference (it queries the inference server)
|
||||
if inference is not None:
|
||||
if inference.model.name != orchestrator.model.name:
|
||||
if inference.vllm.model != orchestrator.model.name:
|
||||
raise ValueError(
|
||||
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
|
||||
f"Inference model name ({inference.vllm.model}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
|
||||
"The orchestrator queries the inference server and must use the same model name."
|
||||
)
|
||||
return
|
||||
@@ -244,9 +229,10 @@ def validate_shared_output_dir(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.output_dir != orchestrator.output_dir.parent:
|
||||
if trainer.output_dir != orchestrator.output_dir:
|
||||
raise ValueError(
|
||||
f"Trainer outputs directory ({trainer.output_dir}) and orchestrator outputs directory parent ({orchestrator.output_dir.parent}) are not the same. Please specify the same outputs directory for both."
|
||||
f"Trainer outputs directory ({trainer.output_dir}) and orchestrator outputs directory ({orchestrator.output_dir}) are not the same. "
|
||||
"Please specify the same outputs directory for both (the orchestrator no longer nests under a run_default subdirectory)."
|
||||
)
|
||||
|
||||
|
||||
@@ -310,9 +296,9 @@ def validate_shared_tokenizer(
|
||||
f"Use the shared [tokenizer] config to set chat_template for both."
|
||||
)
|
||||
if inference is not None:
|
||||
if trainer.tokenizer.chat_template != inference.model.chat_template:
|
||||
if trainer.tokenizer.chat_template != inference.vllm.chat_template:
|
||||
raise ValueError(
|
||||
f"Inference chat_template ({inference.model.chat_template!r}) does not match "
|
||||
f"Inference chat_template ({inference.vllm.chat_template!r}) does not match "
|
||||
f"the shared tokenizer chat_template ({trainer.tokenizer.chat_template!r}). "
|
||||
f"Use the shared [tokenizer] config to set chat_template for all components."
|
||||
)
|
||||
|
||||
+20
-6
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "prime-rl"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
description = "Async RL Training at Scale"
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
@@ -33,7 +33,7 @@ dependencies = [
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"torchtitan",
|
||||
"verifiers[harbor]>=0.2.2.dev76",
|
||||
"verifiers[harbor]>=0.3.0",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
@@ -59,8 +59,13 @@ env-server = "prime_rl.entrypoints.env_server:main"
|
||||
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
|
||||
|
||||
[project.optional-dependencies]
|
||||
# Both wheels are the same flash-attn 2.8.3 / cu128 / torch 2.11 / cp312 build and carry
|
||||
# sm_80 / sm_90 / sm_100 / sm_120 cubins. `attn="auto"` picks FA4 on sm_100 and FA3 on
|
||||
# sm_90, so FA2 is the resolved backend on sm_120 (see `_resolve_attn_impl` in
|
||||
# trainer/model.py).
|
||||
flash-attn = [
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.22/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
|
||||
]
|
||||
flash-attn-3 = ["flash_attn_3"]
|
||||
|
||||
@@ -123,13 +128,22 @@ override-dependencies = [
|
||||
"openenv-core",
|
||||
]
|
||||
|
||||
# Environment packages (research-environments + verifiers) are auto-discovered as
|
||||
# workspace members, so new envs need no per-package registration. Install them
|
||||
# with `uv sync --all-packages`.
|
||||
# research-environments packages are auto-discovered as workspace members, so new
|
||||
# envs there need no per-package registration. verifiers' example envs are opt-in:
|
||||
# only the ones prime-rl trains or tests on are listed, so an upstream example with
|
||||
# conflicting pins can't break the shared lock. Install them with
|
||||
# `uv sync --all-packages`.
|
||||
[tool.uv.workspace]
|
||||
members = [
|
||||
"deps/research-environments/environments/*/*",
|
||||
"deps/verifiers/environments/*",
|
||||
"deps/verifiers/environments/alphabet_sort_v1",
|
||||
"deps/verifiers/environments/color_codeword_v1",
|
||||
"deps/verifiers/environments/gsm8k_v1",
|
||||
"deps/verifiers/environments/kuhn_poker_v1",
|
||||
"deps/verifiers/environments/proposer_solver_v1",
|
||||
"deps/verifiers/environments/reverse_text_v1",
|
||||
"deps/verifiers/environments/wiki_search_v1",
|
||||
"deps/verifiers/environments/wordle_v1",
|
||||
]
|
||||
# tau2-synth-v1 and tau3-bench-v1 pin `tau2` forks/revs that conflict with the
|
||||
# canonical tau2-bench-v1; a workspace shares one lock, so these can't coexist.
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
#!/bin/bash
|
||||
# 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
|
||||
|
||||
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
|
||||
|
||||
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 --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"
|
||||
@@ -143,16 +143,6 @@ 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!"
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ uv run rl @ base.toml --trainer @ trainer.toml --trainer.lr 1e-3 # mix
|
||||
|
||||
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base.
|
||||
|
||||
Naming: CLI uses kebab-case (`--model.max-model-len`); TOML uses snake_case (`max_model_len`).
|
||||
Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max_model_len`).
|
||||
|
||||
## Inspect & validate
|
||||
|
||||
@@ -38,7 +38,7 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
|
||||
|
||||
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
|
||||
|
||||
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--model.max-model-len None`.
|
||||
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--vllm.max-model-len None`.
|
||||
|
||||
**Lists** — TOML uses array of tables; later config files replace lists wholesale, so overlays must include the full desired list:
|
||||
|
||||
@@ -71,7 +71,9 @@ type = "subprocess"
|
||||
|
||||
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text-v1` or `--orchestrator.eval.source.0.env.taskset.id reverse-text-v1`.
|
||||
|
||||
**Dicts** — TOML uses a section; CLI takes a JSON string: `--vllm-extra '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
|
||||
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
|
||||
|
||||
**vLLM pass-through** — `[inference.vllm]` uses vLLM's own argument names (`model`, `tensor_parallel_size`, `data_parallel_size`, `max_model_len`, ...) and forwards *any* key to the vLLM server, typed by prime-rl or not: `[inference.vllm] max_num_seqs = 256`, or `--inference.vllm.max-num-seqs 256` on the CLI. CLI values are JSON-coerced, so dict-valued vLLM args work as `--inference.vllm.compilation-config '{"cudagraph_mode": "NONE"}'`. Non-vLLM knobs (router, deployment, weight broadcast, kv-cache offload, env vars) stay on `[inference]` itself.
|
||||
|
||||
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
|
||||
|
||||
@@ -88,7 +90,7 @@ In TOML, an empty section header (`[ckpt]`) does the same.
|
||||
|
||||
## RL trainer token exports
|
||||
|
||||
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, component weight streams (rl/ce/ref_kl), advantages, 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 under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
|
||||
```toml
|
||||
enable_token_export = true
|
||||
|
||||
@@ -29,7 +29,7 @@ uv sync --all-extras --all-packages # + all env packages (needed to train
|
||||
uv sync --package prime-rl --package gsm8k-v1 # core + just one env
|
||||
```
|
||||
|
||||
Environment packages under `deps/research-environments/environments/*/*` and `deps/verifiers/environments/*` are uv **workspace members**, auto-discovered — adding a new env needs no `pyproject.toml` change. They are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
|
||||
Environment packages are uv **workspace members**. Those under `deps/research-environments/environments/*/*` are auto-discovered — adding a new env there needs no `pyproject.toml` change. verifiers' example envs are enumerated explicitly in `[tool.uv.workspace].members` (only the ones prime-rl trains or tests on) — to use another, add its path to the list. Members are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
|
||||
|
||||
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`.
|
||||
|
||||
|
||||
@@ -162,7 +162,7 @@ jq '.rewards' {output_dir}/rollouts/step_42/train/effective/traces.jsonl
|
||||
jq 'select(.ok | not) | {id, env: .info.env_name, runtime}' {output_dir}/rollouts/step_*/train/all/traces.jsonl
|
||||
```
|
||||
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{output_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the trace subtrees.
|
||||
|
||||
### Common failure modes
|
||||
|
||||
|
||||
@@ -60,8 +60,8 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
|
||||
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly.
|
||||
|
||||
```bash
|
||||
uv run inference --model.name Qwen/Qwen3-0.6B
|
||||
uv run inference --model.name Qwen/Qwen3-0.6B --model.enforce-eager
|
||||
uv run inference --vllm.model Qwen/Qwen3-0.6B
|
||||
uv run inference --vllm.model Qwen/Qwen3-0.6B --vllm.enforce-eager
|
||||
```
|
||||
|
||||
Smoke checks:
|
||||
|
||||
@@ -64,7 +64,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
template = env.get_template(config.slurm.template_path.name)
|
||||
|
||||
is_disaggregated = config.deployment.type == "disaggregated"
|
||||
dp_per_node = config.deployment.gpus_per_node // config.parallel.tp
|
||||
dp_per_node = config.deployment.gpus_per_node // config.vllm.tensor_parallel_size
|
||||
|
||||
offload = config.kv_cache_offload
|
||||
is_mooncake = offload is not None and offload.type == "mooncake"
|
||||
@@ -100,7 +100,7 @@ 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,
|
||||
data_parallel_rpc_port=config.data_parallel_rpc_port,
|
||||
data_parallel_rpc_port=config.vllm.data_parallel_rpc_port,
|
||||
use_deep_gemm=config.use_deep_gemm,
|
||||
prefill_env_vars=config.deployment.prefill_env_vars,
|
||||
decode_env_vars=config.deployment.decode_env_vars,
|
||||
@@ -110,8 +110,8 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
elif is_multi_node:
|
||||
template_vars.update(
|
||||
backend_port=config.backend_port,
|
||||
data_parallel_rpc_port=config.data_parallel_rpc_port,
|
||||
enable_expert_parallel=config.enable_expert_parallel,
|
||||
data_parallel_rpc_port=config.vllm.data_parallel_rpc_port,
|
||||
enable_expert_parallel=config.vllm.enable_expert_parallel,
|
||||
infer_nodes_per_replica=config.deployment.num_nodes,
|
||||
)
|
||||
|
||||
@@ -170,7 +170,7 @@ def start_router(config: InferenceConfig) -> subprocess.Popen:
|
||||
"--worker-urls",
|
||||
f"http://{worker_host}:{config.backend_port}",
|
||||
"--intra-node-data-parallel-size",
|
||||
str(config.data_parallel_size_local or config.parallel.dp),
|
||||
str(config.vllm.data_parallel_size_local or config.vllm.data_parallel_size),
|
||||
"--request-id-headers",
|
||||
"x-session-id",
|
||||
"--worker-startup-timeout-secs",
|
||||
@@ -222,7 +222,7 @@ def inference_local(config: InferenceConfig):
|
||||
from prime_rl.inference.vllm.server import server # pyright: ignore
|
||||
|
||||
try:
|
||||
server(config, vllm_extra=config.vllm_extra)
|
||||
server(config)
|
||||
finally:
|
||||
if router_process is not None:
|
||||
router_stopping.set()
|
||||
|
||||
@@ -49,14 +49,24 @@ ENVS_DIR = "envs"
|
||||
|
||||
|
||||
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig, str]]:
|
||||
"""``(split, source, address)`` for every train/eval source. The launcher runs one
|
||||
env server per source at its deterministic address; the orchestrator connects there."""
|
||||
"""``(split, source, address)`` for every launcher-managed train/eval source. The
|
||||
launcher runs one env server per source at its deterministic address; the
|
||||
orchestrator connects there. A source with ``serve.address`` set is externally
|
||||
managed — its server runs elsewhere and only the orchestrator connects to it — so
|
||||
the launcher neither writes its TOML nor spawns a server for it."""
|
||||
addresses = config.orchestrator.env_addresses
|
||||
return [
|
||||
(split, source, addresses[(split, source.resolved_name)]) for split, source in config.orchestrator.env_sources
|
||||
(split, source, addresses[(split, source.resolved_name)])
|
||||
for split, source in config.orchestrator.env_sources
|
||||
if source.serve.address is None
|
||||
]
|
||||
|
||||
|
||||
def env_server_names(config: RLConfig, split: str) -> list[str]:
|
||||
"""Names of the launcher-managed env servers for one split."""
|
||||
return [source.resolved_name for source_split, source, _ in env_servers(config) if source_split == split]
|
||||
|
||||
|
||||
def get_physical_gpu_ids() -> list[int]:
|
||||
"""Return physical GPU IDs visible to the launcher."""
|
||||
raw_visible = os.environ.get("CUDA_VISIBLE_DEVICES")
|
||||
@@ -93,9 +103,10 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
with open(output_dir / INFERENCE_TOML, "wb") as f:
|
||||
tomli_w.dump(inference_dict, f)
|
||||
|
||||
# One EnvServerConfig TOML per source: `env-server @ <path>` binds at the source's
|
||||
# deterministic address, where the orchestrator connects. The source's env/serve/legacy
|
||||
# blocks carry over; its other knobs (sampling, algo, name, ...) are orchestrator-side.
|
||||
# One EnvServerConfig TOML per launcher-managed source: `env-server @ <path>` binds
|
||||
# at the source's deterministic address, where the orchestrator connects. The source's
|
||||
# env/serve/legacy blocks carry over; its other knobs (sampling, algo, name, ...) are
|
||||
# orchestrator-side.
|
||||
for split, source, address in env_servers(config):
|
||||
env_dir = output_dir / ENVS_DIR / split
|
||||
env_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -159,9 +170,8 @@ def rl_local(config: RLConfig):
|
||||
}
|
||||
|
||||
# Validate client port matches inference server port
|
||||
if config.inference is not None and not config.orchestrator.model.client.is_elastic:
|
||||
base_url = config.orchestrator.model.client.base_url[0]
|
||||
parsed = urlparse(base_url)
|
||||
if config.inference is not None:
|
||||
parsed = urlparse(config.orchestrator.model.client.base_url)
|
||||
client_port = parsed.port
|
||||
expected_port = config.inference.server.port
|
||||
if client_port != expected_port:
|
||||
@@ -227,7 +237,7 @@ def rl_local(config: RLConfig):
|
||||
"No [inference] block configured - the policy inference server will not be started here. "
|
||||
"Every algorithm requires a policy inference pool for evals + weight sync; "
|
||||
"make sure one is running at orchestrator.model.client.base_url "
|
||||
f"({', '.join(config.orchestrator.model.client.base_url)}), otherwise the orchestrator "
|
||||
f"({config.orchestrator.model.client.base_url}), otherwise the orchestrator "
|
||||
"will hang waiting for it."
|
||||
)
|
||||
|
||||
@@ -237,7 +247,7 @@ def rl_local(config: RLConfig):
|
||||
assert algo is not None, "TrainSourceConfig.algo must be resolved before launch (inherit_env_algorithms)"
|
||||
for ref in (algo.sampling.source, getattr(algo, "teacher", None)):
|
||||
if isinstance(ref, FrozenModelConfig):
|
||||
frozen_endpoints.append(f"{ref.name} ({', '.join(ref.base_url)})")
|
||||
frozen_endpoints.append(f"{ref.name} ({ref.base_url})")
|
||||
if frozen_endpoints:
|
||||
endpoints = ", ".join(dict.fromkeys(frozen_endpoints))
|
||||
logger.info(
|
||||
@@ -453,10 +463,9 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
else {}
|
||||
)
|
||||
|
||||
# Env servers launch next to the orchestrator, one per train/eval source.
|
||||
sources = config.orchestrator.env_sources
|
||||
train_env_names = [source.resolved_name for split, source in sources if split == "train"]
|
||||
eval_env_names = [source.resolved_name for split, source in sources if split == "eval"]
|
||||
# Env servers launch next to the orchestrator, one per launcher-managed train/eval source.
|
||||
train_env_names = env_server_names(config, "train")
|
||||
eval_env_names = env_server_names(config, "eval")
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
script = template.render(
|
||||
@@ -473,7 +482,6 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
is_disaggregated=True,
|
||||
config_dir=config_dir,
|
||||
output_dir=config.output_dir,
|
||||
orchestrator_output_dir=config.orchestrator.output_dir,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=infer_deploy.num_nodes * config.deployment.num_infer_replicas,
|
||||
nodes_per_infer_replica=infer_deploy.num_nodes,
|
||||
@@ -489,8 +497,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
router_port=config.inference.server.port,
|
||||
prefill_port=infer_deploy.prefill_port,
|
||||
decode_port=infer_deploy.decode_port,
|
||||
inference_tp=config.inference.parallel.tp,
|
||||
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port,
|
||||
inference_tp=config.inference.vllm.tensor_parallel_size,
|
||||
inference_data_parallel_rpc_port=config.inference.vllm.data_parallel_rpc_port,
|
||||
use_deep_gemm=config.inference.use_deep_gemm,
|
||||
prefill_env_vars=infer_deploy.prefill_env_vars,
|
||||
decode_env_vars=infer_deploy.decode_env_vars,
|
||||
@@ -499,7 +507,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
inference_env_vars=inference_env_vars,
|
||||
prefill_vllm_extra_json=vllm_overrides_fragment(infer_deploy.prefill_vllm_overrides),
|
||||
decode_vllm_extra_json=vllm_overrides_fragment(infer_deploy.decode_vllm_overrides),
|
||||
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
|
||||
dp_per_node=config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
|
||||
**mooncake_vars,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
|
||||
@@ -514,7 +522,6 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
is_disaggregated=False,
|
||||
config_dir=config_dir, # TODO: should prob have each subconfig path separately
|
||||
output_dir=config.output_dir,
|
||||
orchestrator_output_dir=config.orchestrator.output_dir,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.total_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
|
||||
@@ -524,10 +531,16 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
router_port=config.inference.server.port if config.inference else 8000,
|
||||
infer_nodes_per_replica=config.deployment.infer_nodes_per_replica,
|
||||
backend_port=config.inference.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,
|
||||
inference_tp=config.inference.vllm.tensor_parallel_size if config.inference else 1,
|
||||
inference_enable_expert_parallel=config.inference.vllm.enable_expert_parallel
|
||||
if config.inference
|
||||
else False,
|
||||
inference_data_parallel_rpc_port=config.inference.vllm.data_parallel_rpc_port
|
||||
if config.inference
|
||||
else 29600,
|
||||
dp_per_node=(config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size)
|
||||
if config.inference
|
||||
else 1,
|
||||
**mooncake_vars,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
|
||||
@@ -558,10 +571,8 @@ def rl_slurm(config: RLConfig):
|
||||
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean_output_dir"})
|
||||
logger.info(f"Wrote config to {config_dir / RL_TOML}")
|
||||
|
||||
train_env_names = [env.resolved_name for env in config.orchestrator.train.source]
|
||||
eval_env_names = (
|
||||
[source.resolved_name for source in config.orchestrator.eval.source] if config.orchestrator.eval else []
|
||||
)
|
||||
train_env_names = env_server_names(config, "train")
|
||||
eval_env_names = env_server_names(config, "eval")
|
||||
|
||||
log_message = format_log_message(
|
||||
log_dir=log_dir,
|
||||
@@ -575,10 +586,8 @@ def rl_slurm(config: RLConfig):
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
|
||||
train_env_names = [env.resolved_name for env in config.orchestrator.train.source]
|
||||
eval_env_names = (
|
||||
[source.resolved_name for source in config.orchestrator.eval.source] if config.orchestrator.eval else []
|
||||
)
|
||||
train_env_names = env_server_names(config, "train")
|
||||
eval_env_names = env_server_names(config, "eval")
|
||||
|
||||
has_infer = config.deployment.infer_nodes_per_replica > 0
|
||||
log_message = format_log_message(
|
||||
|
||||
@@ -26,7 +26,7 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
os.environ["VLLM_USE_DEEP_GEMM"] = deep_gemm_enabled
|
||||
os.environ["VLLM_MOE_USE_DEEP_GEMM"] = deep_gemm_enabled
|
||||
|
||||
if config.enable_lora:
|
||||
if config.vllm.enable_lora:
|
||||
os.environ["VLLM_ALLOW_RUNTIME_LORA_UPDATING"] = "True"
|
||||
|
||||
if config.log.json_logging:
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import asyncio
|
||||
from argparse import Namespace
|
||||
from typing import Any
|
||||
|
||||
import uvloop
|
||||
from fastapi import APIRouter, Request
|
||||
@@ -211,20 +210,18 @@ vllm.v1.utils.run_api_server_worker_proc = custom_run_api_server_worker_proc
|
||||
# Adapted from vllm/entrypoints/cli/serve.py
|
||||
# Only difference we do some config translation (i.e. pass populated namespace
|
||||
# to `parse_args`) and additional arg validation
|
||||
def server(config: InferenceConfig, vllm_extra: dict[str, Any] | None = None):
|
||||
def server(config: InferenceConfig):
|
||||
import os
|
||||
|
||||
from vllm.entrypoints.cli.serve import run_headless, run_multi_api_server
|
||||
from vllm.entrypoints.openai.api_server import run_server
|
||||
|
||||
# Signal worker processes to disable LoRA on MoE layers when LoRA targets don't include experts
|
||||
if config.lora_target_modules and not any("expert" in m for m in config.lora_target_modules):
|
||||
lora_target_modules = config.vllm.lora_target_modules
|
||||
if lora_target_modules and not any("expert" in m for m in lora_target_modules):
|
||||
os.environ["PRIME_NO_MOE_LORA"] = "1"
|
||||
|
||||
namespace = config.to_vllm()
|
||||
if vllm_extra:
|
||||
for key, value in vllm_extra.items():
|
||||
setattr(namespace, key, value)
|
||||
namespace = config.to_namespace()
|
||||
|
||||
parser = FlexibleArgumentParser(description="vLLM OpenAI-Compatible RESTful API server.")
|
||||
parser = make_arg_parser(parser)
|
||||
|
||||
@@ -65,15 +65,15 @@ async def connect_frozen_pool(
|
||||
(sft), so the rollout carries tokens. Left as plain chat-completions
|
||||
otherwise (opd/opsd read teacher logprobs via prefill, where the train
|
||||
client type is moot)."""
|
||||
from prime_rl.utils.client import setup_inference_pool
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={', '.join(config.base_url)})")
|
||||
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
|
||||
if renderer_config is not None:
|
||||
pool = await setup_inference_pool(
|
||||
pool = InferencePool(
|
||||
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
|
||||
)
|
||||
else:
|
||||
pool = await setup_inference_pool(config, model_name=config.name)
|
||||
pool = InferencePool(config, model_name=config.name)
|
||||
await pool.wait_for_ready(config.name)
|
||||
return pool
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.configs.algorithm import OPDAlgoConfig
|
||||
from prime_rl.orchestrator.algo.base import Algorithm
|
||||
from prime_rl.utils.client import StaticInferencePool
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
@@ -29,13 +28,10 @@ class OPDAlgorithm(Algorithm):
|
||||
def __init__(self, config: OPDAlgoConfig, policy_pool: InferencePool):
|
||||
super().__init__(config, policy_pool)
|
||||
self.teacher = config.teacher
|
||||
self.teacher_pool: StaticInferencePool | None = None # static teacher endpoint, connected in setup()
|
||||
self.teacher_pool: InferencePool | None = None # frozen teacher endpoint, connected in setup()
|
||||
|
||||
async def setup(self) -> None:
|
||||
pool = await self.connect(self.teacher)
|
||||
if not isinstance(pool, StaticInferencePool):
|
||||
raise TypeError("opd teacher must be a static endpoint — prefill scoring needs fixed endpoints")
|
||||
self.teacher_pool = pool
|
||||
self.teacher_pool = await self.connect(self.teacher)
|
||||
|
||||
async def score_rollout(self, rollout: Rollout) -> None:
|
||||
pool = self.teacher_pool
|
||||
|
||||
@@ -28,7 +28,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
from collections import Counter, defaultdict
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum, auto
|
||||
from typing import Literal
|
||||
@@ -47,7 +47,7 @@ from prime_rl.orchestrator.types import (
|
||||
RolloutKind,
|
||||
)
|
||||
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
|
||||
from prime_rl.utils.client import InferencePool, client_identity
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -413,20 +413,9 @@ class RolloutDispatcher:
|
||||
else:
|
||||
pool, model_name, live_sourced = self._train_pool_for(group.env_name)
|
||||
|
||||
# Pin a single client per group to keep prefix-cache hits
|
||||
if group.pinned_client is None:
|
||||
if group.kind == "eval":
|
||||
client = await pool.get_eval_client()
|
||||
else:
|
||||
load = Counter(
|
||||
client_identity(m.client_config) for m in self.inflight.values() if m.client_config is not None
|
||||
)
|
||||
client = await pool.select_train_client(load)
|
||||
if group_id not in self.groups:
|
||||
return False
|
||||
group.pinned_client = client
|
||||
else:
|
||||
client = group.pinned_client
|
||||
group.pinned_client = pool.eval_client if group.kind == "eval" else pool.train_client
|
||||
client = group.pinned_client
|
||||
|
||||
env_collection = self.train_envs if group.kind == "train" else self.eval_envs
|
||||
if env_collection is None:
|
||||
|
||||
@@ -37,7 +37,7 @@ if TYPE_CHECKING:
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.orchestrator.ckpt import CheckpointManager
|
||||
from prime_rl.transport.base import TrainingBatchSender
|
||||
from prime_rl.transport.base import MicroBatchSender
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.monitor.base import Monitor
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive imports
|
||||
@@ -49,6 +49,7 @@ from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.filters import setup_filters
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.packing import BatchPacker
|
||||
from prime_rl.orchestrator.patches import (
|
||||
monkey_patch_chat_completion_logprobs,
|
||||
monkey_patch_oai_iterable_types,
|
||||
@@ -74,7 +75,7 @@ from prime_rl.orchestrator.utils import (
|
||||
from prime_rl.orchestrator.watcher import WeightWatcher
|
||||
from prime_rl.trainer.model import setup_tokenizer
|
||||
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.transport import TrainingBatch, setup_training_batch_sender
|
||||
from prime_rl.transport import setup_micro_batch_sender
|
||||
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
|
||||
from prime_rl.utils.client import init_nccl_broadcast, init_nixl_broadcast
|
||||
from prime_rl.utils.config import to_toml_dict
|
||||
@@ -129,7 +130,8 @@ class Orchestrator:
|
||||
tokenizer: PreTrainedTokenizer
|
||||
policy_inference: InferencePool
|
||||
monitor: Monitor
|
||||
sender: TrainingBatchSender
|
||||
sender: MicroBatchSender | None
|
||||
packer: BatchPacker
|
||||
train_envs: TrainEnvs
|
||||
train_source: TrainSource
|
||||
train_sink: TrainSink
|
||||
@@ -218,8 +220,7 @@ class Orchestrator:
|
||||
# references are external endpoints — each env's Algorithm builds its
|
||||
# own pools in ``setup()`` below.
|
||||
get_logger().info(
|
||||
f"Initializing policy inference pool (base_url={', '.join(config.model.client.base_url)}, "
|
||||
f"model={config.model.name})"
|
||||
f"Initializing policy inference pool (base_url={config.model.client.base_url}, model={config.model.name})"
|
||||
)
|
||||
self.renderer, self.policy_inference = await setup_policy_inference_pool(
|
||||
config=config, tokenizer=self.tokenizer
|
||||
@@ -333,9 +334,6 @@ class Orchestrator:
|
||||
self.model_express.publish()
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
|
||||
get_logger().info(f"Initializing training batch sender ({config.rollout_transport})")
|
||||
self.sender = setup_training_batch_sender(config.output_dir, config.rollout_transport)
|
||||
|
||||
self.lora_name = config.model.lora.name if config.model.lora else None
|
||||
|
||||
self.train_source = TrainSource(self.train_envs)
|
||||
@@ -350,16 +348,31 @@ class Orchestrator:
|
||||
else:
|
||||
get_logger().info("Training from scratch")
|
||||
|
||||
# Sync inference to the incoming policy before the first step when resuming or when using
|
||||
# an in-memory transport, which rendezvouses with the trainer's startup broadcast.
|
||||
if self.resume_step is not None or config.weight_broadcast.type in ("nccl", "nixl"):
|
||||
self.packer = BatchPacker(config)
|
||||
if config.bench:
|
||||
# Bench runs have no trainer: nothing consumes shipped batches, and the
|
||||
# ZMQ sender's READY barrier would block forever.
|
||||
self.sender = None
|
||||
else:
|
||||
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
|
||||
self.sender = setup_micro_batch_sender(
|
||||
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
|
||||
)
|
||||
|
||||
# Sync inference to the incoming policy before the first step, rendezvousing
|
||||
# with the trainer's startup broadcast (v{resume_step} on resume, v0 from
|
||||
# scratch). Bench runs have no trainer, so there is no broadcast to wait for.
|
||||
if not config.bench:
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
if config.weight_broadcast.type == "nixl":
|
||||
weights_path = None
|
||||
else:
|
||||
check_exists = config.weight_broadcast.type == "filesystem"
|
||||
# Without a ckpt block, fall back to a default timeout instead of not waiting at all.
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
# The trainer's startup broadcast is always coming, so wait for it
|
||||
# rather than failing immediately when the directory is not there yet.
|
||||
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
|
||||
STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
)
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
@@ -645,7 +658,11 @@ class Orchestrator:
|
||||
records = [r.to_record() for r in effective]
|
||||
await asyncio.to_thread(save_rollouts, records, get_trace_path(config.output_dir, step, "train", "effective"))
|
||||
|
||||
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
|
||||
pack_start_time = time.perf_counter()
|
||||
micro_batch_grid = await asyncio.to_thread(self.packer.pack, batch.samples)
|
||||
pack_time = time.perf_counter() - pack_start_time
|
||||
if self.sender is not None:
|
||||
await self.sender.send(micro_batch_grid)
|
||||
self.progress.step += 1
|
||||
self.update_dispatch_gate()
|
||||
# Checkpoint the step we just shipped (resume point: continue at step + 1).
|
||||
@@ -679,6 +696,7 @@ class Orchestrator:
|
||||
"progress/total_rollouts": self.progress.total_samples,
|
||||
"progress/total_tasks": self.progress.total_problems,
|
||||
"time/step": step_time,
|
||||
"time/pack": pack_time,
|
||||
"time/save_ckpt": save_ckpt_time,
|
||||
"time/wait_for_policy": self.wait_for_policy_time,
|
||||
"step": step,
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
from transformers import AutoConfig
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.trainer.batch import build_bin_cost, prepare_batch
|
||||
from prime_rl.transport.types import MicroBatch, TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
class BatchPacker:
|
||||
"""Bin-packs a step's training samples into one micro-batch list per trainer DP rank."""
|
||||
|
||||
def __init__(self, config: OrchestratorConfig):
|
||||
self.seq_len = config.seq_len
|
||||
self.num_train_workers = config.num_train_workers
|
||||
self.pad_to_multiple_of = config.pad_to_multiple_of
|
||||
try:
|
||||
model_config = AutoConfig.from_pretrained(
|
||||
config.model.name, trust_remote_code=config.tokenizer.trust_remote_code
|
||||
)
|
||||
except Exception as e:
|
||||
get_logger().warning(
|
||||
f"Could not load model config for {config.model.name} ({e}) - "
|
||||
"packing balances by token count instead of estimated FLOPs"
|
||||
)
|
||||
model_config = None
|
||||
self.bin_cost = build_bin_cost(model_config)
|
||||
|
||||
def pack(self, samples: list[TrainingSample]) -> list[list[MicroBatch]]:
|
||||
return prepare_batch(
|
||||
rollouts=samples,
|
||||
seq_len=self.seq_len,
|
||||
num_train_workers=self.num_train_workers,
|
||||
bin_cost=self.bin_cost,
|
||||
pad_to_multiple_of=self.pad_to_multiple_of,
|
||||
)
|
||||
@@ -10,7 +10,7 @@ from pathlib import Path
|
||||
import orjson
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.utils.client import setup_inference_pool
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.logger import InterceptHandler, get_logger, setup_logger
|
||||
from prime_rl.utils.utils import (
|
||||
get_broadcast_dir,
|
||||
@@ -39,7 +39,7 @@ async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
|
||||
get_logger().info("Using direct renderer rollout client")
|
||||
else:
|
||||
get_logger().info("No policy-sourced train env — renderer kept for client-side tokenization only")
|
||||
inference_pool = await setup_inference_pool(
|
||||
inference_pool = InferencePool(
|
||||
client_config,
|
||||
model_name=model_name,
|
||||
train_client_type="renderer",
|
||||
|
||||
@@ -23,9 +23,14 @@ launch_inference_rank() {
|
||||
mkdir -p "$rpcbase"
|
||||
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")
|
||||
--vllm.data-parallel-size "$dp" --vllm.data-parallel-size-local 1 --vllm.api-server-count 1)
|
||||
[ -n "$rpc" ] && cmd+=(--vllm.data-parallel-rpc-port "$rpc")
|
||||
# Per-rank vLLM overrides go through a JSON file merged into [inference.vllm]
|
||||
# (dict-valued keys like compilation_config can't be inlined as CLI flags).
|
||||
if [ -n "$extra" ]; then
|
||||
printf '%s' "$extra" > "$rpcbase/vllm-overrides.json"
|
||||
cmd+=(--vllm @ "$rpcbase/vllm-overrides.json")
|
||||
fi
|
||||
if [ -n "$nixl" ]; then
|
||||
CUDA_VISIBLE_DEVICES="$gpus" VLLM_NIXL_SIDE_CHANNEL_PORT="$nixl" VLLM_RPC_BASE_PATH="$rpcbase" "${cmd[@]}" 2>&1 | tee -a "$log" &
|
||||
else
|
||||
|
||||
@@ -67,7 +67,9 @@ source .venv/bin/activate
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
|
||||
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
|
||||
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
|
||||
SYNC_SH
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras --all-packages
|
||||
@@ -155,7 +157,13 @@ CLEANUP_SH
|
||||
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
|
||||
# tasks so a crashed router/engine terminates the SLURM job instead of leaving
|
||||
# the surviving ranks holding nodes.
|
||||
srun --kill-on-bad-exit=1 bash -c '
|
||||
#
|
||||
# The body goes to bash on stdin through a quoted heredoc instead of a
|
||||
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
|
||||
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
|
||||
# (including in the shared _launch_*.sh.j2 includes) need no escaping. Nothing in
|
||||
# the body reads stdin, which would otherwise eat the rest of the script.
|
||||
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
# pipefail ensures `cmd | tee log` propagates `cmd` failures, and the
|
||||
# wait/cleanup block at the end of this script surfaces background
|
||||
# process crashes (router) as task failures.
|
||||
@@ -220,9 +228,9 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
export VLLM_NIXL_SIDE_CHANNEL_PORT=5600
|
||||
|
||||
# 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.
|
||||
# InferenceConfig.to_namespace() from the per-node config, so it is no longer assembled here.
|
||||
|
||||
DECODE_COMPILE_CFG='"'"'{"cudagraph_mode":"FULL_DECODE_ONLY"}'"'"'
|
||||
DECODE_COMPILE_CFG='{"cudagraph_mode":"FULL_DECODE_ONLY"}'
|
||||
|
||||
DP_PER_NODE={{ dp_per_node }}
|
||||
TP=$((GPUS_PER_NODE / DP_PER_NODE))
|
||||
@@ -293,7 +301,7 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
# 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.
|
||||
# endpoints. The kv_transfer_config is built in InferenceConfig.to_namespace() 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))
|
||||
@@ -350,4 +358,4 @@ for pid in $(jobs -p); do
|
||||
kill -TERM $pid 2>/dev/null || true
|
||||
done
|
||||
exit $EXIT_CODE
|
||||
'
|
||||
LAUNCH_SH
|
||||
|
||||
@@ -58,7 +58,6 @@ export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parall
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
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
|
||||
@@ -125,6 +124,16 @@ export MASTER_PORT=29500
|
||||
echo "MASTER_ADDR=${MASTER_ADDR}"
|
||||
echo "MASTER_PORT=${MASTER_PORT}"
|
||||
|
||||
# The orchestrator runs on trainer rank 0's node (SLURM_PROCID == NUM_INFER_NODES) by
|
||||
# default; 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.
|
||||
# The ZMQ rollout transport binds in the orchestrator process, so both sides must
|
||||
# address the orchestrator's node.
|
||||
{% if num_infer_nodes > 0 and orchestrator_on_inference %}ORCH_PROCID=$((NUM_INFER_NODES - 1)){% else %}ORCH_PROCID=$NUM_INFER_NODES{% endif %}
|
||||
export ORCH_PROCID
|
||||
export ORCH_ADDR="${HOSTNAMES[$ORCH_PROCID]}"
|
||||
echo "ORCH_ADDR=${ORCH_ADDR}"
|
||||
|
||||
# Setup environment
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
@@ -135,7 +144,9 @@ source .venv/bin/activate
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
|
||||
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
|
||||
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
|
||||
SYNC_SH
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras --all-packages
|
||||
@@ -183,7 +194,13 @@ CLEANUP_SH
|
||||
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
|
||||
# tasks so a crashed component terminates the SLURM job instead of leaving the
|
||||
# surviving ranks holding nodes.
|
||||
srun --kill-on-bad-exit=1 bash -c '
|
||||
#
|
||||
# The body goes to bash on stdin through a quoted heredoc instead of a
|
||||
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
|
||||
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
|
||||
# (including in the shared _launch_*.sh.j2 includes) need no escaping. Nothing in
|
||||
# the body reads stdin, which would otherwise eat the rest of the script.
|
||||
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
# pipefail ensures `cmd | tee log` propagates `cmd` failures, and the
|
||||
# wait/cleanup block at the end of this script surfaces background
|
||||
# process crashes (router, orchestrator) as task failures.
|
||||
@@ -258,9 +275,9 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
export VLLM_NIXL_SIDE_CHANNEL_PORT=5600
|
||||
|
||||
# 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.
|
||||
# InferenceConfig.to_namespace() from the per-node config, so it is no longer assembled here.
|
||||
|
||||
DECODE_COMPILE_CFG='"'"'{"cudagraph_mode":"FULL_DECODE_ONLY"}'"'"'
|
||||
DECODE_COMPILE_CFG='{"cudagraph_mode":"FULL_DECODE_ONLY"}'
|
||||
|
||||
REPLICA_BASE=$((REPLICA_IDX * NODES_PER_INFER_REPLICA))
|
||||
|
||||
@@ -323,7 +340,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
# 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.
|
||||
# endpoints. The kv_transfer_config is built in InferenceConfig.to_namespace() 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))
|
||||
@@ -390,15 +407,13 @@ else
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.toml \
|
||||
{% if use_zmq_transport %}--rollout_transport.host $MASTER_ADDR \
|
||||
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
|
||||
{% endif %}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 %}
|
||||
# Launch the orchestrator on the node ORCH_ADDR points at (see the ORCH_PROCID
|
||||
# computation above). Top-level (after the role if/else) so the wait -n teardown
|
||||
# covers it.
|
||||
if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --model.client.base-url $INFER_URLS"
|
||||
@@ -430,7 +445,7 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
{%- endif %}
|
||||
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $MASTER_ADDR"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
|
||||
fi
|
||||
@@ -461,4 +476,4 @@ for pid in $REMAINING_PIDS; do
|
||||
kill -TERM $pid 2>/dev/null || true
|
||||
done
|
||||
exit $EXIT_CODE
|
||||
'
|
||||
LAUNCH_SH
|
||||
|
||||
@@ -54,7 +54,9 @@ source $PROJECT_DIR/.venv/bin/activate
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
|
||||
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
|
||||
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
|
||||
SYNC_SH
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
cd $PROJECT_DIR && uv sync --all-extras --all-packages
|
||||
@@ -94,7 +96,13 @@ CLEANUP_SH
|
||||
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
|
||||
# tasks so a single trainer crash terminates the entire SLURM job instead of
|
||||
# leaving the surviving ranks (and their nodes) idle.
|
||||
srun --kill-on-bad-exit=1 bash -c '
|
||||
#
|
||||
# The body goes to bash on stdin through a quoted heredoc instead of a
|
||||
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
|
||||
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
|
||||
# need no escaping. Nothing in the body reads stdin, which would otherwise eat
|
||||
# the rest of the script.
|
||||
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
set -o pipefail
|
||||
|
||||
# Setup environment
|
||||
@@ -130,4 +138,4 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
-m prime_rl.trainer.sft.train \
|
||||
@ $CONFIG_PATH \
|
||||
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
'
|
||||
LAUNCH_SH
|
||||
|
||||
+275
-57
@@ -1,10 +1,11 @@
|
||||
import copy
|
||||
import heapq
|
||||
from collections.abc import Callable, Sequence
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
from prime_rl.trainer.utils import balanced_partition
|
||||
from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
|
||||
|
||||
# Backfill value per component weight stream when a packed sample doesn't
|
||||
@@ -13,6 +14,241 @@ from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, T
|
||||
STREAM_FILL = {"rl_weights": 1.0, "ce_weights": 0.0, "ref_kl_weights": 0.0}
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def _copy_routed_experts(routed_experts: RoutedExperts) -> RoutedExperts:
|
||||
return RoutedExperts(
|
||||
data=routed_experts.data,
|
||||
@@ -229,32 +465,28 @@ def _is_multimodal_sample(sample: MicroBatch) -> bool:
|
||||
|
||||
@dataclass
|
||||
class _MicroBatchBin:
|
||||
samples: list[tuple[int, MicroBatch]]
|
||||
samples: list[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))
|
||||
def from_sample(cls, sample: MicroBatch) -> "_MicroBatchBin":
|
||||
return cls(samples=[sample], length=len(sample.input_ids))
|
||||
|
||||
@property
|
||||
def first_sample(self) -> MicroBatch:
|
||||
return self.samples[0][1]
|
||||
|
||||
@property
|
||||
def first_lora_idx(self) -> int:
|
||||
return self.samples[0][0]
|
||||
return self.samples[0]
|
||||
|
||||
@property
|
||||
def first_multimodal_sample(self) -> MicroBatch | None:
|
||||
for _, sample in self.samples:
|
||||
for sample in self.samples:
|
||||
if _is_multimodal_sample(sample):
|
||||
return sample
|
||||
return None
|
||||
|
||||
def can_add(self, sample: MicroBatch, max_seq_len: int, lora_idx: int) -> bool:
|
||||
def can_add(self, sample: MicroBatch, max_seq_len: int) -> bool:
|
||||
# Loss routing is per token (component weight streams), so samples of
|
||||
# different loss types pack together freely. Multimodal packing is still
|
||||
# constrained by modality sidecars, length, routed experts, and LoRA/run.
|
||||
# constrained by modality sidecars, length, and routed experts.
|
||||
first_sample = self.first_sample
|
||||
if self.length + len(sample.input_ids) > max_seq_len:
|
||||
return False
|
||||
@@ -263,10 +495,6 @@ class _MicroBatchBin:
|
||||
|
||||
sample_is_mm = _is_multimodal_sample(sample)
|
||||
existing_mm_sample = self.first_multimodal_sample
|
||||
if existing_mm_sample is None and not sample_is_mm:
|
||||
return True
|
||||
if self.first_lora_idx != lora_idx:
|
||||
return False
|
||||
if existing_mm_sample is not None and sample_is_mm:
|
||||
dst = existing_mm_sample.mm_kwargs
|
||||
src = sample.mm_kwargs
|
||||
@@ -280,39 +508,39 @@ class _MicroBatchBin:
|
||||
)
|
||||
return True
|
||||
|
||||
def add(self, lora_idx: int, sample: MicroBatch) -> None:
|
||||
self.samples.append((lora_idx, sample))
|
||||
def add(self, sample: MicroBatch) -> None:
|
||||
self.samples.append(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])
|
||||
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]] = []
|
||||
ranked = sorted(self.samples, key=lambda sample: -bin_cost([len(sample.input_ids)]))
|
||||
left: list[MicroBatch] = []
|
||||
right: list[MicroBatch] = []
|
||||
left_workload = right_workload = 0
|
||||
for lora_idx, sample in ranked:
|
||||
for sample in ranked:
|
||||
sample_workload = bin_cost([len(sample.input_ids)])
|
||||
if left_workload <= right_workload:
|
||||
left.append((lora_idx, sample))
|
||||
left.append(sample)
|
||||
left_workload += sample_workload
|
||||
else:
|
||||
right.append((lora_idx, sample))
|
||||
right.append(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)),
|
||||
_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_ref_logprobs = any(sample.ref_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)
|
||||
def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
|
||||
has_ref_logprobs = any(sample.ref_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)
|
||||
# A weight stream materializes as soon as one packed sample carries it; the
|
||||
# samples that lack it get the stream's identity fill (STREAM_FILL).
|
||||
has_stream = {name: any(getattr(s, name) is not None for _, s in bin_content.samples) for name in STREAM_FILL}
|
||||
has_stream = {name: any(getattr(s, name) is not None for s in bin_content.samples) for name in STREAM_FILL}
|
||||
|
||||
input_ids: list[int] = []
|
||||
loss_mask: list[bool] = []
|
||||
@@ -327,9 +555,8 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
|
||||
streams: dict[str, list[float] | None] = {name: ([] if has_stream[name] else None) for name in STREAM_FILL}
|
||||
seq_lens: list[int] = []
|
||||
routed_experts: RoutedExperts | None = None
|
||||
lora_num_tokens = [0] * num_loras
|
||||
|
||||
for lora_idx, sample in bin_content.samples:
|
||||
for sample in bin_content.samples:
|
||||
sample_len = len(sample.input_ids)
|
||||
input_ids.extend(sample.input_ids)
|
||||
loss_mask.extend(sample.loss_mask)
|
||||
@@ -365,9 +592,8 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
|
||||
mm_kwargs[key].data += sample.mm_kwargs[key].data
|
||||
mm_kwargs[key].shape[0] += sample.mm_kwargs[key].shape[0]
|
||||
seq_lens.extend(sample.seq_lens)
|
||||
lora_num_tokens[lora_idx] += sample_len
|
||||
|
||||
sequence_lengths = [len(sample.input_ids) for _, sample in bin_content.samples]
|
||||
sequence_lengths = [len(sample.input_ids) for sample in bin_content.samples]
|
||||
assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids))
|
||||
assert sum(seq_lens) == len(input_ids), (seq_lens, len(input_ids))
|
||||
|
||||
@@ -380,7 +606,6 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
|
||||
sequence_lengths=sequence_lengths,
|
||||
ref_logprobs=ref_logprobs,
|
||||
temperatures=temperatures,
|
||||
lora_num_tokens=lora_num_tokens,
|
||||
routed_experts=routed_experts,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
env_names=env_names,
|
||||
@@ -410,9 +635,8 @@ def _expand_bins_by_splitting(
|
||||
|
||||
|
||||
def packed_samples_into_micro_bs(
|
||||
samples: list[tuple[int, MicroBatch]],
|
||||
samples: list[MicroBatch],
|
||||
max_seq_len: int,
|
||||
num_loras: int,
|
||||
num_train_workers: int,
|
||||
bin_cost: Callable[[Sequence[int]], int],
|
||||
) -> list[MicroBatch]:
|
||||
@@ -421,24 +645,24 @@ def packed_samples_into_micro_bs(
|
||||
We follow the First Fit Decreasing algorithm to pack the samples into bins and minimize potential padding while never truncating.
|
||||
With per-token temperatures, samples can be packed together regardless of their temperature values.
|
||||
|
||||
Multimodal samples pack with text spans from the same run/LoRA and with
|
||||
compatible eager ``mm_kwargs`` samples. Packed batches preserve sample
|
||||
boundaries in ``seq_lens``.
|
||||
Multimodal samples pack with text spans and with compatible eager
|
||||
``mm_kwargs`` samples. Packed batches preserve sample boundaries in
|
||||
``seq_lens``.
|
||||
"""
|
||||
# Sort by (lora_idx, -length) for packing efficiency
|
||||
samples.sort(key=lambda x: (x[0], -len(x[1].input_ids)))
|
||||
# Sort by decreasing length for packing efficiency
|
||||
samples.sort(key=lambda sample: -len(sample.input_ids))
|
||||
|
||||
bins: list[_MicroBatchBin] = []
|
||||
|
||||
for idx, sample in samples:
|
||||
for sample in samples:
|
||||
# Try to find a bin that can fit this sequence. Multimodal samples only
|
||||
# pack when their sidecar tensors are compatible.
|
||||
for bin_content in bins:
|
||||
if bin_content.can_add(sample, max_seq_len, idx):
|
||||
bin_content.add(idx, sample)
|
||||
if bin_content.can_add(sample, max_seq_len):
|
||||
bin_content.add(sample)
|
||||
break
|
||||
else:
|
||||
bins.append(_MicroBatchBin.from_sample(idx, sample))
|
||||
bins.append(_MicroBatchBin.from_sample(sample))
|
||||
|
||||
if num_train_workers > 1:
|
||||
target_count = max(
|
||||
@@ -447,7 +671,7 @@ def packed_samples_into_micro_bs(
|
||||
)
|
||||
_expand_bins_by_splitting(bins, target_count, bin_cost)
|
||||
|
||||
return [_materialize_bin(bin_content, num_loras) for bin_content in bins]
|
||||
return [_materialize_bin(bin_content) for bin_content in bins]
|
||||
|
||||
|
||||
def _distribute_group(
|
||||
@@ -505,10 +729,6 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
|
||||
stream = getattr(micro_batch, stream_name)
|
||||
if stream is not None:
|
||||
stream.extend([0.0] * padding_size)
|
||||
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:
|
||||
@@ -577,8 +797,6 @@ def prepare_batch(
|
||||
rollouts: list[TrainingSample],
|
||||
seq_len: int,
|
||||
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]]:
|
||||
@@ -591,9 +809,9 @@ def prepare_batch(
|
||||
a text-only batch, the all-gather will hang. We separate micro batches by modality
|
||||
and distribute them so that at each step index, all ranks see the same modality.
|
||||
"""
|
||||
all_samples = [(idx, prepare_sample(rollout, seq_len)) for idx, rollout in zip(idxs, rollouts)]
|
||||
all_samples = [prepare_sample(rollout, seq_len) for rollout in rollouts]
|
||||
|
||||
micro_batches = packed_samples_into_micro_bs(all_samples, seq_len, num_loras, num_train_workers, bin_cost)
|
||||
micro_batches = packed_samples_into_micro_bs(all_samples, seq_len, 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
|
||||
|
||||
@@ -3,7 +3,7 @@ import gc
|
||||
import shutil
|
||||
import time
|
||||
import warnings
|
||||
from dataclasses import asdict
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -22,10 +22,9 @@ from transformers.processing_utils import ProcessorMixin
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.configs.trainer import CheckpointConfig, LoRAConfig, WeightCheckpointConfig
|
||||
from prime_rl.trainer.lora import has_lora_layers, save_lora_config
|
||||
from prime_rl.trainer.lora import get_lora_state, has_lora_layers, save_lora_config
|
||||
from prime_rl.trainer.models import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.optim import CPUOffloadOptimizer
|
||||
from prime_rl.trainer.runs import Progress, get_multi_run_manager
|
||||
from prime_rl.trainer.weights import (
|
||||
gather_weights_on_master,
|
||||
save_state_dict,
|
||||
@@ -35,6 +34,13 @@ from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path, get_weights_dir
|
||||
|
||||
|
||||
@dataclass
|
||||
class Progress:
|
||||
step: int = 1
|
||||
total_tokens: int = 0
|
||||
total_samples: int = 0
|
||||
|
||||
|
||||
def _try_rmtree(path: Path, logger) -> None:
|
||||
"""Remove a directory tree, logging and skipping on failure."""
|
||||
try:
|
||||
@@ -363,7 +369,7 @@ class WeightCheckpointManager:
|
||||
f"base_model.model.{key}": (value.full_tensor() if isinstance(value, DTensor) else value).to(
|
||||
"cpu", non_blocking=False
|
||||
)
|
||||
for key, value in get_multi_run_manager().get_state_dict_for_run(0).items()
|
||||
for key, value in get_lora_state().adapter_state_dict().items()
|
||||
}
|
||||
|
||||
if not lora_state_dict:
|
||||
|
||||
@@ -1,21 +1,107 @@
|
||||
import re
|
||||
from typing import Dict, List
|
||||
from typing import Callable, Dict, List
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from prime_rl.configs.trainer import LoRAConfig
|
||||
from prime_rl.trainer.models.layers.lora import MultiLoRALinear, MultiLoRAModule
|
||||
from prime_rl.trainer.models.layers.lora import (
|
||||
MultiLoRALinear,
|
||||
MultiLoRAModule,
|
||||
get_lora_num_tokens,
|
||||
get_multilora_scaling,
|
||||
set_lora_num_tokens,
|
||||
set_multilora_scaling,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lora.multi_moe import (
|
||||
MultiLoRAGptOssGroupedExperts,
|
||||
MultiLoRAGroupedExperts,
|
||||
MultiLoRANonGatedGroupedExperts,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.moe import GptOssGroupedExperts, GroupedExperts, NonGatedGroupedExperts
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
class LoRAState:
|
||||
"""Module registry + shared tensors for the single LoRA adapter.
|
||||
|
||||
Owns the canonical ``lora_num_tokens`` / ``scaling_factors`` tensors the
|
||||
LoRA layers read (the layers capture references at construction, so this
|
||||
must exist before ``apply_lora_to_model`` builds them) and the registry of
|
||||
adapted modules used for optimizer setup, adapter state dicts, and
|
||||
parameter resets."""
|
||||
|
||||
def __init__(self, config: LoRAConfig, device: torch.device):
|
||||
set_lora_num_tokens(None, reset_reference=True)
|
||||
set_multilora_scaling(None, reset_reference=True)
|
||||
set_lora_num_tokens(torch.zeros(1, dtype=torch.int32, device=device), reset_reference=True)
|
||||
set_multilora_scaling(
|
||||
torch.full((1,), config.alpha / config.rank, dtype=torch.bfloat16, device=device),
|
||||
reset_reference=True,
|
||||
)
|
||||
self.lora_num_tokens = get_lora_num_tokens()
|
||||
self.scaling_factors = get_multilora_scaling()
|
||||
self._modules: list[tuple[str, MultiLoRAModule]] = []
|
||||
self._adapter_state_dict_converter: Callable[[dict[str, torch.Tensor]], dict[str, torch.Tensor]] | None = None
|
||||
|
||||
def register_adapter_state_dict_converter(
|
||||
self, converter: Callable[[dict[str, torch.Tensor]], dict[str, torch.Tensor]]
|
||||
) -> None:
|
||||
"""Register a converter applied to adapter state dicts (e.g. model.convert_adapter_to_hf)."""
|
||||
self._adapter_state_dict_converter = converter
|
||||
|
||||
def register_module(self, prefix: str, module: MultiLoRAModule) -> None:
|
||||
"""Register an adapted module with its FQN prefix (e.g. "model.layers.0.self_attn.q_proj")."""
|
||||
self._modules.append((prefix, module))
|
||||
|
||||
def named_adapter_parameters(self) -> list[tuple[str, nn.Parameter]]:
|
||||
"""Named parameters of the adapter across all registered modules."""
|
||||
params = []
|
||||
for prefix, module in self._modules:
|
||||
for name, param in module.named_parameters_for_adapter(0):
|
||||
params.append((f"{prefix}.{name}.weight", param))
|
||||
return params
|
||||
|
||||
def adapter_state_dict(self) -> dict[str, torch.Tensor]:
|
||||
"""Adapter-only state dict, converted for HF compatibility when a converter is registered."""
|
||||
state_dict = {}
|
||||
for prefix, module in self._modules:
|
||||
# MoE modules expose a custom state_dict_for_adapter returning the
|
||||
# vLLM-compatible per-expert format
|
||||
if hasattr(module, "state_dict_for_adapter"):
|
||||
for name, tensor in module.state_dict_for_adapter(0).items():
|
||||
state_dict[f"{prefix}.{name}"] = tensor.detach()
|
||||
else:
|
||||
for name, param in module.named_parameters_for_adapter(0):
|
||||
state_dict[f"{prefix}.{name}.weight"] = param.detach()
|
||||
|
||||
if self._adapter_state_dict_converter is not None:
|
||||
state_dict = self._adapter_state_dict_converter(state_dict)
|
||||
return state_dict
|
||||
|
||||
def reset_adapter_parameters(self) -> None:
|
||||
"""Reset the adapter to fresh initialization across all registered modules."""
|
||||
for _, module in self._modules:
|
||||
module.reset_parameters(0)
|
||||
|
||||
|
||||
_LORA_STATE: LoRAState | None = None
|
||||
|
||||
|
||||
def get_lora_state() -> LoRAState:
|
||||
"""Returns the LoRAState singleton. Initialized by ``apply_lora_to_model``."""
|
||||
if _LORA_STATE is None:
|
||||
raise RuntimeError("LoRAState not initialized. Apply LoRA to the model first (`apply_lora_to_model`).")
|
||||
return _LORA_STATE
|
||||
|
||||
|
||||
def setup_lora_state(config: LoRAConfig, device: torch.device) -> LoRAState:
|
||||
global _LORA_STATE
|
||||
_LORA_STATE = LoRAState(config, device)
|
||||
return _LORA_STATE
|
||||
|
||||
|
||||
def strip_lora_from_state_dict(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
|
||||
"""Strip LoRA from the state dict."""
|
||||
new_state_dict = {}
|
||||
@@ -143,9 +229,9 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
logger = get_logger()
|
||||
from prime_rl.trainer.models import PreTrainedModelPrimeRL
|
||||
|
||||
lora_state = setup_lora_state(config, torch.device("cuda", get_world().local_rank))
|
||||
if isinstance(model, PreTrainedModelPrimeRL):
|
||||
get_multi_run_manager().register_adapter_state_dict_converter(type(model).convert_adapter_to_hf)
|
||||
n_loras = get_multi_run_manager().max_runs
|
||||
lora_state.register_adapter_state_dict_converter(type(model).convert_adapter_to_hf)
|
||||
|
||||
from torch.distributed.fsdp import FSDPModule
|
||||
|
||||
@@ -172,7 +258,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
lora_module = MultiLoRALinear(
|
||||
base_layer=base_module,
|
||||
rank=config.rank,
|
||||
n_adapters=n_loras,
|
||||
n_adapters=1,
|
||||
alpha=config.alpha,
|
||||
dropout=config.dropout,
|
||||
)
|
||||
@@ -181,7 +267,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
lora_module = MultiLoRAGroupedExperts(
|
||||
base_layer=base_module,
|
||||
rank=config.rank,
|
||||
n_adapters=n_loras,
|
||||
n_adapters=1,
|
||||
alpha=config.alpha,
|
||||
dropout=config.dropout,
|
||||
)
|
||||
@@ -190,7 +276,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
lora_module = MultiLoRANonGatedGroupedExperts(
|
||||
base_layer=base_module,
|
||||
rank=config.rank,
|
||||
n_adapters=n_loras,
|
||||
n_adapters=1,
|
||||
alpha=config.alpha,
|
||||
dropout=config.dropout,
|
||||
)
|
||||
@@ -199,7 +285,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
lora_module = MultiLoRAGptOssGroupedExperts(
|
||||
base_layer=base_module,
|
||||
rank=config.rank,
|
||||
n_adapters=n_loras,
|
||||
n_adapters=1,
|
||||
alpha=config.alpha,
|
||||
dropout=config.dropout,
|
||||
)
|
||||
@@ -210,7 +296,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
)
|
||||
continue
|
||||
|
||||
lora_module.register_with_runs(get_multi_run_manager(), module_name)
|
||||
lora_state.register_module(module_name, lora_module)
|
||||
_set_module_by_name(model, module_name, lora_module)
|
||||
|
||||
freeze_all_except_lora_and_specified(model, config)
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
from abc import abstractmethod
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.trainer.runs import MultiRunManager
|
||||
|
||||
_LORA_PREFIX = "base_layer."
|
||||
|
||||
# Global state for multilora - initialized once in train.py, referenced by modules
|
||||
@@ -123,24 +120,6 @@ class MultiLoRAModule(nn.Module):
|
||||
"""
|
||||
...
|
||||
|
||||
def register_with_runs(self, runs: "MultiRunManager", prefix: str) -> None:
|
||||
"""Register this module with the MultiRunManager system.
|
||||
|
||||
This method should be called after FSDP/compile/AC setup as these
|
||||
transformations may change the underlying parameters while preserving
|
||||
the module.
|
||||
|
||||
The MultiRunManager class will use this registration to:
|
||||
- Get named parameters for specific run indices (for optimizer setup)
|
||||
- Reset parameters when new runs are created
|
||||
- Construct sliced state dicts for weight broadcast
|
||||
|
||||
Args:
|
||||
runs: The MultiRunManager instance to register with
|
||||
prefix: The module's name/prefix in the model (e.g., "model.layers.0.self_attn.q_proj")
|
||||
"""
|
||||
runs.register_module(prefix, self)
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
"""Forward missing attributes to wrapped module."""
|
||||
try:
|
||||
|
||||
@@ -1,233 +0,0 @@
|
||||
"""Multi-run checkpointing for RL training.
|
||||
|
||||
MultiCheckpointManager owns per-run CheckpointManagers and AppStates,
|
||||
each saving to its own run directory.
|
||||
"""
|
||||
|
||||
import shutil
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch.distributed.checkpoint.stateful import Stateful
|
||||
|
||||
from prime_rl.configs.trainer import CheckpointConfig
|
||||
from prime_rl.trainer.ckpt import CheckpointManager
|
||||
from prime_rl.trainer.runs import Progress, get_multi_run_manager
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.pathing import get_stable_ckpt_steps
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.trainer.optim import MultiLoRAOptimizer
|
||||
from prime_rl.trainer.scheduler import MultiLoRAScheduler
|
||||
|
||||
|
||||
class RunState(Stateful):
|
||||
"""Per-run state wrapper - just like AppState but for adapter weights."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_state_dict: dict[str, Any],
|
||||
optimizer,
|
||||
scheduler,
|
||||
progress: Progress,
|
||||
):
|
||||
self.model_state_dict = model_state_dict
|
||||
self.optimizer = optimizer
|
||||
self.scheduler = scheduler
|
||||
self.progress = progress
|
||||
|
||||
def state_dict(self) -> dict[str, Any]:
|
||||
state = {
|
||||
"model": self.model_state_dict,
|
||||
"progress": asdict(self.progress),
|
||||
}
|
||||
if self.optimizer is not None:
|
||||
state["optimizer"] = self.optimizer.state_dict()
|
||||
if self.scheduler is not None:
|
||||
state["scheduler"] = self.scheduler.state_dict()
|
||||
return state
|
||||
|
||||
@torch.no_grad()
|
||||
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
|
||||
# Load adapter weights
|
||||
for key, value in state_dict["model"].items():
|
||||
if key in self.model_state_dict:
|
||||
self.model_state_dict[key].copy_(value)
|
||||
# Load optimizer
|
||||
if "optimizer" in state_dict and self.optimizer is not None:
|
||||
self.optimizer.load_state_dict(state_dict["optimizer"])
|
||||
# Load scheduler
|
||||
if "scheduler" in state_dict and self.scheduler is not None:
|
||||
self.scheduler.load_state_dict(state_dict["scheduler"])
|
||||
# Don't load progress because it resets packers count
|
||||
# There will be a step issue if we load progress
|
||||
|
||||
|
||||
class MultiCheckpointManager:
|
||||
"""Owns per-run CheckpointManagers and AppStates."""
|
||||
|
||||
def __init__(self, output_dir: Path):
|
||||
self.output_dir = output_dir
|
||||
self.multi_run_manager = get_multi_run_manager()
|
||||
self.world = get_world()
|
||||
self.logger = get_logger()
|
||||
self.managers: list[CheckpointManager | None] = [None] * self.multi_run_manager.max_runs
|
||||
self.multi_run_manager.register_deletion_hook(self._run_deletion_hook)
|
||||
self.multi_run_manager.register_creation_hook(self._run_creation_hook)
|
||||
|
||||
def _run_deletion_hook(self, idx: int, run_id: str) -> None:
|
||||
self.managers[idx] = None
|
||||
|
||||
def _run_creation_hook(self, idx: int, run_id: str) -> None:
|
||||
self.managers[idx] = self._maybe_create_manager(idx)
|
||||
|
||||
def _maybe_create_manager(self, idx: int) -> CheckpointManager | None:
|
||||
ckpt_config = self.multi_run_manager.config[idx].ckpt
|
||||
if ckpt_config is None:
|
||||
return None
|
||||
|
||||
config = CheckpointConfig(
|
||||
interval=ckpt_config.interval,
|
||||
keep_last=ckpt_config.keep_last,
|
||||
keep_interval=ckpt_config.keep_interval,
|
||||
)
|
||||
run_dir = self.multi_run_manager.get_run_dir(idx)
|
||||
manager = CheckpointManager(run_dir, config)
|
||||
self.managers[idx] = manager
|
||||
return manager
|
||||
|
||||
def _should_save(self, idx: int, step: int) -> bool:
|
||||
"""Determine if a checkpoint should be saved for a given run and step."""
|
||||
ckpt_config = self.multi_run_manager.config[idx].ckpt
|
||||
if ckpt_config is None or ckpt_config.interval is None:
|
||||
return False
|
||||
if step <= 0 or step % ckpt_config.interval != 0:
|
||||
return False
|
||||
# Check if already saved this step
|
||||
return step not in self.managers[idx].ckpt_steps
|
||||
|
||||
def save(
|
||||
self,
|
||||
optimizer: "MultiLoRAOptimizer",
|
||||
scheduler: "MultiLoRAScheduler",
|
||||
) -> None:
|
||||
for idx in self.multi_run_manager.used_idxs:
|
||||
# pack() already advanced progress to the next step, so the step just finished
|
||||
# (and its broadcasts/step_{step} weights) is progress - 1.
|
||||
step = self.multi_run_manager.progress[idx].step - 1
|
||||
if not self._should_save(idx, step):
|
||||
continue
|
||||
|
||||
manager = self.managers[idx]
|
||||
|
||||
# We have a very wide try-except because we dont want to crash the trainer over one run having issues
|
||||
try:
|
||||
model_state_dict = {
|
||||
k: v.data.detach().clone() for k, v in self.multi_run_manager.get_named_parameters_for_run(idx)
|
||||
}
|
||||
run_state = RunState(
|
||||
model_state_dict,
|
||||
optimizer.optimizers[idx],
|
||||
scheduler.schedulers[idx],
|
||||
self.multi_run_manager.progress[idx],
|
||||
)
|
||||
ckpt_path = manager.get_ckpt_path(step)
|
||||
ckpt_path.mkdir(parents=True, exist_ok=True)
|
||||
self.logger.info(
|
||||
f"Saving checkpoint for run {idx} at step {step} to {ckpt_path / f'rank_{self.world.rank}.pt'}"
|
||||
)
|
||||
torch.save(run_state.state_dict(), ckpt_path / f"rank_{self.world.rank}.pt")
|
||||
|
||||
# Copy broadcast folder to checkpoint
|
||||
# This way, we only need to save the checkpoint folder
|
||||
if self.world.is_master:
|
||||
run_dir = self.multi_run_manager.get_run_dir(idx)
|
||||
broadcast_src = run_dir / "broadcasts" / f"step_{step}"
|
||||
weight_dst = run_dir / "checkpoints" / f"step_{step}" / "weight"
|
||||
try:
|
||||
shutil.copytree(broadcast_src, weight_dst)
|
||||
except FileNotFoundError:
|
||||
self.logger.error(
|
||||
f"Broadcast folder not found for run {idx} at step {step}. Looking for it in {broadcast_src}"
|
||||
)
|
||||
dist.barrier()
|
||||
manager.mark_stable(step)
|
||||
manager.ckpt_steps.append(step)
|
||||
except FileNotFoundError:
|
||||
self.logger.warning(f"Run {idx} deleted during checkpoint, skipping")
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error checkpointing run {idx}: {e}")
|
||||
dist.barrier()
|
||||
# If the run is deleted, remove the run directory
|
||||
# This is avoid the creation of zombie runs when the directory is deleted while we are checkpointing which recreates the directory
|
||||
# Ideally we move this to discover but lets have here for now
|
||||
if (
|
||||
self.multi_run_manager.get_orchestrator_config(self.multi_run_manager.idx_2_id[idx]) is None
|
||||
and self.world.is_master
|
||||
):
|
||||
try:
|
||||
self.logger.warning(f"Run {idx} deleted during checkpoint, removing run directory")
|
||||
shutil.rmtree(self.multi_run_manager.get_run_dir(idx))
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error removing run directory for run {idx}: {e}")
|
||||
dist.barrier()
|
||||
|
||||
def load_run(
|
||||
self,
|
||||
idx: int,
|
||||
optimizer: "MultiLoRAOptimizer",
|
||||
scheduler: "MultiLoRAScheduler",
|
||||
) -> bool:
|
||||
if (
|
||||
self.multi_run_manager.config[idx].ckpt is None
|
||||
or self.multi_run_manager.config[idx].ckpt.resume_step is None
|
||||
):
|
||||
return False
|
||||
|
||||
manager = self.managers[idx]
|
||||
if manager is None:
|
||||
return False
|
||||
|
||||
step = self.multi_run_manager.config[idx].ckpt.resume_step
|
||||
if step == -1:
|
||||
stable_steps = get_stable_ckpt_steps(manager.ckpt_dir)
|
||||
if not stable_steps:
|
||||
return False
|
||||
step = max(stable_steps)
|
||||
|
||||
try:
|
||||
model_state_dict = dict(self.multi_run_manager.get_named_parameters_for_run(idx))
|
||||
run_state = RunState(
|
||||
model_state_dict,
|
||||
optimizer.optimizers[idx],
|
||||
scheduler.schedulers[idx],
|
||||
self.multi_run_manager.progress[idx],
|
||||
)
|
||||
ckpt_path = manager.get_ckpt_path(step)
|
||||
if not ckpt_path.exists():
|
||||
raise FileNotFoundError(f"Checkpoint not found at {ckpt_path}")
|
||||
self.logger.info(f"Loading checkpoint from {ckpt_path}")
|
||||
state_dict = torch.load(ckpt_path / f"rank_{self.world.rank}.pt", weights_only=False)
|
||||
run_state.load_state_dict(state_dict)
|
||||
|
||||
self.logger.info(f"Resumed run {self.multi_run_manager.idx_2_id[idx]} from step {step}")
|
||||
return True
|
||||
except Exception as e:
|
||||
self.logger.error(f"Error loading checkpoint for run {idx}: {e}")
|
||||
return False
|
||||
|
||||
def maybe_clean(self) -> None:
|
||||
if not self.world.is_master:
|
||||
return
|
||||
for idx in self.multi_run_manager.used_idxs:
|
||||
if self.managers[idx] is None:
|
||||
continue
|
||||
self.managers[idx].maybe_clean()
|
||||
|
||||
|
||||
def setup_multi_checkpoint_manager(output_dir: Path) -> tuple[MultiCheckpointManager, None]:
|
||||
return MultiCheckpointManager(output_dir), None
|
||||
@@ -1,5 +1,4 @@
|
||||
import copy
|
||||
from typing import Callable
|
||||
|
||||
import torch
|
||||
from dion import Muon
|
||||
@@ -9,7 +8,6 @@ from torch.optim import SGD, AdamW, Optimizer
|
||||
|
||||
from prime_rl.configs.trainer import OptimizerConfig
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.trainer.sign_sgd import SignSGD
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -112,16 +110,8 @@ def setup_optimizer(
|
||||
config: OptimizerConfig,
|
||||
named_params: list[tuple[str, nn.Parameter]],
|
||||
parallel_dims: ParallelDims,
|
||||
lora: bool = False,
|
||||
cpu_offload: bool = False,
|
||||
) -> Optimizer | CPUOffloadOptimizer:
|
||||
if lora:
|
||||
# Wait for run 0 to be created in the multi run manager
|
||||
# Otherwise, the creation will reset the parameters
|
||||
multi_run_manager = get_multi_run_manager()
|
||||
multi_run_manager.wait_for_run(0)
|
||||
named_params = multi_run_manager.get_named_parameters_for_run(0)
|
||||
|
||||
optimizer = _create_optimizer(config, named_params, parallel_dims)
|
||||
|
||||
if cpu_offload:
|
||||
@@ -252,65 +242,3 @@ def _create_muon_optimizer(
|
||||
fsdp_mesh_dim=1 if parallel_dims.dp_replicate_enabled else 0,
|
||||
)
|
||||
return optimizer
|
||||
|
||||
|
||||
class MultiLoRAOptimizer:
|
||||
def __init__(self, config: OptimizerConfig, parallel_dims: ParallelDims):
|
||||
self.config = config
|
||||
self.parallel_dims = parallel_dims
|
||||
self.multi_run_manager = get_multi_run_manager()
|
||||
self.logger = get_logger()
|
||||
|
||||
self.optimizers: list[Optimizer | None] = [None] * self.multi_run_manager.max_runs
|
||||
self._post_creation_callbacks: list[Callable[[Optimizer, int], None]] = []
|
||||
|
||||
# Register creation hook for optimizer setup
|
||||
# The MultiRunManager class handles parameter reset internally when new runs are created
|
||||
self.multi_run_manager.register_creation_hook(self.optimizer_creation_hook)
|
||||
|
||||
def register_post_creation_callback(
|
||||
self, callback: Callable[[Optimizer, int], None], index: int | None = None
|
||||
) -> None:
|
||||
"""Register a callback to be called after an optimizer is created.
|
||||
|
||||
Args:
|
||||
callback: A callable that takes (optimizer: Optimizer, idx: int) as arguments.
|
||||
index: Optional index to insert at. If None, appends to end.
|
||||
"""
|
||||
if index is None:
|
||||
self._post_creation_callbacks.append(callback)
|
||||
else:
|
||||
self._post_creation_callbacks.insert(index, callback)
|
||||
|
||||
def optimizer_creation_hook(self, idx: int, run_id: str) -> None:
|
||||
# Get named parameters for this run from the MultiRunManager system
|
||||
named_params = self.multi_run_manager.get_named_parameters_for_run(idx)
|
||||
|
||||
lr = self.multi_run_manager.config[idx].optim.lr
|
||||
self.optimizers[idx] = _create_optimizer(self.config, named_params, self.parallel_dims, lr)
|
||||
|
||||
# Call post-creation callbacks in order
|
||||
for callback in self._post_creation_callbacks:
|
||||
callback(self.optimizers[idx], idx)
|
||||
|
||||
def step(self):
|
||||
for idx in self.multi_run_manager.ready_to_update_idxs:
|
||||
self.optimizers[idx].step()
|
||||
|
||||
def zero_grad(self):
|
||||
for idx in self.multi_run_manager.ready_to_update_idxs:
|
||||
self.optimizers[idx].zero_grad()
|
||||
|
||||
def get_current_lr(self, idx: int | None = None) -> float:
|
||||
if idx is None:
|
||||
for idx in self.multi_run_manager.ready_to_update_idxs:
|
||||
return self.optimizers[idx].param_groups[0]["lr"]
|
||||
else:
|
||||
self.logger.warning("No runs are ready to update. Returning 0.0 for current learning rate.")
|
||||
return 0.0
|
||||
else:
|
||||
return self.optimizers[idx].param_groups[0]["lr"]
|
||||
|
||||
|
||||
def setup_multi_optimizer(config: OptimizerConfig, parallel_dims: ParallelDims) -> MultiLoRAOptimizer:
|
||||
return MultiLoRAOptimizer(config, parallel_dims)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user