Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1046b876c | ||
|
|
381df0a658 | ||
|
|
532d622b4c | ||
|
|
ec92686fbc | ||
|
|
fb31b51e84 | ||
|
|
33b7d19cb1 | ||
|
|
56a9402953 | ||
|
|
0c0b92f99c | ||
|
|
84ce4d6677 | ||
|
|
01e959596a | ||
|
|
738eb5016a | ||
|
|
06eb91d7c8 | ||
|
|
327f378e07 | ||
|
|
4aeca13870 | ||
|
|
8ab86036b2 | ||
|
|
f0bc8f1fab | ||
|
|
756f217f22 | ||
|
|
78cef2844f | ||
|
|
ef42886edc | ||
|
|
ed05a1418d | ||
|
|
1ef8f1a843 | ||
|
|
e229a286f2 | ||
|
|
2ffe374e02 | ||
|
|
bbb90a1b41 | ||
|
|
9f0d41e23d | ||
|
|
e0638c7eb6 |
@@ -34,8 +34,42 @@ concurrency:
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
authorize:
|
||||
name: Authorize dispatcher
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Require maintain or admin
|
||||
# Gate MANUAL dispatches only; other events (e.g. release) are
|
||||
# already privileged and pass through. Guard the step, not the job —
|
||||
# a skipped job would skip `prepare` via `needs: authorize`.
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
ACTOR: ${{ github.triggering_actor }}
|
||||
REPO: ${{ github.repository }}
|
||||
run: |
|
||||
# Restricted to repo members with maintain or admin. Automated
|
||||
# in-repo dispatches (devx_tag dev-image builds, the release build)
|
||||
# run as github-actions[bot] via GITHUB_TOKEN — allow those through.
|
||||
if [ "$ACTOR" = "github-actions[bot]" ]; then
|
||||
echo "Dispatcher is repo automation ($ACTOR); allowed."
|
||||
exit 0
|
||||
fi
|
||||
role=$(gh api "repos/${REPO}/collaborators/${ACTOR}/permission" --jq '.role_name' 2>/dev/null || true)
|
||||
echo "Dispatcher $ACTOR has repo role: ${role:-<none>}"
|
||||
case "$role" in
|
||||
admin|maintain)
|
||||
echo "Authorized." ;;
|
||||
*)
|
||||
echo "::error::$ACTOR (role: ${role:-none}) is not allowed to trigger image builds; requires maintain or admin." >&2
|
||||
exit 1 ;;
|
||||
esac
|
||||
|
||||
prepare:
|
||||
name: Prepare build
|
||||
needs: authorize
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -81,27 +115,30 @@ jobs:
|
||||
INPUT_TAG: ${{ env.BUILD_TAG }}
|
||||
PLATFORMS: ${{ env.BUILD_PLATFORMS }}
|
||||
run: |
|
||||
case "$INPUT_REF" in
|
||||
main|v[0-9]*|*.dev[0-9]*) ;;
|
||||
*)
|
||||
echo "ref '${INPUT_REF}' not allowed for ghcr publish (must be main, v*, or *.dev*)" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -n "$INPUT_TAG" ] && [ "$INPUT_TAG" != "$INPUT_REF" ] && [ "$INPUT_REF" != "main" ]; then
|
||||
echo "custom 'tag' that differs from 'ref' is only allowed when ref=main; got ref='${INPUT_REF}' tag='${INPUT_TAG}'" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
raw_tag="$INPUT_TAG"
|
||||
if [ -z "$raw_tag" ]; then
|
||||
raw_tag="$INPUT_REF"
|
||||
sanitize() {
|
||||
echo "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//' | cut -c1-50
|
||||
}
|
||||
|
||||
# A ref that is exactly a git tag builds under that tag verbatim;
|
||||
# any other ref (branch / arbitrary commit) is prefixed with
|
||||
# `git describe` so the tag carries the nearest release, commit
|
||||
# distance and short sha (e.g. v0.7.0-42-g1a2b3c4d5-fix-my-branch)
|
||||
# and can't collide with a clean release tag.
|
||||
if [ -n "$INPUT_TAG" ]; then
|
||||
tag=$(sanitize "$INPUT_TAG")
|
||||
elif tag=$(git describe --tags --exact-match 2>/dev/null); then
|
||||
:
|
||||
else
|
||||
tag="$(git describe --tags --always)-$(sanitize "$INPUT_REF")"
|
||||
fi
|
||||
|
||||
tag=$(echo "$raw_tag" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | cut -c1-50 | sed 's/^-//;s/-$//')
|
||||
if [ -z "$tag" ]; then
|
||||
echo "Could not derive a valid image tag from '${raw_tag}'." >&2
|
||||
echo "Could not derive a valid image tag from ref='${INPUT_REF}' tag='${INPUT_TAG}'." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -156,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 }}
|
||||
|
||||
+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*)
|
||||
|
||||
+3
-2
@@ -8,8 +8,9 @@ Configurations for running prime-rl.
|
||||
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
|
||||
- **`ci/`** — integration and nightly configs used by CI.
|
||||
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
|
||||
(per-algorithm smokes) and `fake/` (fake-data trainer/SFT smokes). Not guaranteed
|
||||
functional or up to date.
|
||||
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and `multi-env/`
|
||||
(two reverse-text train sources + one eval source, one env server per source). Not
|
||||
guaranteed functional or up to date.
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/<env>/rl.toml
|
||||
|
||||
@@ -34,9 +34,20 @@ max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort-v1"
|
||||
min_turns = 3
|
||||
max_turns = 5
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
|
||||
@@ -21,17 +21,23 @@ seq_len = 8192
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "math-env-v1"
|
||||
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
dataset_subset = "default"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
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"
|
||||
|
||||
@@ -24,9 +24,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -42,11 +42,17 @@ max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
env.taskset = { id = "wiki-search-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wiki-search-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference.model]
|
||||
[inference.vllm]
|
||||
tool_call_parser = "hermes"
|
||||
|
||||
@@ -23,9 +23,15 @@ group_size = 8
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
env.taskset = { id = "wordle-v1" }
|
||||
env.player.harness = { id = "null" }
|
||||
env.player.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wordle-v1"
|
||||
|
||||
[orchestrator.train.source.env.player.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
@@ -24,9 +24,23 @@ max_completion_tokens = 384
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset = { id = "alphabet-sort-v1", min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, task = { similarity_power = 4, power_per_turn = false } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort-v1"
|
||||
min_turns = 2
|
||||
max_turns = 2
|
||||
min_names_per_turn = 1
|
||||
max_names_per_turn = 3
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
similarity_power = 4
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -28,15 +28,23 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
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"
|
||||
|
||||
@@ -27,15 +27,23 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
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"
|
||||
|
||||
@@ -27,16 +27,20 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
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"
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# 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 +1,11 @@
|
||||
# Inference config for multi-run RL integration test
|
||||
[vllm]
|
||||
model = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
max_model_len = 2048
|
||||
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"
|
||||
|
||||
|
||||
@@ -16,9 +16,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[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
|
||||
|
||||
@@ -39,9 +39,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -52,12 +58,20 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.4
|
||||
|
||||
@@ -45,9 +45,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -58,12 +64,20 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.4
|
||||
|
||||
@@ -25,9 +25,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -24,9 +24,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -20,14 +20,25 @@ group_size = 16
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort-v1"
|
||||
min_turns = 3
|
||||
max_turns = 5
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 4
|
||||
[inference.vllm]
|
||||
data_parallel_size = 4
|
||||
|
||||
@@ -20,32 +20,43 @@ seq_len = 8192
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "math-env-v1"
|
||||
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
dataset_subset = "default"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2024"
|
||||
env.taskset = { id = "aime24-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
group_size = 32
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "aime24-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
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"
|
||||
|
||||
@@ -20,9 +20,15 @@ group_size = 16
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -25,17 +25,21 @@ enforce = true
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
env.taskset = { id = "wiki-search-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wiki-search-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 4
|
||||
|
||||
[inference.model]
|
||||
[inference.vllm]
|
||||
tool_call_parser = "hermes"
|
||||
data_parallel_size = 4
|
||||
|
||||
@@ -20,17 +20,22 @@ group_size = 16
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
env.taskset = { id = "wordle-v1" }
|
||||
env.player.harness = { id = "null" }
|
||||
env.player.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wordle-v1"
|
||||
|
||||
[orchestrator.train.source.env.player.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
|
||||
[inference.vllm]
|
||||
data_parallel_size = 6
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
@@ -22,9 +22,16 @@ max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "color-codeword"
|
||||
env.taskset = { id = "color-codeword-v1", images_per_turn = 1 }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "color-codeword-v1"
|
||||
images_per_turn = 1
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer]
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -26,9 +26,20 @@ alpha = 0.1
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort-v1"
|
||||
min_turns = 3
|
||||
max_turns = 5
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
@@ -47,4 +58,6 @@ name = "prime-qwen3"
|
||||
lr = 1e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
@@ -23,9 +23,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -36,9 +42,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
@@ -46,4 +58,6 @@ lr = 3e-6
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
@@ -23,9 +23,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -36,9 +42,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
@@ -46,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
|
||||
|
||||
@@ -33,15 +33,27 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-grpo"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-opd"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.source.algo]
|
||||
type = "opd"
|
||||
@@ -59,12 +71,20 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
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
|
||||
|
||||
@@ -35,9 +35,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -48,9 +54,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
@@ -58,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
|
||||
|
||||
@@ -35,9 +35,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -48,9 +54,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
@@ -64,4 +76,6 @@ save_adapter_separately = true
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
+32
-10
@@ -23,11 +23,21 @@ max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "kuhn-poker"
|
||||
env.taskset = { id = "kuhn-poker-v1" }
|
||||
env.player0.harness = { id = "null" }
|
||||
env.player0.runtime = { type = "subprocess" }
|
||||
env.player1.harness = { id = "null" }
|
||||
env.player1.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "kuhn-poker-v1"
|
||||
|
||||
[orchestrator.train.source.env.player0.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player0.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.source.env.player1.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player1.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -38,11 +48,21 @@ max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "kuhn-poker"
|
||||
env.taskset = { id = "kuhn-poker-v1" }
|
||||
env.player0.harness = { id = "null" }
|
||||
env.player0.runtime = { type = "subprocess" }
|
||||
env.player1.harness = { id = "null" }
|
||||
env.player1.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "kuhn-poker-v1"
|
||||
|
||||
[orchestrator.eval.source.env.player0.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.player0.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval.source.env.player1.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.player1.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
@@ -50,4 +70,6 @@ lr = 3e-6
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
@@ -31,9 +31,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -44,12 +50,20 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
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
|
||||
|
||||
@@ -40,9 +40,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -53,9 +59,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
@@ -63,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
|
||||
|
||||
@@ -40,9 +40,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -53,9 +59,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
@@ -69,4 +81,6 @@ save_adapter_separately = true
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Minimal multi-env debug run: two reverse-text train sources + one eval source.
|
||||
# The launcher spawns one env server per source at its derived address
|
||||
# (tcp://127.0.0.1:5000-5002); the orchestrator connects to each.
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-a"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-b"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
num_examples = 64
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
Vendored
+1
-1
Submodule deps/renderers updated: 5fdf78c30e...2a7e77eb14
Vendored
+1
-1
Submodule deps/research-environments updated: 6a2dee6fcd...b10db7640b
Vendored
+1
-1
Submodule deps/verifiers updated: fcb48822ea...0a4d872f02
+59
-21
@@ -100,7 +100,9 @@ Echo also takes an optional user-supplied token filter that narrows the role sel
|
||||
```toml
|
||||
[orchestrator.algo.filter]
|
||||
import_path = "my_module.drop_warnings"
|
||||
kwargs = { patterns = ["WARNING"] }
|
||||
|
||||
[orchestrator.algo.filter.kwargs]
|
||||
patterns = ["WARNING"]
|
||||
```
|
||||
|
||||
```python
|
||||
@@ -121,18 +123,32 @@ Both components resolve per environment. Each env inherits `[orchestrator.algo]`
|
||||
type = "grpo"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "math"
|
||||
env.taskset = { id = "math-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
# inherits the top-level grpo
|
||||
name = "math" # inherits the top-level grpo
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "math-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "terminal"
|
||||
env.taskset = { id = "terminal-v1" }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
algo = { type = "echo" } # this env runs its own algorithm
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "terminal-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
# this env runs its own algorithm
|
||||
[orchestrator.train.source.algo]
|
||||
type = "echo"
|
||||
```
|
||||
|
||||
### The Algorithm Classes
|
||||
@@ -253,7 +269,9 @@ Wire it up:
|
||||
[trainer.loss]
|
||||
type = "custom"
|
||||
import_path = "my_module.ppo_clip_loss"
|
||||
kwargs = { clip_eps = 0.2 }
|
||||
|
||||
[trainer.loss.kwargs]
|
||||
clip_eps = 0.2
|
||||
```
|
||||
|
||||
The dataclasses:
|
||||
@@ -346,12 +364,22 @@ episode_agents = ["solver"]
|
||||
[[orchestrator.train.source]]
|
||||
name = "proposer-solver"
|
||||
group_size = 4 # proposed problems per source task
|
||||
env.taskset = { id = "proposer-solver-v1" }
|
||||
env.n = 4 # solver attempts per proposed problem
|
||||
env.proposer.harness = { id = "null" }
|
||||
env.proposer.runtime = { type = "subprocess" }
|
||||
env.solver.harness = { id = "null" }
|
||||
env.solver.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "proposer-solver-v1"
|
||||
|
||||
[orchestrator.train.source.env.proposer.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.proposer.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.source.env.solver.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.solver.runtime]
|
||||
type = "subprocess"
|
||||
```
|
||||
|
||||
`group_size` controls how many problems are proposed from each source task. `env.n` controls how many solvers attempt each proposed problem. If a comparison contains only one trace—for example, a solver when `env.n = 1`—its advantage is zero and the zero-advantage filter removes it.
|
||||
@@ -371,11 +399,21 @@ decay = 0.95
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "kuhn-poker"
|
||||
env.taskset = { id = "kuhn-poker-v1" }
|
||||
env.player0.harness = { id = "null" }
|
||||
env.player0.runtime = { type = "subprocess" }
|
||||
env.player1.harness = { id = "null" }
|
||||
env.player1.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "kuhn-poker-v1"
|
||||
|
||||
[orchestrator.train.source.env.player0.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player0.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.source.env.player1.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player1.runtime]
|
||||
type = "subprocess"
|
||||
```
|
||||
|
||||
Both of `kuhn-poker-v1`'s agents late-bind to the run's own model — shared-policy self-play against a continuously improving opponent. Pin one agent to a frozen endpoint (`env.player1.model = ...`) for asymmetric play; its traces are marked untrainable by the env and never reach the advantage computation. A single-agent env under `rae` degrades to REINFORCE with an EMA baseline.
|
||||
|
||||
+37
-14
@@ -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`).
|
||||
@@ -97,7 +97,7 @@ Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one i
|
||||
|
||||
### Dicts
|
||||
|
||||
CLI takes a JSON literal. TOML uses a table or inline-table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
|
||||
CLI takes a JSON literal. TOML uses a table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
|
||||
|
||||
```bash
|
||||
uv run rl @ rl.toml --orchestrator.train.source.0.args \
|
||||
@@ -106,7 +106,10 @@ uv run rl @ rl.toml --orchestrator.train.source.0.args \
|
||||
|
||||
```toml
|
||||
[[orchestrator.train.source]]
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
|
||||
[orchestrator.train.source.args]
|
||||
dataset_name = "openai/gsm8k"
|
||||
dataset_subset = "main"
|
||||
```
|
||||
|
||||
### Optional Sub-Configs
|
||||
@@ -123,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
|
||||
|
||||
@@ -149,23 +152,43 @@ Training and evaluation sources are arrays of tables. Set one source per environ
|
||||
```toml
|
||||
[[orchestrator.train.source]]
|
||||
name = "gsm8k"
|
||||
env.taskset = { id = "gsm8k-v1", split = "train" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
ratio = 3 # 75% of batches
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "gsm8k-v1"
|
||||
split = "train"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
ratio = 1 # default — 25% of batches
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "gsm8k-eval"
|
||||
env.taskset = { id = "gsm8k-v1", split = "test" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "gsm8k-v1"
|
||||
split = "test"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
```
|
||||
|
||||
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
|
||||
|
||||
+2
-2
@@ -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:
|
||||
|
||||
+41
-34
@@ -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
|
||||
|
||||
@@ -174,11 +168,17 @@ Every deployment fronts its vLLM engines with a single global router — it list
|
||||
```toml
|
||||
[inference.router] # or [router] for the standalone inference entrypoint
|
||||
type = "llm-d" # "vllm-router" (default) or "llm-d"
|
||||
# llm-d-only knobs (all optional):
|
||||
scorers = { "prefix-cache-scorer" = 3.0, "active-request-scorer" = 2.0 } # base, applied to every profile
|
||||
prefill_scorer_overrides = { "queue-scorer" = 2.0, "kv-cache-utilization-scorer" = 2.0 } # merged onto the P/D prefill profile
|
||||
decode_scorer_overrides = {} # merged onto the P/D decode profile
|
||||
non_cached_tokens = 16 # below this many non-cached prompt tokens, skip remote prefill (P/D)
|
||||
non_cached_tokens = 16 # llm-d only: below this many non-cached prompt tokens, skip remote prefill (P/D)
|
||||
|
||||
# llm-d only: base scorer weights, applied to every profile
|
||||
[inference.router.scorers]
|
||||
"prefix-cache-scorer" = 3.0
|
||||
"active-request-scorer" = 2.0
|
||||
|
||||
# llm-d only: merged onto the P/D prefill profile (decode_scorer_overrides for decode)
|
||||
[inference.router.prefill_scorer_overrides]
|
||||
"queue-scorer" = 2.0
|
||||
"kv-cache-utilization-scorer" = 2.0
|
||||
```
|
||||
|
||||
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`. The only backend supported for single-node (local) deployments.
|
||||
@@ -255,34 +255,41 @@ For configuring various knobs with environment variables, we enable you to confi
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
|
||||
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip"}
|
||||
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip"}
|
||||
[inference.deployment.prefill_env_vars]
|
||||
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
|
||||
"VLLM_DEEP_GEMM_WARMUP" = "skip"
|
||||
|
||||
[inference.deployment.decode_env_vars]
|
||||
"VLLM_DEEP_GEMM_WARMUP" = "skip"
|
||||
```
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env-server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
|
||||
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
|
||||
|
||||
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
|
||||
|
||||
+1
-1
@@ -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.
|
||||
|
||||
+6
-7
@@ -36,7 +36,8 @@ This page covers everything you need to launch, observe, checkpoint, and recover
|
||||
| `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. |
|
||||
| `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. |
|
||||
| `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. |
|
||||
|
||||
## RL Trainer
|
||||
|
||||
@@ -102,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.
|
||||
@@ -217,7 +218,7 @@ Checkpointing is split across processes because the orchestrator and trainer can
|
||||
| Process | What's saved | Where |
|
||||
|---|---|---|
|
||||
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<output_dir>/checkpoints/step_N/trainer/` |
|
||||
| Orchestrator | Step counter, total tokens / samples / problems | `<output_dir>/checkpoints/step_N/orchestrator/` |
|
||||
| Orchestrator | Progress, per-env data state | `<output_dir>/checkpoints/step_N/orchestrator/` |
|
||||
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
|
||||
| Trainer (HF weights) | HF-compatible weight snapshot for serving | `<output_dir>/weights/step_N/` |
|
||||
|
||||
@@ -271,12 +272,10 @@ The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The f
|
||||
├── inference/
|
||||
│ ├── node_*.log # per-node inference stdout (multi-node only)
|
||||
│ └── router.log # the single global router (multi-node only)
|
||||
└── envs/{train,eval}/<env_name>/
|
||||
├── env_server.log
|
||||
└── env_worker_<id>.log
|
||||
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
|
||||
```
|
||||
|
||||
Env worker logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
|
||||
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
|
||||
|
||||
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
|
||||
|
||||
|
||||
@@ -95,8 +95,18 @@ num_turns_weight = 0.0
|
||||
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
|
||||
[[orchestrator.train.source]]
|
||||
name = "openseeker"
|
||||
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072] }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
skills = ["search"]
|
||||
forward_env = ["SERPER_API_KEY"]
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-search"]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "openseeker-v1"
|
||||
@@ -118,8 +128,18 @@ choices = ["A", "B"]
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "redsearcher"
|
||||
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072] }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
skills = ["search"]
|
||||
forward_env = ["SERPER_API_KEY"]
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-search"]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
|
||||
@@ -147,13 +167,27 @@ interval = 20
|
||||
[[orchestrator.eval.source]]
|
||||
name = "browsecomp"
|
||||
num_examples = 500 # full set is 1266; cap eval at 500
|
||||
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304 }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
|
||||
env.agent.timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
skills = ["search"]
|
||||
forward_env = ["SERPER_API_KEY"]
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-search"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "browsecomp-v1"
|
||||
task = { judge = { model = "Qwen/Qwen3-235B-A22B-Instruct-2507" } }
|
||||
|
||||
[orchestrator.eval.source.env.taskset.task.judge]
|
||||
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.eval.source.env.taskset.task.judges]]
|
||||
@@ -166,15 +200,13 @@ task = { judge = { 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
|
||||
|
||||
@@ -99,9 +99,19 @@ thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
env.taskset = { id = "scaleswe-v1" }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "scaleswe-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-swe"]
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
@@ -112,23 +122,33 @@ interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
env.taskset = { id = "swebench-verified-v1" }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] }
|
||||
env.agent.timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-swe"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
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
|
||||
|
||||
@@ -93,8 +93,16 @@ num_turns_weight = 0.1
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "tmax"
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-terminal"]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "tmax-v1"
|
||||
@@ -121,9 +129,19 @@ interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
|
||||
env.agent.timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-terminal"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified-v1"
|
||||
@@ -145,9 +163,19 @@ id = "swebench-verified-v1"
|
||||
[[orchestrator.eval.source]]
|
||||
name = "terminal-bench-2"
|
||||
group_size = 4 # avg@4
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
|
||||
env.agent.timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["glm45air-terminal"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "terminal-bench-2-v1"
|
||||
@@ -169,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"
|
||||
@@ -35,16 +22,43 @@ prefill_nodes_per_replica = 2
|
||||
num_prefill_replicas = 4
|
||||
decode_nodes_per_replica = 8
|
||||
num_decode_replicas = 1
|
||||
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
|
||||
[deployment.prefill_env_vars]
|
||||
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
|
||||
"VLLM_DEEP_GEMM_WARMUP" = "skip"
|
||||
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
|
||||
|
||||
[deployment.decode_env_vars]
|
||||
"VLLM_DEEP_GEMM_WARMUP" = "skip"
|
||||
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
|
||||
|
||||
[router]
|
||||
type = "llm-d"
|
||||
scorers = { "prefix-cache-scorer" = 3.0 }
|
||||
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 }
|
||||
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 }
|
||||
non_cached_tokens = 128
|
||||
|
||||
[router.scorers]
|
||||
"prefix-cache-scorer" = 3.0
|
||||
|
||||
[router.prefill_scorer_overrides]
|
||||
"queue-scorer" = 4.0
|
||||
"active-request-scorer" = 5.0
|
||||
|
||||
[router.decode_scorer_overrides]
|
||||
"active-request-scorer" = 5.0
|
||||
"kv-cache-utilization-scorer" = 4.0
|
||||
"queue-scorer" = 3.0
|
||||
|
||||
[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
|
||||
|
||||
@@ -28,23 +28,53 @@ prefill_nodes_per_replica = 2
|
||||
num_prefill_replicas = 4
|
||||
decode_nodes_per_replica = 8
|
||||
num_decode_replicas = 1
|
||||
|
||||
# skip warmup for faster start in cost of some jit overhead early
|
||||
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
|
||||
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
[inference.deployment.prefill_env_vars]
|
||||
"VLLM_ENABLE_MOE_DP_CHUNK" = "0"
|
||||
"VLLM_DEEP_GEMM_WARMUP" = "skip"
|
||||
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
|
||||
|
||||
[inference.deployment.decode_env_vars]
|
||||
"VLLM_DEEP_GEMM_WARMUP" = "skip"
|
||||
"UCX_RCACHE_MAX_UNRELEASED" = "1024"
|
||||
|
||||
# gives the most KV cache while keeping decent throughput, KV cache increase comes in from lower deep-ep LL static buffers
|
||||
prefill_vllm_overrides = {"enable_dbo"=true}
|
||||
decode_vllm_overrides = {"max_num_batched_tokens"=96, "max_num_seqs"=96}
|
||||
[inference.deployment.prefill_vllm_overrides]
|
||||
"enable_dbo" = true
|
||||
|
||||
[inference.deployment.decode_vllm_overrides]
|
||||
"max_num_batched_tokens" = 96
|
||||
"max_num_seqs" = 96
|
||||
|
||||
[inference.router]
|
||||
type = "llm-d"
|
||||
scorers = { "prefix-cache-scorer" = 3.0 } # need some prefix-cache routing, however due to shared mooncake pool do low prio
|
||||
|
||||
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 } # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
|
||||
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 } # decode doesn't really create queue, it fills in KV cache fast, give 4.0
|
||||
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
|
||||
|
||||
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
|
||||
"prefix-cache-scorer" = 3.0
|
||||
|
||||
[inference.router.prefill_scorer_overrides] # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
|
||||
"queue-scorer" = 4.0
|
||||
"active-request-scorer" = 5.0
|
||||
|
||||
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
|
||||
"active-request-scorer" = 5.0
|
||||
"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
|
||||
@@ -93,35 +123,28 @@ clear_thinking = false
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 1.0
|
||||
extra_body = {chat_template_kwargs = {clear_thinking = false}}
|
||||
|
||||
[orchestrator.train.sampling.extra_body.chat_template_kwargs]
|
||||
clear_thinking = false
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "r2e"
|
||||
env.taskset = { id = "r2e-gym-v1" }
|
||||
env.agent.harness = { id = "rlm" }
|
||||
env.agent.runtime = { type = "prime", labels = ["glm5-llmd"] }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "r2e-gym-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
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
|
||||
@@ -73,21 +77,22 @@ interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
env.taskset = { id = "swebench-verified-v1" }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["glm5-pd-disag", "swe-bench-verified"]
|
||||
|
||||
[[orchestrator.post_batch_filters]]
|
||||
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"
|
||||
|
||||
@@ -50,37 +50,74 @@ oversampling_factor = 2
|
||||
[[orchestrator.train.source]]
|
||||
name = "swe"
|
||||
ratio = 0.3
|
||||
env.taskset = { id = "r2e-gym-v1" }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "swe"] }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "r2e-gym-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["intellect-3.1", "swe"]
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "deepdive"
|
||||
ratio = 0.2
|
||||
env.taskset = { id = "deepdive-v1" }
|
||||
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"] }
|
||||
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "deepdive-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
skills = ["search"]
|
||||
forward_env = ["SERPER_API_KEY"]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["intellect-3.1", "deepdive"]
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "math"
|
||||
ratio = 0.3
|
||||
env.taskset = { id = "i3_math_v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_math_v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "logic"
|
||||
ratio = 0.2
|
||||
env.taskset = { id = "i3_logic_v1", filter = { max = 0.874 } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_logic_v1"
|
||||
|
||||
[orchestrator.train.source.env.taskset.filter]
|
||||
max = 0.874
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "code"
|
||||
ratio = 0.2
|
||||
env.taskset = { id = "i3_code_v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_code_v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[[orchestrator.pre_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
@@ -91,19 +128,30 @@ interval = 25
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
env.taskset = { id = "swebench-verified-v1" }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["intellect-3.1", "swe-bench-verified"]
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2025"
|
||||
env.taskset = { id = "aime25-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "aime25-v1"
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -48,25 +48,36 @@ batch_size = 2048
|
||||
oversampling_factor = 2
|
||||
max_off_policy_steps = 16
|
||||
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "swe"
|
||||
env.taskset = { id = "r2e-gym-v1" }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "prime", labels = ["minimax-swe", "swe"] }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "r2e-gym-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["minimax-swe", "swe"]
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
env.taskset = { id = "swebench-verified-v1" }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified-v1"
|
||||
|
||||
# PrimeIntellect/MiniMax-M2.5-bf16 — template-identical to MiniMaxAI/MiniMax-M2.5 (mapped).
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["minimax-swe", "swe-bench-verified"]
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
[orchestrator.renderer]
|
||||
name = "minimax-m2"
|
||||
|
||||
@@ -83,9 +83,19 @@ truncate_history_thinking = false
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
env.taskset = { id = "scaleswe-v1" }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "scaleswe-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["nemotron-3-super-swe"]
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
@@ -94,19 +104,29 @@ interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
env.taskset = { id = "swebench-verified-v1" }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] }
|
||||
env.agent.timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
vm = true
|
||||
idle_timeout = "None"
|
||||
labels = ["nemotron-3-super-swe"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
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
|
||||
|
||||
@@ -50,18 +50,30 @@ max_completion_tokens = 32768
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "math"
|
||||
env.taskset = { id = "i3_math_v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_math_v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2025"
|
||||
env.taskset = { id = "aime25-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "aime25-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -48,18 +48,32 @@ max_off_policy_steps = 16
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "swe"
|
||||
env.taskset = { id = "r2e-gym-v1" }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "r2e-gym-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["qwen30b-swe", "swe"]
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
env.taskset = { id = "swebench-verified-v1" }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "prime"
|
||||
labels = ["qwen30b-swe", "swe-bench-verified"]
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -36,16 +36,24 @@ group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
env.taskset = { id = "general-agent-v1", task = { tools = { colocated = true } }, min_tier = 1 }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "modal" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "general-agent-v1"
|
||||
min_tier = 1
|
||||
|
||||
[orchestrator.train.source.env.taskset.task.tools]
|
||||
colocated = true
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
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
|
||||
|
||||
@@ -33,8 +33,19 @@ max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort-v1"
|
||||
min_turns = 3
|
||||
max_turns = 5
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[inference] # Default inference config
|
||||
|
||||
@@ -18,27 +18,39 @@ seq_len = 8192
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "math-env-v1"
|
||||
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
dataset_subset = "default"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2024"
|
||||
env.taskset = { id = "aime24-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
group_size = 32
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "aime24-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
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 \
|
||||
|
||||
@@ -17,9 +17,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -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,17 +40,23 @@ name = "qwen3-4b-wiki-search"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wiki-search-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[[orchestrator.pre_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
enforce = true
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
env.taskset = { id = "wiki-search-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[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
|
||||
|
||||
@@ -20,18 +20,22 @@ group_size = 16
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
env.taskset = { id = "wordle-v1" }
|
||||
env.player.harness = { id = "null" }
|
||||
env.player.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wordle-v1"
|
||||
|
||||
[orchestrator.train.source.env.player.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
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"
|
||||
|
||||
@@ -15,9 +15,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
@@ -7,10 +7,10 @@ requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"pydantic>=1.10.13",
|
||||
"prime-pydantic-config>=0.4.2",
|
||||
"renderers>=0.1.8",
|
||||
"renderers>=0.1.9",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.2.2.dev43",
|
||||
"verifiers>=0.3.0",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
|
||||
@@ -1,14 +1,66 @@
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import SerializeAsAny, model_validator
|
||||
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class EnvServerConfig(BaseConfig):
|
||||
env: EnvConfig
|
||||
"""``uv run env-server``: what to serve (``[env]``, or ``[legacy]`` for a classic v0
|
||||
env) and how it's hosted (``[serve]``). The ``rl`` launcher writes one of these per
|
||||
train/eval source, with ``serve.address`` set to the source's derived address."""
|
||||
|
||||
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
|
||||
"""The 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: vf.ServeConfig = vf.ServeConfig()
|
||||
"""How it's served: the worker pool, the bind address, each worker's episode bound."""
|
||||
|
||||
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
|
||||
"""A classic (v0) environment to serve through the bridge instead of ``env``."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _resolve_env(cls, data):
|
||||
"""Narrow ``env`` to the selected env's config class."""
|
||||
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
|
||||
|
||||
@property
|
||||
def is_legacy(self) -> bool:
|
||||
"""Whether this serves the v0 bridge: a legacy id and no v1 taskset."""
|
||||
return self.legacy.id is not None and not self.env.taskset.id
|
||||
|
||||
@property
|
||||
def env_id(self) -> str:
|
||||
"""The served env's identifier: the v1 env's, else the v0 env id."""
|
||||
return self.env.env_id or self.legacy.id or ""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env(self):
|
||||
# A v0 id next to any v1 env identity leaves one of the two going nowhere, and
|
||||
# which one depends on `is_legacy`: a taskset makes it False, so the v0 env never
|
||||
# loads; a bare `env.id` leaves it True, so the v0 env runs under the v1 name.
|
||||
if self.legacy.id is not None and self.env.env_id:
|
||||
if self.env.taskset.id:
|
||||
raise ValueError(
|
||||
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with "
|
||||
f"the v1 taskset {self.env.taskset.id!r}. Pairing a reusable env with a taskset "
|
||||
f"is env.id = {self.legacy.id!r}; to run the v0 env instead, drop the taskset."
|
||||
)
|
||||
raise ValueError(
|
||||
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with the "
|
||||
f"v1 env.id {self.env.id!r}: the v0 env is what would run, stamped with the v1 "
|
||||
"env's name. Keep whichever one you meant to run."
|
||||
)
|
||||
if not self.env_id:
|
||||
raise ValueError(
|
||||
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or legacy = { id = "<id>" } (v0)'
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -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,6 +4,7 @@ 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,
|
||||
@@ -122,15 +123,19 @@ class EvalSamplingConfig(BaseConfig):
|
||||
return args
|
||||
|
||||
|
||||
class ServingConfig(vf.ServingConfig):
|
||||
"""Verifiers' serving block with ``address`` back to optional. Verifiers defaults it
|
||||
to the address its own ``serve`` CLI binds; here the question is whether to spawn a
|
||||
server or connect to one already running, and that answer has to survive the
|
||||
resolved config being written to a file and read back — so it must be a *value*
|
||||
(``None``), not field-set metadata, which a round-trip drops."""
|
||||
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``)."""
|
||||
|
||||
address: str | None = None
|
||||
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to that server instead of spawning one; when None, it spawns a subprocess env server on a free port. ``pool`` sizes the spawned server."""
|
||||
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):
|
||||
@@ -141,8 +146,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: ServingConfig = ServingConfig()
|
||||
"""How the env server is run: ``serve.pool`` sizes the spawned server, ``serve.address`` points at an external one instead, and ``serve.max_concurrent`` bounds one worker's episodes in flight (unset = unbounded; the dispatcher's ``max_inflight_episodes`` is the run's bound)."""
|
||||
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."""
|
||||
|
||||
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
|
||||
"""A classic (v0) environment to run through the bridge instead of ``env``."""
|
||||
@@ -296,6 +301,11 @@ class EvalConfig(BaseConfig):
|
||||
"""If True, skip the startup eval that otherwise runs before any
|
||||
train rollouts."""
|
||||
|
||||
retrigger_on_resume: bool = False
|
||||
"""If True, re-trigger evals at the checkpoint step on resume (e.g. after a
|
||||
crash that left in-flight evals unfinished). By default, assumes a clean
|
||||
exit where all evals already completed."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
|
||||
@@ -467,11 +477,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."""
|
||||
|
||||
pool_size: int | None = Field(None, ge=1)
|
||||
"""Number of renderer slots shared across concurrent rollouts. Bump
|
||||
for long multi-turn prompts where client-side jinja tokenization
|
||||
serializes."""
|
||||
|
||||
optim: OptimizerConfig = OptimizerConfig()
|
||||
"""Per-run optimizer configuration for multi-run training."""
|
||||
|
||||
@@ -529,6 +534,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
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)."""
|
||||
|
||||
batch_size: int | None = Field(None, ge=1)
|
||||
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
|
||||
|
||||
@@ -619,22 +627,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
"""True when at least one train env samples rollouts from the live policy."""
|
||||
return any(env.algo is not None and env.algo.sampling.source == "policy" for env in self.train.source)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_pool_size(self):
|
||||
"""``pool_size`` sizes the renderer-client pool for policy-sourced
|
||||
sampling. Reject it when that path never runs — no train env samples
|
||||
from the policy — so callers don't silently pass it and wonder why
|
||||
it's ignored."""
|
||||
if self.pool_size is None:
|
||||
return self
|
||||
if not self.any_policy_sourced:
|
||||
raise ValueError(
|
||||
f"orchestrator.pool_size={self.pool_size!r} is set but no train env samples "
|
||||
"from the policy — the renderer-client sampling pool never runs (the renderer "
|
||||
"is still used for client-side tokenization). Remove pool_size."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_auto_resolves(self):
|
||||
"""Reject the silent DefaultRenderer fallback at config time.
|
||||
@@ -741,3 +733,24 @@ class OrchestratorConfig(BaseConfig):
|
||||
# bridge applies legacy.extra_env_kwargs via env.set_kwargs).
|
||||
env.legacy.extra_env_kwargs["max_seq_len"] = self.seq_len
|
||||
return self
|
||||
|
||||
@property
|
||||
def env_sources(self) -> list[tuple[str, EnvConfig]]:
|
||||
"""Every ``(split, source)`` this run pulls from, train first then eval — the
|
||||
order that fixes each source's deterministic env-server port."""
|
||||
sources: list[tuple[str, EnvConfig]] = [("train", source) for source in self.train.source]
|
||||
if self.eval is not None:
|
||||
sources += [("eval", source) for source in self.eval.source]
|
||||
return sources
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str]:
|
||||
"""Where each source's env server lives, keyed by ``(split, resolved_name)``:
|
||||
``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}"
|
||||
for index, (split, source) in enumerate(self.env_sources)
|
||||
}
|
||||
|
||||
@@ -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."
|
||||
)
|
||||
@@ -608,17 +612,17 @@ 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
|
||||
@@ -635,35 +639,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 +678,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 +728,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
|
||||
)
|
||||
|
||||
@@ -2,12 +2,17 @@ import re
|
||||
|
||||
# (regex, parser_name) — first match wins.
|
||||
TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
# Trinity-Large-Thinking uses the Qwen3-Coder tool format; the rest of the family is Hermes.
|
||||
(re.compile(r"^arcee-ai/Trinity-Large-Thinking"), "qwen3_coder"),
|
||||
(re.compile(r"^arcee-ai/Trinity-"), "hermes"),
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V3\.2"), "deepseek_v32"),
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V3\.1"), "deepseek_v31"),
|
||||
(re.compile(r"^zai-org/GLM-4\.5"), "glm45"),
|
||||
(re.compile(r"^zai-org/GLM-4\.7"), "glm47"),
|
||||
(re.compile(r"^zai-org/GLM-5"), "glm47"),
|
||||
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2"),
|
||||
(re.compile(r"^openai/gpt-oss"), "openai"),
|
||||
(re.compile(r"^poolside/Laguna"), "poolside_v1"),
|
||||
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "qwen3_coder"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3"), "qwen3_coder"),
|
||||
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
|
||||
@@ -18,9 +23,13 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
]
|
||||
|
||||
REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
# Trinity-Large-Preview doesn't reason; the Thinking/Mini/Nano variants do.
|
||||
(re.compile(r"^arcee-ai/Trinity-(Large-Thinking|Mini|Nano)"), "deepseek_r1"),
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V3\.[12]"), "deepseek_r1"),
|
||||
(re.compile(r"^zai-org/GLM-"), "glm45"),
|
||||
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
|
||||
# openai/gpt-oss has no entry here — vLLM's harmony serving path splits reasoning natively.
|
||||
(re.compile(r"^poolside/Laguna"), "poolside_v1"),
|
||||
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Super"), "nemotron_v3"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Nano"), "nano_v3"),
|
||||
|
||||
@@ -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).
|
||||
@@ -155,7 +154,7 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
conflicts.append(("output_dir", sub))
|
||||
fill(sub, expected_value)
|
||||
|
||||
# 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 +164,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 +224,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
|
||||
@@ -310,9 +309,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."
|
||||
)
|
||||
|
||||
+32
-11
@@ -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"
|
||||
@@ -18,7 +18,7 @@ dependencies = [
|
||||
"torchaudio",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers==5.6.2",
|
||||
"vllm>=0.24.0",
|
||||
"vllm>=0.26.0",
|
||||
"mooncake-transfer-engine>=0.3.10.post2",
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
@@ -33,7 +33,7 @@ dependencies = [
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"torchtitan",
|
||||
"verifiers[harbor]>=0.2.2.dev43",
|
||||
"verifiers[harbor]>=0.3.0",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
@@ -53,14 +53,19 @@ sft = "prime_rl.entrypoints.sft:main"
|
||||
inference = "prime_rl.entrypoints.inference:main"
|
||||
trainer = "prime_rl.entrypoints.trainer:main"
|
||||
orchestrator = "prime_rl.entrypoints.orchestrator:main"
|
||||
env-server = "prime_rl.orchestrator.env_server.env_server:main"
|
||||
env-server = "prime_rl.entrypoints.env_server:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
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.
|
||||
@@ -200,8 +214,8 @@ vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
@@ -235,7 +249,14 @@ explicit = true
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["F", "I"]
|
||||
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
|
||||
|
||||
# jaxtyping writes shapes as string annotations (`Int[Tensor, "batch seq"]`), which ruff reads as
|
||||
# forward references and reports as syntax errors / undefined names.
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"src/prime_rl/trainer/model.py" = ["F722", "F821"]
|
||||
"src/prime_rl/trainer/rl/data.py" = ["F722", "F821"]
|
||||
"src/prime_rl/trainer/rl/loss.py" = ["F722", "F821"]
|
||||
"src/prime_rl/trainer/sft/data.py" = ["F722", "F821"]
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
# `prime_rl` is split across two editable wheels (prime-rl + prime-rl-configs).
|
||||
|
||||
@@ -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!"
|
||||
}
|
||||
|
||||
|
||||
+26
-9
@@ -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
|
||||
|
||||
@@ -34,29 +34,46 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
|
||||
|
||||
## Special syntax
|
||||
|
||||
**No inline tables** — checked-in configs use `[section]` headers, never `key = { ... }`. Expand `env.taskset = { id = "..." }` to a full-path header (`[orchestrator.train.source.env.taskset]` — subtable headers after a `[[...]]` entry attach to that entry).
|
||||
|
||||
**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:
|
||||
|
||||
```toml
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text-eval"
|
||||
env.taskset = { id = "reverse-text-v1", split = "test" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
split = "test"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
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.
|
||||
|
||||
|
||||
@@ -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`.
|
||||
|
||||
|
||||
@@ -89,17 +89,25 @@ grep -E "WARNING|ERROR" {output_dir}/logs/envs/{train,eval}/*.log
|
||||
|
||||
All metrics print to the console log (and W&B when configured).
|
||||
|
||||
**Progress** — orchestrator log. Rollout metrics are keyed `{scope}/{subset}/<metric>/<stat>`: `scope` is `train/agg` (all train envs) or `train/<env>` (`eval/<env>` for eval); `subset` is `all` (every rollout) or `effective` (post-filter).
|
||||
**Progress** — orchestrator log. Rollout metrics mirror the episode/trace hierarchy, at two levels:
|
||||
|
||||
- `{scope}/{subset}/<metric>/<stat>` — episode-level facts only: the token/turn/branch counts, summed over an episode's traces.
|
||||
- `{scope}/{subset}/<agent>/<metric>/<stat>` — every trace-level metric (reward, truncation, errors, timing, env metrics, filter verdicts, eval scores), keyed by agent name so seats never mix. Flat over that agent's traces: one sample is one trace, so an in-episode fan-out like n solvers contributes n samples.
|
||||
|
||||
`scope` is `train/agg` (all train envs) or `train/<env>` (`eval/<env>` for eval); `subset` is `all` (every rollout) or `effective` (post-filter). Single-agent envs have one agent — usually `agent` — and one trace per episode, so both levels agree; multi-agent envs name each seat (`proposer`, `solver`, `judge`, …).
|
||||
|
||||
| Metric | Description |
|
||||
|--------|-------------|
|
||||
| `train/agg/effective/reward/mean` | mean training reward (per env: `train/<env>/effective/reward/mean`) |
|
||||
| `train/agg/effective/num_total_tokens/mean` | avg tokens per rollout (also `num_input_tokens`, `num_output_tokens`) |
|
||||
| `train/agg/effective/num_turns/mean` | avg turns per rollout (multi-turn only) |
|
||||
| `train/agg/effective/is_truncated/mean` | fraction truncated |
|
||||
| `train/agg/all/has_error/mean` | fraction errored (per-type under `train/agg/all/error/<type>`; also `dispatcher/errored/{train,eval}`) |
|
||||
| `train/<env>/effective/metrics/<name>/mean` | env-specific metrics (e.g. pass rate) |
|
||||
| `eval/<env>/effective/{avg@k,pass@k}` | eval scores when configured |
|
||||
| `train/agg/effective/<agent>/reward/mean` | mean training reward for that agent (per env: `train/<env>/effective/<agent>/reward/mean`) |
|
||||
| `train/agg/effective/num_total_tokens/mean` | avg tokens per episode, summed over its agents (also `num_input_tokens`, `num_output_tokens`) |
|
||||
| `train/agg/effective/num_turns/mean` | avg turns per episode, summed over its agents |
|
||||
| `train/<env>/effective/<agent>/num_turns/mean` | avg turns for that agent alone (also token counts, `num_branches`) |
|
||||
| `train/agg/effective/<agent>/is_truncated/mean` | fraction of that agent's rollouts truncated |
|
||||
| `train/agg/all/<agent>/has_error/mean` | fraction of that agent's rollouts errored (per-type under `train/agg/all/<agent>/error/<type>`; also `dispatcher/errored/{train,eval}`) |
|
||||
| `train/agg/all/<agent>/is_trainable/mean` | fraction carrying a training signal — 0.0 for a frozen seat like a judge (also `is_filtered`, `filters/<name>`) |
|
||||
| `train/<env>/effective/<agent>/metrics/<name>/mean` | env-specific metrics for that agent (e.g. pass rate) |
|
||||
| `train/<env>/effective/<agent>/timing/agent/model/mean` | model vs harness share of that agent's phase |
|
||||
| `eval/<env>/effective/<agent>/{avg@k,pass@k}` | eval scores for that agent, when configured |
|
||||
|
||||
**Stability** — trainer log:
|
||||
|
||||
@@ -172,9 +180,9 @@ All processes use `setproctitle` so they're visible in `ps`/`htop`/`pstree`:
|
||||
```
|
||||
PRIME-RL::Launcher
|
||||
├── PRIME-RL::Inference (vLLM server, GPU 0)
|
||||
├── PRIME-RL::Orchestrator (CPU-only)
|
||||
│ └── Verifiers::EnvServer (ZMQ env server per environment)
|
||||
│ └── Verifiers::EnvWorker0..N
|
||||
├── PRIME-RL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
|
||||
│ └── Verifiers::EnvWorker0..N
|
||||
├── PRIME-RL::Orchestrator (CPU-only; connects to each env server)
|
||||
├── torchrun
|
||||
│ └── PRIME-RL::Trainer (GPU 1+)
|
||||
└── tail trainer.log
|
||||
|
||||
@@ -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:
|
||||
|
||||
+8
-10
@@ -12,28 +12,26 @@ from prime_rl.utils.utils import clean_exit
|
||||
|
||||
@clean_exit
|
||||
def run_server(config: EnvServerConfig):
|
||||
env = config.env
|
||||
address = env.serve.address or "tcp://127.0.0.1:5000"
|
||||
# The env's ``serve.pool`` (static or elastic) sizes the server; a v0/legacy env runs through
|
||||
# ``serve.pool`` (static or elastic) sizes the server; a v0/legacy env runs through
|
||||
# the bridge, a v1 env is a native env block — both speak the same serve protocol,
|
||||
# so the orchestrator is agnostic. serve_env applies the logging setup in this process
|
||||
# and in every spawned worker.
|
||||
server_kwargs = (
|
||||
{"env_id": env.env_id, "env_args": env.legacy.args, "extra_env_kwargs": env.legacy.extra_env_kwargs}
|
||||
if env.is_legacy
|
||||
else {"config_data": env_config_data(env.env), "max_concurrent": env.serve.max_concurrent}
|
||||
{"env_id": config.env_id, "env_args": config.legacy.args, "extra_env_kwargs": config.legacy.extra_env_kwargs}
|
||||
if config.is_legacy
|
||||
else {"config_data": env_config_data(config.env), "max_concurrent": config.serve.max_concurrent}
|
||||
)
|
||||
serve_env(
|
||||
**pool_serve_kwargs(env.serve.pool),
|
||||
legacy=env.is_legacy,
|
||||
address=address,
|
||||
**pool_serve_kwargs(config.serve.pool),
|
||||
legacy=config.is_legacy,
|
||||
address=config.serve.address,
|
||||
log_setup=partial(setup_env_server_logging, config.log.level, config.log.json_logging),
|
||||
**server_kwargs,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry-point for env-server. Run using `uv run env-server`"""
|
||||
"""Main entry-point for the env server. Run using `uv run env-server`"""
|
||||
set_proc_title("EnvServer")
|
||||
run_server(cli(EnvServerConfig))
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -8,12 +8,14 @@ import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import pynvml
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
from prime_rl.configs.inference import VllmRouterConfig
|
||||
from prime_rl.configs.orchestrator import EnvConfig
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.entrypoints.inference import vllm_overrides_fragment
|
||||
from prime_rl.utils.config import cli, to_toml_dict
|
||||
@@ -43,6 +45,17 @@ TRAINER_TOML = "trainer.toml"
|
||||
ORCHESTRATOR_TOML = "orchestrator.toml"
|
||||
INFERENCE_TOML = "inference.toml"
|
||||
|
||||
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."""
|
||||
addresses = config.orchestrator.env_addresses
|
||||
return [
|
||||
(split, source, addresses[(split, source.resolved_name)]) for split, source in config.orchestrator.env_sources
|
||||
]
|
||||
|
||||
|
||||
def get_physical_gpu_ids() -> list[int]:
|
||||
"""Return physical GPU IDs visible to the launcher."""
|
||||
@@ -80,6 +93,22 @@ 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.
|
||||
for split, source, address in env_servers(config):
|
||||
env_dir = output_dir / ENVS_DIR / split
|
||||
env_dir.mkdir(parents=True, exist_ok=True)
|
||||
source_dict = to_toml_dict(source)
|
||||
env_server_dict = {
|
||||
"env": source_dict["env"],
|
||||
"serve": {**source_dict.get("serve", {}), "address": address},
|
||||
"legacy": source_dict.get("legacy", {}),
|
||||
"log": {"level": config.orchestrator.log.vf_level, "json_logging": config.orchestrator.log.json_logging},
|
||||
}
|
||||
with open(env_dir / f"{source.resolved_name}.toml", "wb") as f:
|
||||
tomli_w.dump(env_server_dict, f)
|
||||
|
||||
|
||||
def rl_local(config: RLConfig):
|
||||
assert config.deployment.type == "single_node"
|
||||
@@ -131,8 +160,6 @@ 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:
|
||||
from urllib.parse import urlparse
|
||||
|
||||
base_url = config.orchestrator.model.client.base_url[0]
|
||||
parsed = urlparse(base_url)
|
||||
client_port = parsed.port
|
||||
@@ -219,6 +246,41 @@ def rl_local(config: RLConfig):
|
||||
"otherwise rollouts will hang."
|
||||
)
|
||||
|
||||
# Start one env server per source. The orchestrator connects to each source's
|
||||
# deterministic address, polling until the server is up, so the servers and the
|
||||
# orchestrator start in parallel.
|
||||
for split, source, address in env_servers(config):
|
||||
name = source.resolved_name
|
||||
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.toml").as_posix()]
|
||||
logger.info(f"Starting {split} env server {name} at {address}")
|
||||
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
|
||||
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
|
||||
env_server_log.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(env_server_log, "w") as log_file:
|
||||
env_server_process = Popen(
|
||||
env_server_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.orchestrator.env_vars,
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(env_server_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events[f"env/{split}/{name}"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(env_server_process, stop_event, error_queue, f"{split} env server {name}"),
|
||||
daemon=True,
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_TOML).as_posix()]
|
||||
logger.info("Starting orchestrator process")
|
||||
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
|
||||
@@ -391,6 +453,11 @@ 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"]
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
@@ -422,8 +489,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,
|
||||
@@ -432,12 +499,14 @@ 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",
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
)
|
||||
else:
|
||||
script = template.render(
|
||||
@@ -455,10 +524,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",
|
||||
@@ -467,6 +542,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
orchestrator_env_vars=orchestrator_env_vars,
|
||||
inference_env_vars=inference_env_vars,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import torch
|
||||
|
||||
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
|
||||
|
||||
|
||||
def apply_shared_vllm_patches():
|
||||
"""vLLM general plugin: prime-rl patches that must run in every vLLM process.
|
||||
@@ -16,7 +14,6 @@ def apply_shared_vllm_patches():
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_qwen3_coder_param_newline_trim()
|
||||
monkey_patch_minimax_m2_think_end_passthrough()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
monkey_patch_online_fp8_parameter_cast()
|
||||
|
||||
@@ -10,14 +10,10 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
# Force the V1 GPU model runner. vLLM 0.24.0 routes Llama/Mistral/Qwen3 plus MoE archs
|
||||
# (DeepseekV2, Qwen2Moe, GraniteMoe; the 0.23 MoE/quantized guard was removed) to the
|
||||
# V2 runner, which has no `_preprocess` hook for our padded-input scrub (see
|
||||
# inference/vllm/padded_input_scrub.py) and doesn't zero the padded decode tail
|
||||
# itself; that stale tail poisons CUDA-graph replay as NaN logits (reproduced on
|
||||
# Nemotron-Nano SWE, PR #2506; upstream fix vllm#42779 is still unmerged). V1 keeps
|
||||
# the scrub effective for every model and is also required for routed-experts capture
|
||||
# (the NIXL PD path rejects V2). setdefault so it stays overridable.
|
||||
# Force the V1 GPU model runner. vLLM routes Llama/Mistral/Qwen3 plus MoE archs
|
||||
# (DeepseekV2, Qwen2Moe, GraniteMoe) to the V2 runner by default, but V2 doesn't
|
||||
# support routed-experts capture (the NIXL PD path rejects it). setdefault so it
|
||||
# stays overridable.
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
|
||||
|
||||
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
|
||||
@@ -30,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,88 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_INSTALL_LOCK = threading.Lock()
|
||||
_INSTALLED = False
|
||||
|
||||
|
||||
def monkey_patch_vllm_padded_input_scrub() -> None:
|
||||
"""Zero vLLM's padded model inputs before graph replay.
|
||||
|
||||
vLLM pads decode batches up to CUDA graph capture sizes. Some kernels read
|
||||
model-input tensors past the scheduled-token prefix, so stale values in the
|
||||
padded tail can affect replayed decode graphs. Keep this shim until the
|
||||
vLLM-side fix is available in the pinned runtime.
|
||||
|
||||
Remove this patch once https://github.com/vllm-project/vllm/pull/42779 is
|
||||
included in the vLLM release we pin/use.
|
||||
"""
|
||||
global _INSTALLED
|
||||
with _INSTALL_LOCK:
|
||||
if _INSTALLED:
|
||||
return
|
||||
|
||||
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
|
||||
|
||||
if getattr(GPUModelRunner, "_prime_rl_padded_input_scrub", False):
|
||||
_INSTALLED = True
|
||||
return
|
||||
|
||||
original_preprocess = GPUModelRunner._preprocess
|
||||
|
||||
def _patched_preprocess(
|
||||
self: Any,
|
||||
scheduler_output: Any,
|
||||
num_input_tokens: int,
|
||||
intermediate_tensors: Any | None = None,
|
||||
) -> tuple[Any, ...]:
|
||||
result = original_preprocess(
|
||||
self,
|
||||
scheduler_output,
|
||||
num_input_tokens,
|
||||
intermediate_tensors,
|
||||
)
|
||||
|
||||
num_scheduled_tokens = int(scheduler_output.total_num_scheduled_tokens)
|
||||
_zero_padded_model_inputs(
|
||||
result,
|
||||
num_scheduled_tokens,
|
||||
int(num_input_tokens),
|
||||
)
|
||||
return result
|
||||
|
||||
GPUModelRunner._preprocess = _patched_preprocess
|
||||
GPUModelRunner._prime_rl_padded_input_scrub = True
|
||||
_INSTALLED = True
|
||||
|
||||
logger.warning("Enabled vLLM padded model-input scrub.")
|
||||
|
||||
|
||||
def _zero_padded_model_inputs(
|
||||
preprocess_result: Sequence[Any],
|
||||
num_scheduled_tokens: int,
|
||||
num_input_tokens: int,
|
||||
) -> None:
|
||||
"""Zero the model-input tail beyond scheduled tokens in-place."""
|
||||
if num_input_tokens <= num_scheduled_tokens:
|
||||
return
|
||||
|
||||
input_ids = preprocess_result[0]
|
||||
inputs_embeds = preprocess_result[1]
|
||||
positions = preprocess_result[2]
|
||||
pad_slice = slice(num_scheduled_tokens, num_input_tokens)
|
||||
|
||||
if input_ids is not None:
|
||||
input_ids[pad_slice].zero_()
|
||||
if inputs_embeds is not None:
|
||||
inputs_embeds[pad_slice].zero_()
|
||||
if positions is not None:
|
||||
if positions.ndim == 1:
|
||||
positions[pad_slice].zero_()
|
||||
else:
|
||||
positions[..., pad_slice].zero_()
|
||||
@@ -1,6 +1,5 @@
|
||||
import asyncio
|
||||
from argparse import Namespace
|
||||
from typing import Any
|
||||
|
||||
import uvloop
|
||||
from fastapi import APIRouter, Request
|
||||
@@ -25,7 +24,6 @@ from prime_rl.inference.patches import (
|
||||
monkey_patch_nano_v3_reasoning_parser,
|
||||
monkey_patch_strip_routed_experts_from_chat,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
monkey_patch_vllm_padded_input_scrub,
|
||||
)
|
||||
|
||||
# NOTE: Fix harmony stop token propagation for GPT-OSS models
|
||||
@@ -37,9 +35,6 @@ monkey_patch_tokenize_params_validation()
|
||||
# NOTE: Register Nano V3 reasoning parser so configs can use
|
||||
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
# NOTE: Optional mitigation for vLLM padded decode inputs until the native fix
|
||||
# is available in our pinned runtime.
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
# NOTE: routed_experts are consumed only via the serialized /generate path (router
|
||||
# replay). The chat-completions path encodes them as a base64 np.save string the PD
|
||||
# router cannot merge, which fails eval rollouts (they use chat completions). Strip
|
||||
@@ -215,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)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Prime-RL extensions to vLLM's `/inference/v1/generate` handler.
|
||||
|
||||
vLLM 0.22 ships a generic tokens-in / tokens-out handler at
|
||||
``vllm.entrypoints.serve.disagg.serving.ServingTokens`` that already covers
|
||||
vLLM ships a generic tokens-in / tokens-out handler at
|
||||
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
|
||||
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
|
||||
priority, ``data_parallel_rank`` header routing and server-side ``max_tokens``
|
||||
defaulting. We subclass it for the bits still missing from the upstream handler:
|
||||
@@ -37,12 +37,12 @@ from vllm.entrypoints.openai.engine.protocol import (
|
||||
RequestResponseMetadata,
|
||||
UsageInfo,
|
||||
)
|
||||
from vllm.entrypoints.serve.disagg.protocol import (
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
|
||||
GenerateRequest,
|
||||
GenerateResponse,
|
||||
GenerateResponseChoice,
|
||||
)
|
||||
from vllm.entrypoints.serve.disagg.serving import ServingTokens
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
|
||||
from vllm.entrypoints.serve.utils.api_utils import get_max_tokens
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
@@ -176,7 +176,7 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
request: GenerateRequest,
|
||||
raw_request: Request | None = None,
|
||||
) -> PrimeRlGenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
|
||||
# Mirrors upstream ``ServingTokens.serve_tokens`` (vllm 0.22). Diffs:
|
||||
# Mirrors upstream ``ServingTokens.serve_tokens``. Diffs:
|
||||
# (a) inject ``data_parallel_rank`` from the inbound header into
|
||||
# ``engine_client.generate``; (b) default ``sampling_params.max_tokens``
|
||||
# to ``max_model_len - prompt_len`` when the caller didn't set it; and
|
||||
@@ -200,10 +200,11 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
# Build the engine input — features-aware (MM) or text-only fallback.
|
||||
# Identical to upstream so we keep tracking it.
|
||||
if features := request.features:
|
||||
from vllm.entrypoints.serve.disagg.mm_serde import decode_mm_kwargs_item
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import decode_mm_kwargs_item
|
||||
from vllm.inputs import mm_input
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
PlaceholderRange,
|
||||
)
|
||||
|
||||
@@ -220,13 +221,13 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
mm_kwargs[modality] = [None] * len(hashes)
|
||||
engine_input = mm_input(
|
||||
prompt_token_ids=request.token_ids,
|
||||
mm_kwargs=mm_kwargs, # type: ignore[arg-type]
|
||||
mm_kwargs=MultiModalKwargsItems(mm_kwargs),
|
||||
mm_hashes=features.mm_hashes,
|
||||
mm_placeholders=mm_placeholders,
|
||||
cache_salt=request.cache_salt,
|
||||
)
|
||||
else:
|
||||
(engine_input,) = await self.openai_serving_render.preprocess_completion(
|
||||
(engine_input,) = await self.online_renderer.preprocess_completion(
|
||||
request,
|
||||
prompt_input=request.token_ids,
|
||||
prompt_embeds=None,
|
||||
|
||||
@@ -29,10 +29,10 @@ class HierarchicalGRPOAlgorithm(Algorithm):
|
||||
self.episode_agents = set(config.episode_agents)
|
||||
|
||||
async def score_group(self, group: list[Rollout]) -> None:
|
||||
peers: dict[tuple[str | None, str | None], list[Rollout]] = defaultdict(list)
|
||||
peers: dict[tuple[str, str | None], list[Rollout]] = defaultdict(list)
|
||||
for rollout in group:
|
||||
episode_scoped = rollout.agent_name in self.episode_agents
|
||||
key = (rollout.agent_name, rollout.episode_id if episode_scoped else None)
|
||||
episode_scoped = rollout.agent.name in self.episode_agents
|
||||
key = (rollout.agent.name, rollout.episode_id if episode_scoped else None)
|
||||
peers[key].append(rollout)
|
||||
for members in peers.values():
|
||||
baseline = sum(rollout.reward for rollout in members) / len(members)
|
||||
|
||||
@@ -32,10 +32,10 @@ class RAEAlgorithm(Algorithm):
|
||||
def __init__(self, config: RAEAlgoConfig, policy_pool: InferencePool):
|
||||
super().__init__(config, policy_pool)
|
||||
self.decay = config.decay
|
||||
self.baselines: dict[str | None, float] = defaultdict(float)
|
||||
self.baselines: dict[str, float] = defaultdict(float)
|
||||
|
||||
async def score_group(self, group: list[Rollout]) -> None:
|
||||
for rollout in group:
|
||||
baseline = self.baselines[rollout.agent_name]
|
||||
baseline = self.baselines[rollout.agent.name]
|
||||
rollout.assign_advantages(rollout.reward - baseline)
|
||||
self.baselines[rollout.agent_name] = self.decay * baseline + (1.0 - self.decay) * rollout.reward
|
||||
self.baselines[rollout.agent.name] = self.decay * baseline + (1.0 - self.decay) * rollout.reward
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Checkpoint manager for ``Progress``. Layout:
|
||||
"""Checkpoint manager for the orchestrator state (``Progress`` counters +
|
||||
``TrainSource`` data position). Layout:
|
||||
``<output_dir>/checkpoints/step_N/orchestrator/progress.pt``."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,6 +14,7 @@ from pathlib import Path
|
||||
import torch
|
||||
|
||||
from prime_rl.configs.orchestrator import CheckpointConfig
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
from prime_rl.orchestrator.types import Progress
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_ckpt_dir, get_step_path
|
||||
@@ -26,7 +28,7 @@ class CheckpointManager:
|
||||
def get_ckpt_path(self, step: int) -> Path:
|
||||
return get_step_path(self.ckpt_dir, step) / "orchestrator"
|
||||
|
||||
def save(self, progress: Progress, step: int) -> None:
|
||||
def save(self, progress: Progress, train_source: TrainSource, step: int) -> None:
|
||||
ckpt_path = self.get_ckpt_path(step)
|
||||
ckpt_path.mkdir(parents=True, exist_ok=True)
|
||||
start = time.perf_counter()
|
||||
@@ -35,7 +37,7 @@ class CheckpointManager:
|
||||
fd, tmp_name = tempfile.mkstemp(dir=ckpt_path, prefix="progress.pt.", suffix=".tmp")
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as f:
|
||||
torch.save({"progress": progress}, f)
|
||||
torch.save({"progress": progress, "train_source": train_source.state_dict()}, f)
|
||||
os.replace(tmp_name, ckpt_path / "progress.pt")
|
||||
except BaseException:
|
||||
with contextlib.suppress(OSError):
|
||||
@@ -45,7 +47,7 @@ class CheckpointManager:
|
||||
f"Orchestrator checkpoint saved to {ckpt_path} in {format_time(time.perf_counter() - start)}"
|
||||
)
|
||||
|
||||
def load(self, progress: Progress, step: int) -> None:
|
||||
def load(self, progress: Progress, train_source: TrainSource, step: int) -> None:
|
||||
ckpt_path = self.get_ckpt_path(step)
|
||||
state_file = ckpt_path / "progress.pt"
|
||||
if not state_file.exists():
|
||||
@@ -53,7 +55,7 @@ class CheckpointManager:
|
||||
get_logger().debug(f"Loading checkpoint from {state_file}")
|
||||
start = time.perf_counter()
|
||||
if self.config.skip_progress:
|
||||
get_logger().info("Skipping progress loading from checkpoint")
|
||||
get_logger().info("Skipping progress and data position loading from checkpoint")
|
||||
else:
|
||||
with open(state_file, "rb") as f:
|
||||
state = torch.load(f, weights_only=False)
|
||||
@@ -61,6 +63,16 @@ class CheckpointManager:
|
||||
for key, value in asdict(saved).items():
|
||||
if hasattr(progress, key):
|
||||
setattr(progress, key, value)
|
||||
train_source.load_state_dict(state["train_source"])
|
||||
for name, position in state["train_source"]["envs"].items():
|
||||
if name not in train_source.base_rows:
|
||||
continue
|
||||
rows = train_source.base_rows[name]
|
||||
num_tasks = len(rows) if rows is not None else "infinite"
|
||||
get_logger().info(
|
||||
f"Resumed data position for env {name} - epoch={position['epoch']}, "
|
||||
f"cursor={position['cursor']}/{num_tasks}"
|
||||
)
|
||||
get_logger().debug(f"Orchestrator checkpoint loaded in {format_time(time.perf_counter() - start)}")
|
||||
|
||||
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
N rollouts in one call reserves N permits (each bridged v0 rollout is its own
|
||||
single-agent episode).
|
||||
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
|
||||
- Emit-everything invariant: every dispatched env-rollout eventually reaches
|
||||
``out_q`` exactly once, as one episode (a ``list[Rollout]``). Failures
|
||||
- Emit-everything invariant: every dispatched episode eventually reaches
|
||||
``out_q`` exactly once, as a ``list[Rollout]``. Failures
|
||||
(env error, empty trajectory, task exception, off-policy cancel) carry
|
||||
``trace.error`` set; sinks decide drop / partial-train policy.
|
||||
``trace.last_error`` set; sinks decide drop / partial-train policy.
|
||||
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
|
||||
schedule next. Transitions are level-triggered (driven by the eval
|
||||
source's emptiness), so in-flight rollouts of the opposite kind drain
|
||||
@@ -495,7 +495,7 @@ class RolloutDispatcher:
|
||||
self.inflight_permits -= n
|
||||
|
||||
async def handle_completed_rollout(self, task: asyncio.Task) -> None:
|
||||
"""Emit every dispatched env-rollout exactly once to ``out_q``: a ``run``
|
||||
"""Emit every dispatched episode exactly once to ``out_q``: a ``run``
|
||||
result as one episode, a legacy ``run_group`` result as ``rollout_count``
|
||||
single-trace episodes. Task exceptions synthesize ``rollout_count``
|
||||
error-marker episodes so the sink's count-to-``group_size`` finalization
|
||||
@@ -521,11 +521,14 @@ class RolloutDispatcher:
|
||||
get_logger().warning(f"Rollout task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
|
||||
task_idx = group.task_idx if group is not None else -1
|
||||
rollouts = [
|
||||
Rollout(task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)))
|
||||
Rollout(
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
|
||||
agent=vf.AgentInfo(config=vf.AgentConfig()),
|
||||
)
|
||||
for _ in range(meta.rollout_count)
|
||||
]
|
||||
for r in rollouts:
|
||||
r.capture_error(exc)
|
||||
r.record_error(exc)
|
||||
is_synth_exception = True
|
||||
|
||||
for r in rollouts:
|
||||
@@ -537,9 +540,9 @@ class RolloutDispatcher:
|
||||
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
|
||||
if r.has_error:
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
if not is_synth_exception and r.error is not None:
|
||||
if not is_synth_exception and r.last_error is not None:
|
||||
get_logger().warning(
|
||||
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — {r.error.type}: {r.error.message}"
|
||||
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — {r.last_error.type}: {r.last_error.message}"
|
||||
)
|
||||
if meta.rollout_count == 1:
|
||||
# A ``run`` task: the whole result is one episode.
|
||||
@@ -601,6 +604,7 @@ class RolloutDispatcher:
|
||||
for _ in range(meta.rollout_count):
|
||||
trace = Rollout(
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
|
||||
agent=vf.AgentInfo(config=vf.AgentConfig()),
|
||||
ok=False,
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
stop_condition="error",
|
||||
@@ -628,6 +632,7 @@ class RolloutDispatcher:
|
||||
for _ in range(unscheduled_cancelled):
|
||||
trace = Rollout(
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
|
||||
agent=vf.AgentInfo(config=vf.AgentConfig()),
|
||||
ok=False,
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
stop_condition="error",
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
"""Env wrappers over a v1 env server.
|
||||
|
||||
Each ``Env`` owns a v1 ``EnvServer`` (spawned as a child process, or an
|
||||
external one pinned by ``config.serve.address``) and an ``EnvClient`` to drive it. The
|
||||
Each ``Env`` is an ``EnvClient`` onto its source's env server. Each server's address
|
||||
is derived from the source's position in the config
|
||||
(``OrchestratorConfig.env_addresses``); the launcher runs the servers at
|
||||
exactly those addresses, and the orchestrator connects. The
|
||||
orchestrator never *runs* an environment — the agents and their runtimes live only
|
||||
in the server — but it does own the *taskset*: a v1 env's tasks are loaded here,
|
||||
once, and each dispatched env-rollout ships its task's data on the request
|
||||
once, and each dispatched episode ships its task's data on the request
|
||||
(``task_data``); the server pydantic-validates it into the taskset's declared
|
||||
``TaskData`` type and runs it. That keeps the server (and every worker in its
|
||||
pool) stateless about data — no per-worker dataset loads, no idx-addressed task
|
||||
@@ -12,7 +14,7 @@ cache — and gives the orchestrator real tasks to cycle, shuffle, and filter. O
|
||||
the legacy (v0) bridge, whose dataset genuinely lives server-side, is still driven
|
||||
by ``task_idx`` (its count comes from ``info``).
|
||||
|
||||
The server answers one ``Episode`` per env-rollout, whose traces we validate into
|
||||
The server answers one ``Episode`` per run request, whose traces we validate into
|
||||
``Trace[WireTaskData]`` — real ``vf.Trace``\\ s (never loose dicts) whose task
|
||||
keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
|
||||
"""
|
||||
@@ -20,19 +22,12 @@ keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import atexit
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import queue
|
||||
import sys
|
||||
from collections.abc import Iterator, Sequence
|
||||
from itertools import islice
|
||||
from multiprocessing.process import BaseProcess
|
||||
from pathlib import Path
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from verifiers.v1.serve import EnvClient, env_config_data
|
||||
from verifiers.v1.serve import EnvClient
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
|
||||
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
|
||||
@@ -45,48 +40,19 @@ from prime_rl.utils.logger import get_logger
|
||||
# task.idx + task.model_dump).
|
||||
ROLLOUT_TYPE = Rollout[vf.WireTaskData]
|
||||
|
||||
# Max wait for a spawned env server to bind and report its address. A legacy
|
||||
# child loads its dataset before reporting, so this is generous.
|
||||
ENV_SERVER_SPAWN_TIMEOUT = 600.0
|
||||
|
||||
|
||||
def _run_env_server(
|
||||
*,
|
||||
log_file: str,
|
||||
log_level: str,
|
||||
json_logging: bool,
|
||||
legacy: bool = False,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
"""Spawned-process entry point: redirect this process's output to ``log_file`` (the
|
||||
server's logging + any subprocess-runtime output), then serve via ``serve_env``. The
|
||||
worker-pool sizing arrives in ``kwargs`` (``max_workers`` / ``multiplex`` / ``elastic``
|
||||
from the env's ``pool``). ``serve_env`` applies ``log_setup`` here and in every spawned
|
||||
worker; a worker inherits this process's redirected stdout/stderr, so its per-rollout
|
||||
logs reach ``log_file`` too. Top-level so it stays picklable for the ``spawn`` start
|
||||
method. ``legacy`` picks the v0 bridge."""
|
||||
from functools import partial
|
||||
|
||||
from verifiers.v1.serve import serve_env
|
||||
|
||||
from prime_rl.orchestrator.utils import setup_env_server_logging
|
||||
|
||||
fh = open(log_file, "w", buffering=1)
|
||||
os.dup2(fh.fileno(), sys.stdout.fileno())
|
||||
os.dup2(fh.fileno(), sys.stderr.fileno())
|
||||
serve_env(
|
||||
legacy=legacy,
|
||||
log_setup=partial(setup_env_server_logging, log_level, json_logging),
|
||||
**kwargs,
|
||||
)
|
||||
# Max wait for the env server to answer health. Generous because the launcher spawns
|
||||
# servers concurrently with the orchestrator, and a legacy server loads its dataset
|
||||
# before serving.
|
||||
ENV_SERVER_STARTUP_TIMEOUT = 600.0
|
||||
|
||||
|
||||
class Env:
|
||||
"""Wraps a v1 env server + client. The orchestrator owns the taskset (loaded once,
|
||||
"""Client onto a v1 env server. The orchestrator owns the taskset (loaded once,
|
||||
client-side); the server owns agent/harness execution."""
|
||||
|
||||
def __init__(self, config: EnvConfig):
|
||||
def __init__(self, config: EnvConfig, address: str):
|
||||
self.config = config
|
||||
self.address = address
|
||||
self.sampling_args: dict = {}
|
||||
self.num_tasks: int | None = 0
|
||||
"""Task count; ``None`` means the taskset is infinite."""
|
||||
@@ -97,7 +63,6 @@ class Env:
|
||||
count) and iterated from there; an infinite one streams off its generator.
|
||||
Consumed once — by ``TrainSource`` (train) or ``EvalEnv.start`` (eval)."""
|
||||
self._env_client: EnvClient | None = None
|
||||
self._env_server_process: BaseProcess | None = None
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
@@ -109,17 +74,14 @@ class Env:
|
||||
raise RuntimeError(f"Env {self.name} not started — call start() first.")
|
||||
return self._env_client
|
||||
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
"""Spawn the env server (if needed), connect, and load the taskset client-side
|
||||
(legacy instead asks the server for ``info`` — its dataset is server-side)."""
|
||||
external = self.config.serve.address is not None
|
||||
address = self.config.serve.address or await self._spawn(log_dir, log_level or "INFO", json_logging)
|
||||
get_logger().debug(f"Connecting {self.name} to env server {address}")
|
||||
self._env_client = EnvClient(address=address)
|
||||
# A spawned server already reported its address *after* binding, so it's up. An
|
||||
# external server has no such handshake, so poll until it answers.
|
||||
if external:
|
||||
await self.env_client.wait_for_server_startup()
|
||||
async def start(self) -> None:
|
||||
"""Connect to the env server and load the taskset client-side (legacy instead
|
||||
asks the server for ``info`` — its dataset is server-side)."""
|
||||
get_logger().debug(f"Connecting {self.name} to env server {self.address}")
|
||||
self._env_client = EnvClient(address=self.address)
|
||||
# The server may still be coming up (the launcher spawns it concurrently with
|
||||
# the orchestrator), so poll until it answers.
|
||||
await self.env_client.wait_for_server_startup(timeout=ENV_SERVER_STARTUP_TIMEOUT)
|
||||
if self.config.is_legacy:
|
||||
info = await self.env_client.info()
|
||||
self.num_tasks = info.num_tasks
|
||||
@@ -137,59 +99,6 @@ class Env:
|
||||
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
|
||||
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks} group_scoring={self.requires_group_scoring}")
|
||||
|
||||
async def _spawn(self, log_dir: Path, log_level: str, json_logging: bool) -> str:
|
||||
"""Spawn a v1 EnvServer child process (it runs the agents; the tasks come from
|
||||
us). The server binds an OS-assigned port (``:0``) and reports the concrete
|
||||
address back over a queue — no free-port guess, no TOCTOU race. Its output
|
||||
goes to ``<log_dir>/<name>.log`` (``log_dir`` is already the train/eval-split
|
||||
``.../logs/envs/{train,eval}`` the orchestrator passes in)."""
|
||||
ctx = mp.get_context("spawn")
|
||||
address_queue: mp.Queue = ctx.Queue()
|
||||
log_file = log_dir / f"{self.name}.log"
|
||||
log_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_logger().debug(f"Spawning env server {self.name} (id={self.config.env_id}, log={log_file})")
|
||||
server_kwargs = (
|
||||
dict(
|
||||
legacy=True,
|
||||
env_id=self.config.env_id,
|
||||
env_args=self.config.legacy.args,
|
||||
extra_env_kwargs=self.config.legacy.extra_env_kwargs,
|
||||
)
|
||||
if self.config.is_legacy
|
||||
# Picklable dict — the narrowed config class doesn't survive the spawn.
|
||||
# ``max_concurrent`` bounds this worker's episodes in flight — usually unset,
|
||||
# since the dispatcher's ``max_inflight_episodes`` is the run's bound.
|
||||
else dict(
|
||||
legacy=False,
|
||||
config_data=env_config_data(self.config.env),
|
||||
max_concurrent=self.config.serve.max_concurrent,
|
||||
)
|
||||
)
|
||||
process = ctx.Process(
|
||||
target=_run_env_server,
|
||||
kwargs=dict(
|
||||
log_file=str(log_file),
|
||||
log_level=log_level,
|
||||
json_logging=json_logging,
|
||||
**vf.pool_serve_kwargs(self.config.serve.pool),
|
||||
address="tcp://127.0.0.1:0",
|
||||
address_queue=address_queue,
|
||||
**server_kwargs,
|
||||
),
|
||||
daemon=False,
|
||||
)
|
||||
process.start()
|
||||
self._env_server_process = process
|
||||
try:
|
||||
address = await asyncio.to_thread(address_queue.get, timeout=ENV_SERVER_SPAWN_TIMEOUT)
|
||||
except queue.Empty:
|
||||
raise RuntimeError(f"Env server {self.name} did not report its address within {ENV_SERVER_SPAWN_TIMEOUT}s")
|
||||
finally:
|
||||
address_queue.close()
|
||||
address_queue.join_thread()
|
||||
get_logger().debug(f"Env server {self.name} bound at {address}")
|
||||
return address
|
||||
|
||||
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
|
||||
sampling = {**self.sampling_args}
|
||||
if cache_salt is not None:
|
||||
@@ -217,14 +126,14 @@ class Env:
|
||||
sampling=self._sampling(cache_salt),
|
||||
)
|
||||
if not episode.traces:
|
||||
error = episode.error
|
||||
error = episode.last_error
|
||||
detail = f"{error.type}: {error.message}" if error is not None else "no traces and no error recorded"
|
||||
raise RuntimeError(f"env-rollout failed before any trace was minted — {detail}")
|
||||
raise RuntimeError(f"episode failed before any trace was produced — {detail}")
|
||||
rollouts = [ROLLOUT_TYPE.model_construct(**dict(wire)) for wire in episode.traces]
|
||||
for rollout in rollouts:
|
||||
rollout.episode_id = episode.id
|
||||
if not episode.ok and rollout.ok:
|
||||
error = episode.error or vf.Error(
|
||||
error = episode.last_error or vf.Error(
|
||||
type="EpisodeFailed", message="A sibling trace in this episode failed"
|
||||
)
|
||||
rollout.errors = [*rollout.errors, error]
|
||||
@@ -244,18 +153,12 @@ class Env:
|
||||
)
|
||||
return [ROLLOUT_TYPE.model_construct(**dict(wire)) for wire in wires]
|
||||
|
||||
def shutdown(self) -> None:
|
||||
if self._env_server_process is None:
|
||||
return
|
||||
self._env_server_process.terminate()
|
||||
self._env_server_process = None
|
||||
|
||||
|
||||
class TrainEnv(Env):
|
||||
config: TrainSourceConfig
|
||||
|
||||
def __init__(self, config: TrainSourceConfig, sampler: Sampler, algorithm: Algorithm):
|
||||
super().__init__(config)
|
||||
def __init__(self, config: TrainSourceConfig, address: str, sampler: Sampler, algorithm: Algorithm):
|
||||
super().__init__(config, address)
|
||||
self.sampler = sampler
|
||||
self.algorithm = algorithm
|
||||
self.sampling_args = sampler.sampling_args(config.sampling.to_sampling_args())
|
||||
@@ -264,13 +167,13 @@ class TrainEnv(Env):
|
||||
class EvalEnv(Env):
|
||||
config: EvalSourceConfig
|
||||
|
||||
def __init__(self, config: EvalSourceConfig):
|
||||
super().__init__(config)
|
||||
def __init__(self, config: EvalSourceConfig, address: str):
|
||||
super().__init__(config, address)
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
self.examples: list[dict] = []
|
||||
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
await super().start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
|
||||
async def start(self) -> None:
|
||||
await super().start()
|
||||
n = self.config.num_examples
|
||||
if self.tasks is None: # legacy: the dataset lives on the server — address it by row
|
||||
count = self.num_tasks if n < 0 else min(n, self.num_tasks)
|
||||
@@ -308,30 +211,10 @@ class Envs(Generic[EnvT]):
|
||||
def __len__(self) -> int:
|
||||
return len(self._envs)
|
||||
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
"""Spawn env servers (where needed) and connect, one at a time. Each server
|
||||
binds an OS-assigned port and reports it back, so there's no port race."""
|
||||
for env in self:
|
||||
await env.start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
|
||||
atexit.register(self.shutdown)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Terminate all spawned env server processes."""
|
||||
processes = [env._env_server_process for env in self if env._env_server_process is not None]
|
||||
if not processes:
|
||||
return
|
||||
logger = get_logger()
|
||||
logger.debug(f"Shutting down {len(processes)} env server(s)")
|
||||
for p in processes:
|
||||
p.terminate()
|
||||
for p in processes:
|
||||
p.join(timeout=25)
|
||||
if p.is_alive():
|
||||
logger.warning(f"Env server {p.pid} did not exit after 25s, force killing")
|
||||
p.kill()
|
||||
p.join(timeout=5)
|
||||
for env in self:
|
||||
env._env_server_process = None
|
||||
async def start(self) -> None:
|
||||
"""Connect to all env servers in parallel — every address is known up front,
|
||||
so there's nothing to serialize on."""
|
||||
await asyncio.gather(*(env.start() for env in self))
|
||||
|
||||
|
||||
class TrainEnvs(Envs[TrainEnv]):
|
||||
@@ -339,12 +222,20 @@ class TrainEnvs(Envs[TrainEnv]):
|
||||
:class:`Sampler` and runtime :class:`Algorithm`, built from the env's
|
||||
resolved algorithm config."""
|
||||
|
||||
def __init__(self, configs: Sequence[TrainSourceConfig], *, policy_pool, renderer_config=None):
|
||||
def __init__(
|
||||
self,
|
||||
configs: Sequence[TrainSourceConfig],
|
||||
addresses: dict[tuple[str, str], str],
|
||||
*,
|
||||
policy_pool,
|
||||
renderer_config=None,
|
||||
):
|
||||
self._envs: dict[str, TrainEnv] = {}
|
||||
for config in configs:
|
||||
assert config.algo is not None, "TrainSourceConfig.algo must be resolved before env construction"
|
||||
env = TrainEnv(
|
||||
config,
|
||||
addresses[("train", config.resolved_name)],
|
||||
Sampler(config.algo.sampling, policy_pool, renderer_config),
|
||||
build_algorithm(config.algo, policy_pool),
|
||||
)
|
||||
@@ -354,8 +245,8 @@ class TrainEnvs(Envs[TrainEnv]):
|
||||
class EvalEnvs(Envs[EvalEnv]):
|
||||
"""Collection of evaluation environments."""
|
||||
|
||||
def __init__(self, configs: Sequence[EvalSourceConfig]):
|
||||
def __init__(self, configs: Sequence[EvalSourceConfig], addresses: dict[tuple[str, str], str]):
|
||||
self._envs: dict[str, EvalEnv] = {}
|
||||
for config in configs:
|
||||
env = EvalEnv(config)
|
||||
env = EvalEnv(config, addresses[("eval", config.resolved_name)])
|
||||
self._envs[env.name] = env
|
||||
|
||||
@@ -6,8 +6,17 @@ A rollout container (``TrainRollouts`` / ``EvalRollouts``) owns the rollout list
|
||||
``rollouts.metrics.num_input_tokens.mean()`` works — and assembles the full
|
||||
``{prefix}/{subset}/<metric>/<stat>`` wandb dict via ``.to_wandb(...)``.
|
||||
|
||||
No I/O, no pandas — plain Python over the ``vf.Trace`` properties each rollout exposes. Aggregation
|
||||
is flat over the rollout list except the solve rates, which group by ``group_id``.
|
||||
The wandb layout mirrors the episode/trace hierarchy, one aggregation per level:
|
||||
|
||||
- ``{prefix}/{subset}/<metric>/<stat>`` — episode level, one value per episode summing its traces
|
||||
(matching ``vf.Episode``'s aggregates). Only the count metrics live here.
|
||||
- ``{prefix}/{subset}/<agent>/<metric>/<stat>`` — agent level, one value per trace, grouped by agent
|
||||
name (``vf.Episode.by_agent``) so agents never mix into one distribution. Everything trace-scoped
|
||||
lives here: reward, rates, timing, custom metrics, the pipeline verdicts, the eval scores.
|
||||
|
||||
A single-agent env has one trace per episode, so the count metrics coincide across levels.
|
||||
|
||||
No I/O, no pandas — plain Python over the ``vf.Trace`` properties each rollout exposes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -90,26 +99,26 @@ class TimingMetrics(StatGroup):
|
||||
"""Per-phase rollout durations, nested so ``metrics.timing.setup.mean()`` reads naturally.
|
||||
``total`` is the per-rollout sum across all phases."""
|
||||
|
||||
PHASES = ("setup", "generation", "finalize", "scoring")
|
||||
PHASES = ("setup", "agent", "finalize", "scoring")
|
||||
|
||||
@property
|
||||
def setup(self) -> Stat:
|
||||
return Stat([r.timing.setup.duration for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def generation(self) -> Stat:
|
||||
return Stat([r.timing.generation.duration for r in self.rollouts])
|
||||
def agent(self) -> Stat:
|
||||
return Stat([r.timing.agent.duration for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def generation_model(self) -> Stat:
|
||||
"""The share of the generation phase spent inside model calls (inference)."""
|
||||
return Stat([r.timing.generation.model.duration for r in self.rollouts])
|
||||
def agent_model(self) -> Stat:
|
||||
"""The share of the agent phase spent inside model calls (inference)."""
|
||||
return Stat([r.timing.agent.model.duration for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def generation_harness(self) -> Stat:
|
||||
"""The share of the generation phase spent outside model calls (harness, tools,
|
||||
def agent_harness(self) -> Stat:
|
||||
"""The share of the agent phase spent outside model calls (harness, tools,
|
||||
user simulation)."""
|
||||
return Stat([r.timing.generation.harness.duration for r in self.rollouts])
|
||||
return Stat([r.timing.agent.harness.duration for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def finalize(self) -> Stat:
|
||||
@@ -126,16 +135,19 @@ class TimingMetrics(StatGroup):
|
||||
def stats(self) -> dict[str, Stat]:
|
||||
return {
|
||||
**{phase: getattr(self, phase) for phase in self.PHASES},
|
||||
"generation/model": self.generation_model,
|
||||
"generation/harness": self.generation_harness,
|
||||
"agent/model": self.agent_model,
|
||||
"agent/harness": self.agent_harness,
|
||||
"total": self.total,
|
||||
}
|
||||
|
||||
|
||||
class CustomMetrics(StatGroup):
|
||||
"""Per-key ``Stat``s over a dynamic per-rollout dict attribute (env ``@metric``s or reward
|
||||
components), each averaged over the rollouts that report the key. ``value`` extracts the
|
||||
float from each entry (rewards are ``vf.Reward`` records; metrics are plain floats)."""
|
||||
components), each over the rollouts that carry the key. Scoring seeds every expected key
|
||||
with ``None`` before invoking it, so a ``None`` value means the signal never produced a
|
||||
score and counts as 0.0 — the ``effective`` subset excludes errored rollouts and gives the
|
||||
clean means. ``value`` extracts the float from each scored entry (rewards are ``vf.Reward``
|
||||
records; metrics are plain floats)."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout], attr: str, value: Callable[[Any], float] = float) -> None:
|
||||
super().__init__(rollouts)
|
||||
@@ -146,40 +158,29 @@ class CustomMetrics(StatGroup):
|
||||
names = sorted({name for r in self.rollouts for name in getattr(r, self.attr)})
|
||||
return {
|
||||
name: Stat(
|
||||
[self.value(getattr(r, self.attr)[name]) for r in self.rollouts if name in getattr(r, self.attr)]
|
||||
[
|
||||
self.value(scores[name]) if scores[name] is not None else 0.0
|
||||
for r in self.rollouts
|
||||
if name in (scores := getattr(r, self.attr))
|
||||
]
|
||||
)
|
||||
for name in names
|
||||
}
|
||||
|
||||
|
||||
class RolloutMetrics:
|
||||
"""Metrics shared by train and eval over a rollout list. Distributional metrics are ``Stat``s
|
||||
(mean/max/min); boolean metrics are ``Stat``s of 0/1 (use ``.mean()`` for the rate). ``to_wandb``
|
||||
assembles the full ``{prefix}/{subset}/...`` dict; ``TrainMetrics`` / ``EvalMetrics`` extend it."""
|
||||
class TraceMetrics(StatGroup):
|
||||
"""Trace-level metrics for one agent, every one of them flat over that agent's traces: one
|
||||
sample is one trace, so a fan-out (n same-agent traces in one episode, e.g. n solvers) simply
|
||||
contributes n samples. Weighing whole episodes against each other is the episode level's job;
|
||||
inside a seat the trace is the unit, which is also what the advantage computation samples."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout]) -> None:
|
||||
self.rollouts = rollouts
|
||||
DISTRIBUTIONS = ("reward", "num_total_tokens", "num_input_tokens", "num_output_tokens", "num_turns", "num_branches")
|
||||
RATES = ("is_truncated", "is_completed")
|
||||
|
||||
# Distributional metrics
|
||||
@property
|
||||
def num_total_tokens(self) -> Stat:
|
||||
return Stat([float(r.num_total_tokens) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def num_input_tokens(self) -> Stat:
|
||||
return Stat([float(r.num_input_tokens) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def num_output_tokens(self) -> Stat:
|
||||
return Stat([float(r.num_output_tokens) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def num_turns(self) -> Stat:
|
||||
return Stat([float(r.num_turns) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def num_branches(self) -> Stat:
|
||||
return Stat([float(r.num_branches) for r in self.rollouts])
|
||||
def stats(self) -> dict[str, Stat]:
|
||||
return {
|
||||
name: Stat([float(getattr(r, name)) for r in self.rollouts]) for name in (*self.DISTRIBUTIONS, *self.RATES)
|
||||
}
|
||||
|
||||
@property
|
||||
def timing(self) -> TimingMetrics:
|
||||
@@ -187,7 +188,7 @@ class RolloutMetrics:
|
||||
|
||||
@property
|
||||
def metrics(self) -> CustomMetrics:
|
||||
"""Env custom ``@metric`` outputs, keyed by name (``metrics.metrics["acc"].mean()``)."""
|
||||
"""Env custom ``@metric`` outputs, keyed by name."""
|
||||
return CustomMetrics(self.rollouts, "metrics")
|
||||
|
||||
@property
|
||||
@@ -196,22 +197,13 @@ class RolloutMetrics:
|
||||
summed into the scalar ``reward``)."""
|
||||
return CustomMetrics(self.rollouts, "rewards", value=lambda reward: reward.value)
|
||||
|
||||
# Boolean rate metrics (0/1 distributions — ``.mean()`` is the rate)
|
||||
@property
|
||||
def is_truncated(self) -> Stat:
|
||||
return Stat([float(r.is_truncated) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def is_completed(self) -> Stat:
|
||||
return Stat([float(r.is_completed) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def has_error(self) -> Stat:
|
||||
return Stat([float(r.has_error) for r in self.rollouts])
|
||||
|
||||
def stop_conditions(self) -> dict[str, float]:
|
||||
"""``generation_truncated`` over all rollouts, then each recorded ``stop_condition``'s rate
|
||||
over the rollouts that recorded one."""
|
||||
"""``generation_truncated`` over the agent's traces, then each recorded
|
||||
``stop_condition``'s rate over the traces that recorded one."""
|
||||
out = {
|
||||
"generation_truncated": sum(
|
||||
1 for r in self.rollouts if r.is_truncated and r.stop_condition != "prompt_too_long"
|
||||
@@ -224,15 +216,16 @@ class RolloutMetrics:
|
||||
return out
|
||||
|
||||
def error_types(self) -> dict[str, int]:
|
||||
"""Count of errored rollouts by error type (the rollout's last error — e.g. ``Cancelled``,
|
||||
"""Count of errored traces by error type (the trace's last error — e.g. ``Cancelled``,
|
||||
``ProviderError``)."""
|
||||
types = [r.error.type for r in self.rollouts if r.has_error]
|
||||
types = [r.last_error.type for r in self.rollouts if r.has_error and r.last_error is not None]
|
||||
return {t: types.count(t) for t in sorted(set(types))}
|
||||
|
||||
def solve_rates(self) -> dict[str, float]:
|
||||
"""Per-group solve rates, assuming binary 0/1 rewards (unspecified for other reward ranges):
|
||||
``solved_none`` (the group earned no reward), ``solved_all`` (every rollout scored 1.0), and
|
||||
``solved_some`` (the mixed remainder — the GRPO-signal groups)."""
|
||||
"""Per-group solve rates over the agent's traces, assuming binary 0/1 rewards (unspecified
|
||||
for other reward ranges): ``solved_none`` (the group earned no reward), ``solved_all``
|
||||
(every trace scored 1.0), and ``solved_some`` (the mixed remainder — the GRPO-signal
|
||||
groups)."""
|
||||
groups: dict = {}
|
||||
for r in self.rollouts:
|
||||
groups.setdefault(r.group_id, []).append(r)
|
||||
@@ -245,6 +238,84 @@ class RolloutMetrics:
|
||||
"solved_some": 1 - (solved_none + solved_all) / n_groups,
|
||||
}
|
||||
|
||||
def to_dict(self, prefix: str, *, subset: Subset) -> dict[str, float]:
|
||||
"""Full ``<stat>`` fan-out for the distributions; ``/mean`` only for the 0/1 rates.
|
||||
Errors live only on the ``all`` subset (``effective`` drops them by construction)."""
|
||||
stats = self.stats()
|
||||
out: dict[str, float] = {}
|
||||
for name in self.DISTRIBUTIONS:
|
||||
out |= stats[name].to_dict(f"{prefix}/{name}")
|
||||
for name in self.RATES:
|
||||
out[f"{prefix}/{name}/mean"] = stats[name].mean()
|
||||
out |= self.timing.to_dict(f"{prefix}/timing")
|
||||
out |= self.metrics.to_dict(f"{prefix}/metrics")
|
||||
out |= self.rewards.to_dict(f"{prefix}/rewards")
|
||||
if subset == "all":
|
||||
out[f"{prefix}/has_error/mean"] = self.has_error.mean()
|
||||
out |= {f"{prefix}/error/{t}": float(count) for t, count in self.error_types().items()}
|
||||
out |= {f"{prefix}/stop_condition/{k}": v for k, v in self.stop_conditions().items()}
|
||||
out |= {f"{prefix}/{k}": v for k, v in self.solve_rates().items()}
|
||||
return out
|
||||
|
||||
|
||||
class EpisodeMetrics:
|
||||
"""Metrics shared by train and eval over a rollout list. The count metrics (tokens/turns/
|
||||
branches) are episode-level — one value per episode, summing its traces — and are the only
|
||||
per-metric keys ``to_wandb`` emits at the env level; every trace-level metric is emitted per
|
||||
agent via ``by_agent()``. The boolean ``Stat`` properties (0/1 distributions, ``.mean()`` is
|
||||
the rate) serve the console log lines. ``TrainMetrics`` / ``EvalMetrics`` extend ``to_wandb``
|
||||
with the train pipeline rates and the eval scores."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout]) -> None:
|
||||
self.rollouts = rollouts
|
||||
|
||||
def episodes(self) -> list[list[Rollout]]:
|
||||
"""The subset's rollouts grouped into their episodes. A rollout without an
|
||||
``episode_id`` (legacy envs, synthesized error markers) is its own episode."""
|
||||
grouped: dict[str, list[Rollout]] = {}
|
||||
for r in self.rollouts:
|
||||
grouped.setdefault(r.episode_id or r.id, []).append(r)
|
||||
return list(grouped.values())
|
||||
|
||||
def by_agent(self) -> dict[str, TraceMetrics]:
|
||||
"""Per-agent metric views (``vf.Episode.by_agent`` over the subset's rollouts)."""
|
||||
per_agent: dict[str, list[Rollout]] = {}
|
||||
for r in self.rollouts:
|
||||
per_agent.setdefault(r.agent.name, []).append(r)
|
||||
return {name: TraceMetrics(rollouts) for name, rollouts in sorted(per_agent.items())}
|
||||
|
||||
# Episode-level count metrics: one value per episode, summing its traces — the same
|
||||
# aggregation as ``vf.Episode.num_turns`` / ``num_*_tokens``.
|
||||
@property
|
||||
def num_total_tokens(self) -> Stat:
|
||||
return Stat([float(sum(r.num_total_tokens for r in episode)) for episode in self.episodes()])
|
||||
|
||||
@property
|
||||
def num_input_tokens(self) -> Stat:
|
||||
return Stat([float(sum(r.num_input_tokens for r in episode)) for episode in self.episodes()])
|
||||
|
||||
@property
|
||||
def num_output_tokens(self) -> Stat:
|
||||
return Stat([float(sum(r.num_output_tokens for r in episode)) for episode in self.episodes()])
|
||||
|
||||
@property
|
||||
def num_turns(self) -> Stat:
|
||||
return Stat([float(sum(r.num_turns for r in episode)) for episode in self.episodes()])
|
||||
|
||||
@property
|
||||
def num_branches(self) -> Stat:
|
||||
return Stat([float(sum(r.num_branches for r in episode)) for episode in self.episodes()])
|
||||
|
||||
# Boolean rate metrics for the console log lines (0/1 distributions — ``.mean()`` is the
|
||||
# rate); to_wandb emits their per-agent counterparts instead.
|
||||
@property
|
||||
def is_truncated(self) -> Stat:
|
||||
return Stat([float(r.is_truncated) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def has_error(self) -> Stat:
|
||||
return Stat([float(r.has_error) for r in self.rollouts])
|
||||
|
||||
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
|
||||
"""The common metric dict for one ``{prefix}/{subset}`` slice. Empty input → ``{}``."""
|
||||
if not self.rollouts:
|
||||
@@ -256,59 +327,55 @@ class RolloutMetrics:
|
||||
out |= self.num_output_tokens.to_dict(f"{p}/num_output_tokens")
|
||||
out |= self.num_turns.to_dict(f"{p}/num_turns")
|
||||
out |= self.num_branches.to_dict(f"{p}/num_branches")
|
||||
out |= self.timing.to_dict(f"{p}/timing")
|
||||
out |= self.metrics.to_dict(f"{p}/metrics")
|
||||
out |= self.rewards.to_dict(f"{p}/rewards")
|
||||
out[f"{p}/is_truncated/mean"] = self.is_truncated.mean()
|
||||
out[f"{p}/is_completed/mean"] = self.is_completed.mean()
|
||||
# errors live only on the `all` subset (effective drops them), so emit the rate + the
|
||||
# per-type counts there only
|
||||
if subset == "all":
|
||||
out[f"{p}/has_error/mean"] = self.has_error.mean()
|
||||
out |= {f"{p}/error/{t}": float(count) for t, count in self.error_types().items()}
|
||||
out |= {f"{p}/stop_condition/{k}": v for k, v in self.stop_conditions().items()}
|
||||
out |= {f"{p}/{k}": v for k, v in self.solve_rates().items()}
|
||||
for agent, agent_metrics in self.by_agent().items():
|
||||
out |= agent_metrics.to_dict(f"{p}/{agent}", subset=subset)
|
||||
return out
|
||||
|
||||
|
||||
class TrainMetrics(RolloutMetrics):
|
||||
"""Common metrics plus the reward distribution and filter-pipeline rates."""
|
||||
class TrainMetrics(EpisodeMetrics):
|
||||
"""Common metrics plus the per-agent filter-pipeline rates. ``reward`` (flat over all traces)
|
||||
serves the console log lines; the wandb reward stats are per-agent."""
|
||||
|
||||
@property
|
||||
def reward(self) -> Stat:
|
||||
return Stat([float(r.reward) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def is_trainable(self) -> Stat:
|
||||
return Stat([float(r.is_trainable) for r in self.rollouts])
|
||||
|
||||
@property
|
||||
def is_filtered(self) -> Stat:
|
||||
return Stat([float(r.is_filtered) for r in self.rollouts])
|
||||
|
||||
def filter_rates(self) -> dict[str, float]:
|
||||
"""Per-filter detection rate over all rollouts."""
|
||||
names = sorted({name for r in self.rollouts for name in r.filter_results})
|
||||
return {
|
||||
name: sum(1 for r in self.rollouts if r.filter_results.get(name)) / len(self.rollouts) for name in names
|
||||
}
|
||||
|
||||
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
|
||||
out = super().to_wandb(prefix=prefix, subset=subset)
|
||||
if not self.rollouts:
|
||||
return out
|
||||
p = f"{prefix}/{subset}"
|
||||
out |= self.reward.to_dict(f"{p}/reward")
|
||||
out[f"{p}/is_trainable/mean"] = self.is_trainable.mean()
|
||||
out[f"{p}/is_filtered/mean"] = self.is_filtered.mean()
|
||||
out |= {f"{p}/filters/{k}/mean": v for k, v in self.filter_rates().items()}
|
||||
# The pipeline verdicts are per-trace (an untrainable seat is 0.0 throughout, and filters
|
||||
# only ever run on trainable survivors), so they read per agent like the rest.
|
||||
for agent, traces in self.by_agent().items():
|
||||
p = f"{prefix}/{subset}/{agent}"
|
||||
rollouts = traces.rollouts
|
||||
out[f"{p}/is_trainable/mean"] = sum(float(r.is_trainable) for r in rollouts) / len(rollouts)
|
||||
out[f"{p}/is_filtered/mean"] = sum(float(r.is_filtered) for r in rollouts) / len(rollouts)
|
||||
names = sorted({name for r in rollouts for name in r.filter_results})
|
||||
out |= {
|
||||
f"{p}/filters/{name}/mean": sum(1 for r in rollouts if r.filter_results.get(name)) / len(rollouts)
|
||||
for name in names
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
class EvalMetrics(RolloutMetrics):
|
||||
"""Common metrics plus the ``avg@<group_size>`` score and (on the effective subset, for
|
||||
binary-reward tasks) pass@k / pass^k. ``group_size`` (the ``avg@k`` k) is supplied by the
|
||||
container so the ``all`` and ``effective`` subsets share one stable key."""
|
||||
def pass_at_k(rollouts: list[Rollout]) -> dict[str, float]:
|
||||
"""pass@k / pass^k averaged over examples; ``{}`` for non-binary rewards."""
|
||||
rewards = [r.reward for r in rollouts]
|
||||
if not set(rewards).issubset({0.0, 1.0}):
|
||||
return {}
|
||||
by_example: dict = {}
|
||||
for r in rollouts:
|
||||
by_example.setdefault(r.group_id, []).append(r.reward)
|
||||
per_example = [compute_pass_metrics(rs) for rs in by_example.values()]
|
||||
keys = sorted({k for d in per_example for k in d})
|
||||
return {k: sum(d[k] for d in per_example if k in d) / sum(1 for d in per_example if k in d) for k in keys}
|
||||
|
||||
|
||||
class EvalMetrics(EpisodeMetrics):
|
||||
"""Common metrics plus the per-agent ``avg@<group_size>`` score and (on the effective subset,
|
||||
for binary-reward tasks) pass@k / pass^k. Both score an agent's own traces, so they live in its
|
||||
subtree like every other trace-level metric. ``group_size`` (the ``avg@k`` k, the run's rollouts
|
||||
per example) is supplied by the container so the ``all`` and ``effective`` subsets — and every
|
||||
agent — share one stable key."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout], group_size: int) -> None:
|
||||
super().__init__(rollouts)
|
||||
@@ -318,26 +385,13 @@ class EvalMetrics(RolloutMetrics):
|
||||
def reward(self) -> Stat:
|
||||
return Stat([float(r.reward) for r in self.rollouts])
|
||||
|
||||
def pass_at_k(self) -> dict[str, float]:
|
||||
"""pass@k / pass^k averaged over examples; ``{}`` for non-binary rewards."""
|
||||
rewards = [r.reward for r in self.rollouts]
|
||||
if not set(rewards).issubset({0.0, 1.0}):
|
||||
return {}
|
||||
by_example: dict = {}
|
||||
for r in self.rollouts:
|
||||
by_example.setdefault(r.group_id, []).append(r.reward)
|
||||
per_example = [compute_pass_metrics(rs) for rs in by_example.values()]
|
||||
keys = sorted({k for d in per_example for k in d})
|
||||
return {k: sum(d[k] for d in per_example if k in d) / sum(1 for d in per_example if k in d) for k in keys}
|
||||
|
||||
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
|
||||
out = super().to_wandb(prefix=prefix, subset=subset)
|
||||
if not self.rollouts:
|
||||
return out
|
||||
p = f"{prefix}/{subset}"
|
||||
out[f"{p}/avg@{self.group_size}"] = self.reward.mean()
|
||||
if subset == "effective":
|
||||
out |= {f"{p}/{k}": v for k, v in self.pass_at_k().items()}
|
||||
for agent, traces in self.by_agent().items():
|
||||
p = f"{prefix}/{subset}/{agent}"
|
||||
out[f"{p}/avg@{self.group_size}"] = traces.stats()["reward"].mean()
|
||||
if subset == "effective":
|
||||
out |= {f"{p}/{k}": v for k, v in pass_at_k(traces.rollouts).items()}
|
||||
return out
|
||||
|
||||
|
||||
@@ -360,7 +414,7 @@ class TrainRollouts:
|
||||
|
||||
@property
|
||||
def effective(self) -> TrainRollouts:
|
||||
return TrainRollouts([r for r in self.rollouts if not r.has_error and not r.is_filtered and r.trainable])
|
||||
return TrainRollouts([r for r in self.rollouts if not r.has_error and not r.is_filtered and r.agent.trainable])
|
||||
|
||||
def by_env(self) -> dict[str, TrainRollouts]:
|
||||
grouped: dict[str, list[Rollout]] = {}
|
||||
@@ -399,13 +453,15 @@ class EvalRollouts:
|
||||
return self._group_size
|
||||
counts: dict = {}
|
||||
for r in self.rollouts:
|
||||
if r.trainable:
|
||||
if r.agent.trainable:
|
||||
counts[r.group_id] = counts.get(r.group_id, 0) + 1
|
||||
return max(counts.values(), default=0)
|
||||
|
||||
@property
|
||||
def effective(self) -> EvalRollouts:
|
||||
return EvalRollouts([r for r in self.rollouts if not r.has_error and r.trainable], group_size=self.group_size)
|
||||
return EvalRollouts(
|
||||
[r for r in self.rollouts if not r.has_error and r.agent.trainable], group_size=self.group_size
|
||||
)
|
||||
|
||||
@property
|
||||
def metrics(self) -> EvalMetrics:
|
||||
|
||||
@@ -24,6 +24,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import tomli_w
|
||||
@@ -80,7 +81,7 @@ from prime_rl.utils.config import to_toml_dict
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.monitor import setup_monitor
|
||||
from prime_rl.utils.pathing import get_log_dir, get_trace_path
|
||||
from prime_rl.utils.pathing import get_trace_path
|
||||
from prime_rl.utils.usage_reporter import UsageReporter
|
||||
from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
@@ -241,6 +242,9 @@ class Orchestrator:
|
||||
train_env_names=[env.resolved_name for env in config.train.source],
|
||||
eval_env_names=[source.resolved_name for source in config.eval.source] if config.eval is not None else [],
|
||||
)
|
||||
# ``RunInfo.id`` is required on the trace: fall back to a run-local uuid
|
||||
# when no external monitor identity (W&B) exists.
|
||||
self.run_id = self.monitor.run_id or uuid.uuid4().hex
|
||||
|
||||
if config.heartbeat is not None:
|
||||
self.heart = Heartbeat(config.heartbeat.url)
|
||||
@@ -256,27 +260,22 @@ class Orchestrator:
|
||||
|
||||
get_logger().info("Loading training environments")
|
||||
self.train_envs = TrainEnvs(
|
||||
config.train.source, policy_pool=self.policy_inference, renderer_config=config.renderer
|
||||
config.train.source,
|
||||
config.env_addresses,
|
||||
policy_pool=self.policy_inference,
|
||||
renderer_config=config.renderer,
|
||||
)
|
||||
get_logger().debug(
|
||||
f"Loaded {len(self.train_envs)} training environment(s) ({', '.join(self.train_envs.names)})"
|
||||
)
|
||||
await self.train_envs.start(
|
||||
log_dir=get_log_dir(config.output_dir.parent) / "envs" / "train",
|
||||
log_level=config.log.vf_level,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
await self.train_envs.start()
|
||||
get_logger().success("Train environment(s) ready")
|
||||
|
||||
if config.eval is not None:
|
||||
get_logger().info("Loading eval environment(s)")
|
||||
self.eval_envs = EvalEnvs(config.eval.source)
|
||||
self.eval_envs = EvalEnvs(config.eval.source, config.env_addresses)
|
||||
get_logger().debug(f"Loaded {len(self.eval_envs)} eval environment(s) ({', '.join(self.eval_envs.names)})")
|
||||
await self.eval_envs.start(
|
||||
log_dir=get_log_dir(config.output_dir.parent) / "envs" / "eval",
|
||||
log_level=config.log.vf_level,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
await self.eval_envs.start()
|
||||
get_logger().success("Eval environment(s) ready")
|
||||
|
||||
if config.ckpt is not None and config.ckpt.resume_step is not None and self.ckpt_manager is not None:
|
||||
@@ -339,8 +338,10 @@ class Orchestrator:
|
||||
|
||||
self.lora_name = config.model.lora.name if config.model.lora else None
|
||||
|
||||
self.train_source = TrainSource(self.train_envs)
|
||||
|
||||
if self.resume_step is not None and self.ckpt_manager is not None:
|
||||
self.ckpt_manager.load(self.progress, step=self.resume_step)
|
||||
self.ckpt_manager.load(self.progress, self.train_source, step=self.resume_step)
|
||||
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
|
||||
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
|
||||
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
|
||||
@@ -380,7 +381,6 @@ class Orchestrator:
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = sync_version
|
||||
|
||||
self.train_source = TrainSource(self.train_envs, seed=42)
|
||||
self.eval_source: EvalSource | None = (
|
||||
EvalSource(
|
||||
self.eval_envs,
|
||||
@@ -470,7 +470,11 @@ class Orchestrator:
|
||||
]
|
||||
|
||||
# Base-model eval (policy v0) — fires before any train rollouts, logged at the first
|
||||
# step, unless ``eval.skip_first_step=True`` (or this is a resume)
|
||||
# step, unless ``eval.skip_first_step=True``. On resume, defaults to assuming a clean
|
||||
# exit (evals already completed); set ``eval.retrigger_on_resume=True`` to also re-fire
|
||||
# interval-aligned evals at the checkpoint step (e.g. after a crash).
|
||||
if config.eval is not None and config.eval.retrigger_on_resume and self.resume_step is not None:
|
||||
self.maybe_trigger_eval(self.resume_step)
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
|
||||
# Anchor step-time clock so the first step measures startup → first batch
|
||||
@@ -496,7 +500,7 @@ class Orchestrator:
|
||||
if self.ckpt_manager is not None and self.progress.step > 1:
|
||||
self.progress.step -= 1
|
||||
get_logger().info("Writing final checkpoint")
|
||||
self.ckpt_manager.save(self.progress, step=self.progress.step)
|
||||
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
|
||||
await self.stop()
|
||||
if clean_exit:
|
||||
get_logger().success("Orchestrator finished.")
|
||||
@@ -527,12 +531,12 @@ class Orchestrator:
|
||||
step = episode[0].eval_step if kind == "eval" else self.progress.step
|
||||
assert step is not None
|
||||
run: vf.RunInfo = (
|
||||
vf.EvalRunInfo(id=self.monitor.run_id, step=step)
|
||||
vf.EvalRunInfo(id=self.run_id, step=step)
|
||||
if kind == "eval"
|
||||
else vf.TrainRunInfo(id=self.monitor.run_id, step=step)
|
||||
else vf.TrainRunInfo(id=self.run_id, step=step)
|
||||
)
|
||||
for rollout in episode:
|
||||
rollout.stamp(
|
||||
rollout.record_run(
|
||||
run,
|
||||
env_name=rollout.env_name,
|
||||
group_id=str(rollout.group_id),
|
||||
@@ -900,7 +904,9 @@ class Orchestrator:
|
||||
return 0.0
|
||||
get_logger().info(f"Saving checkpoint at step {step}")
|
||||
t = time.perf_counter()
|
||||
await asyncio.to_thread(self.ckpt_manager.save, self.progress, step)
|
||||
# Synchronous on purpose: the payload is tiny, and snapshotting on the
|
||||
# event loop keeps the dispatcher from mutating TrainSource mid-save
|
||||
self.ckpt_manager.save(self.progress, self.train_source, step)
|
||||
return time.perf_counter() - t
|
||||
|
||||
def update_dispatch_gate(self) -> None:
|
||||
@@ -977,9 +983,6 @@ class Orchestrator:
|
||||
for env in self.train_envs:
|
||||
for pool in (*env.sampler.connected_pools, *env.algorithm.connected_pools):
|
||||
await pool.stop()
|
||||
self.train_envs.shutdown()
|
||||
if self.eval_envs is not None:
|
||||
self.eval_envs.shutdown()
|
||||
if self.usage_reporter is not None:
|
||||
self.usage_reporter.close()
|
||||
|
||||
|
||||
@@ -155,7 +155,7 @@ class TrainSink:
|
||||
message graph. Training is renderer-only across all modes (RL/OPD student, SFT teacher),
|
||||
so every node already carries its tokens. Errored rollouts are dropped at the group
|
||||
level, so skip them here; untrainable traces never become training data."""
|
||||
if rollout.has_error or not rollout.trainable:
|
||||
if rollout.has_error or not rollout.agent.trainable:
|
||||
return
|
||||
samples = await asyncio.to_thread(
|
||||
trace_to_samples,
|
||||
@@ -198,7 +198,7 @@ class TrainSink:
|
||||
)
|
||||
return
|
||||
# Untrainable traces carry no samples and must not skew the group baseline.
|
||||
survivors = [r for r in survivors if r.trainable]
|
||||
survivors = [r for r in survivors if r.agent.trainable]
|
||||
if not survivors:
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user