Compare commits
59
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
436873190d | ||
|
|
f0c339a234 | ||
|
|
9f425fffcb | ||
|
|
16efd8afda | ||
|
|
7d5f2d74a6 | ||
|
|
2a0007f51d | ||
|
|
4e7bc94fcd | ||
|
|
d70075381c | ||
|
|
064ee23a8c | ||
|
|
7c8755d9d5 | ||
|
|
bf3d381cfe | ||
|
|
0be5ac452a | ||
|
|
c5afcaa2e2 | ||
|
|
3cbeb5d0f1 | ||
|
|
f8660256f0 | ||
|
|
a66f8bed1b | ||
|
|
d1f366b1bc | ||
|
|
eb89285418 | ||
|
|
9e1c011ce1 | ||
|
|
d507aeafc0 | ||
|
|
3dd3b30e75 | ||
|
|
3a5f617969 | ||
|
|
c268702f55 | ||
|
|
62702bafa7 | ||
|
|
35b452b01c | ||
|
|
2e29c66fd7 | ||
|
|
d3765e289d | ||
|
|
9bf203c678 | ||
|
|
46bcf628f6 | ||
|
|
a3151e3711 | ||
|
|
c33020a3d4 | ||
|
|
7089ba1e4d | ||
|
|
38494ccb41 | ||
|
|
375d8596d8 | ||
|
|
e035135126 | ||
|
|
533e992ad2 | ||
|
|
858207d340 | ||
|
|
570463cca2 | ||
|
|
31e81e5b18 | ||
|
|
137f8f49c8 | ||
|
|
f04c8d988c | ||
|
|
4d361adacc | ||
|
|
7f77713886 | ||
|
|
efeddae6bb | ||
|
|
8dfe8734e3 | ||
|
|
fa21395a68 | ||
|
|
b5daec1cbb | ||
|
|
b452660025 | ||
|
|
060f25bb3a | ||
|
|
77af037537 | ||
|
|
9281c5589a | ||
|
|
9dbb523933 | ||
|
|
5789850d4d | ||
|
|
146fcd0136 | ||
|
|
b0612a0e1f | ||
|
|
c0a026c0d4 | ||
|
|
7c9c1308dc | ||
|
|
941019f2e3 | ||
|
|
9e1f0521e3 |
@@ -77,8 +77,11 @@ jobs:
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr
|
||||
from prime_rl.utils.validation import validate_shared_ckpt_config
|
||||
|
||||
# `verifiers` (+ its `datasets` dep) is a declared slim dep: the v1 config types
|
||||
# (EnvConfig, Task, ...) extend verifiers.v1, which is pure-pydantic and pulls no
|
||||
# GPU/ML deps. We still forbid the actual heavy training deps below.
|
||||
forbidden = ["torch", "transformers", "vllm", "wandb", "ring_flash_attn",
|
||||
"verifiers", "prime", "datasets", "liger_kernel", "loguru"]
|
||||
"prime", "liger_kernel", "loguru"]
|
||||
leaked = [m for m in forbidden if m in sys.modules]
|
||||
if leaked:
|
||||
raise SystemExit(f"slim install leaked heavy deps into sys.modules: {leaked}")
|
||||
|
||||
+3
-2
@@ -23,7 +23,8 @@ configs/endpoints.py
|
||||
final_summary.json
|
||||
.pydantic_config
|
||||
.chroma_db
|
||||
|
||||
deps/nixl_*
|
||||
nixl_workspace/*
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
@@ -202,4 +203,4 @@ debug_I2_zero_band
|
||||
|
||||
outputs/
|
||||
|
||||
third_party/
|
||||
third_party/
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`orchestrator.algo.length_penalty` restructured to a single `linear` shape; `tokens`/`turns` length penalties removed**: The `grpo`-family length penalty keeps the `[orchestrator.algo.length_penalty]` key but is collapsed to a single `type = "linear"` shape; the discriminated `type = "tokens" | "turns"` efficiency-shaping variants (and the `efficiency_shaping` helper) are removed. The linear penalty subtracts a `pass_rate`-scaled penalty from each reward before the GRPO baseline, summing three terms — `num_output_tokens_weight` × output tokens, `num_input_tokens_weight` × input (non-output) tokens, and `num_turns_weight` × turns — each normalized by the group's own max for that quantity. Field renames within the penalty: `coef` → `num_output_tokens_weight` (default `0.25`), `context_coef` → `num_input_tokens_weight` (default `0.1`), `turns_coef` → `num_turns_weight` (default `0.1`); the `gate_by_correctness` flag is removed. `extra="forbid"` rejects the old keys, so existing configs must migrate. (2026-06-29)
|
||||
- **`model.fused_lm_head_token_chunk_size` `"auto"` option removed**: The `"auto"` value is no longer accepted. Use an explicit integer (e.g. `8192`) or `"disabled"`. The `"auto"` value previously resolved to `8192` for RL training — set `fused_lm_head_token_chunk_size = 8192` explicitly to get the same behavior.
|
||||
- **Memory-saving defaults enabled**: `trainer.model.ac`, `trainer.model.ac_offloading`, `trainer.model.compile`, `trainer.model.optim_cpu_offload`, and `trainer.model.fused_lm_head_token_chunk_size` are now enabled by default to provide sane memory-efficient defaults out of the box. Specifically: `ac` defaults to `ActivationCheckpointConfig()` (full mode), `ac_offloading` defaults to `ActivationOffloadingConfig()`, `compile` defaults to `CompileConfig()` (`fullgraph=false`), `optim_cpu_offload` defaults to `true`, and `fused_lm_head_token_chunk_size` defaults to `1024`. SFT training silently disables `fused_lm_head_token_chunk_size` (sets it to `"disabled"`). Configs using `max_concurrent_runs > 1` must explicitly set `optim_cpu_offload = false`. To disable any of these, set the field to `None` / `"None"` / `false` / `"disabled"` as appropriate.
|
||||
- **`model.ep` defaults to `"auto"`**: The `ep` field type changed from `int` to `int | Literal["auto"]`, defaulting to `"auto"`. At trainer startup, `resolve_ep()` checks if the model is MoE (via `AutoConfig`); if so, it resolves to `min(fsdp_island_size, 8)` where `fsdp_island_size = world_size // dp_replicate`. For non-MoE models, `"auto"` resolves to 1 (no-op). Set `ep` to an explicit integer to override.
|
||||
- **verifiers v1 training integration** (collection of removals/renames). The orchestrator now trains against a v1 env server returning `vf.Trace` rollouts, renderer-only, with a unified token schema.
|
||||
- **`[[orchestrator.train.env]]` is now a v1 `vf.EnvServerConfig`**: a v1 env is `taskset = { id = "<id>" }` + `harness = { id = "default", runtime = { type = "subprocess" } }`. A bare `id = "<id>"` (optionally with `args`) runs the v0 env through the verifiers legacy bridge — old flat `id`/`args`-only configs keep working as legacy envs; v1 envs must use the `taskset`/`harness` shape.
|
||||
- **`orchestrator.train.env` no longer defaults to a `reverse-text` env**: the default is now empty (`[]`), so configs must declare `[[orchestrator.train.env]]` explicitly.
|
||||
- **`...env[].num_workers` → `pool`**: per-env worker sizing moves to a `pool` config (`static`/`elastic`). Back-compat: `num_workers = N` maps to `pool = { type = "static", num_workers = N }` and `"auto"` to the default elastic pool; the group-level `orchestrator.train.num_workers` / `orchestrator.eval.num_workers` are removed.
|
||||
- **`orchestrator.renderer` is now required (MITO removed)**: it was `RendererConfig | None`, where `renderer = None` selected the MITO path; training is now renderer-only, so `renderer` is non-optional. Drop `renderer = None` / `renderer = "None"`.
|
||||
- **`...client.timeout` / `...client.connect_timeout` removed**: the v1 rollout client manages its own timeouts. Drop these from `[orchestrator.student.client]` and `[orchestrator.teacher.client]`. (2026-06-23)
|
||||
- **`orchestrator.advantage` length-penalty overhaul + length-weighted baseline**: `length_penalty` is now a single shape — a linear penalty that subtracts `coef * pass_rate * (model completion tokens / orchestrator.seq_len)` from each reward before the baseline subtraction (`pass_rate` = group mean reward, so solved-often problems get the strongest concision pressure and never-solved groups get none), with an optional `gate_by_correctness` flag (default `false`) that restricts the penalty to correct rollouts (`reward == 1`). The previous discriminated `type = "tokens" | "turns"` efficiency-shaping variants and the per-penalty `max_length` field have been removed — configure `[orchestrator.advantage.length_penalty]` with `coef` (and optionally `gate_by_correctness`) instead; the denominator is always `orchestrator.seq_len`. Also adds `orchestrator.advantage.length_weighted_baseline` (default `false`): when enabled, the GRPO baseline is the token-length-weighted mean reward (`sum(len_i * reward_i) / sum(len_i)`) instead of the plain mean. (2026-06-03)
|
||||
- **`trainer.experimental.token_export` removed → `trainer.enable_token_export`**: `TrainerExperimentalConfig` and the `[trainer.experimental] token_export = true` setting have been removed with no migration alias. Existing trainer configs must delete the `[trainer.experimental]` block and set the new top-level trainer flag instead: `enable_token_export = true` in a trainer config file, or `trainer.enable_token_export = true` when nested under `[trainer]` in an RL config. The trainer entrypoint CLI flag is `--enable-token-export`. (2026-06-10)
|
||||
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
|
||||
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
|
||||
- **`orchestrator.seed` removed**: was only consumed by the deleted buffer; no replacement.
|
||||
|
||||
+96
-8
@@ -32,6 +32,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends --force-yes \
|
||||
libnl-route-3-dev \
|
||||
libibverbs-dev \
|
||||
librdmacm-dev \
|
||||
python3.12 \
|
||||
python3.12-venv \
|
||||
python3.12-dev \
|
||||
&& ln -sf /usr/bin/python3.12 /usr/local/bin/python \
|
||||
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
|
||||
ARG UCX_VERSION=1.19.1
|
||||
@@ -60,8 +64,13 @@ ADD https://astral.sh/uv/install.sh /uv-installer.sh
|
||||
# Set install dir to location accessible to non-root users
|
||||
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
|
||||
ENV PATH="/usr/local/bin:$PATH"
|
||||
ENV UV_PYTHON_INSTALL_DIR="/usr/local/share/uv/python"
|
||||
# Build .venv against the system CPython, so the venv's recorded interpreter
|
||||
# matches the runtime interpreter and no bin/python relink is needed at runtime.
|
||||
ENV UV_PYTHON_PREFERENCE=only-system
|
||||
ENV UV_CACHE_DIR="/usr/local/share/uv/cache"
|
||||
# Explicity set venv dir inside /app so to ensure it gets copied over during
|
||||
# the runtime stage's `COPY /app`
|
||||
ENV UV_PROJECT_ENVIRONMENT="/app/.venv"
|
||||
|
||||
# Install Python dependencies (The gradual copies help with caching)
|
||||
WORKDIR /app
|
||||
@@ -77,26 +86,92 @@ COPY deps/ /app/deps/
|
||||
COPY configs /app/configs
|
||||
COPY examples /app/examples
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
|
||||
|
||||
# Use submodule git metadata from the build context when present. Docker copies
|
||||
# only the submodule .git pointer files into /app/deps, so we temporarily link
|
||||
# /app/.git/modules to the read-only context before resolving versions.
|
||||
# Opt-in extras for disaggregated P/D inference (deep-ep, deep-gemm, quack).
|
||||
# Default off — they're heavy source builds only the disagg-MoE path needs.
|
||||
# Enable via `--build-arg INCLUDE_DISAGG_EXTRAS=1`.
|
||||
ARG INCLUDE_DISAGG_EXTRAS=0
|
||||
ARG VERIFIERS_PRETEND_VERSION
|
||||
ARG RENDERERS_PRETEND_VERSION
|
||||
RUN --mount=type=cache,target=/app/.cache/uv \
|
||||
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --extra modelexpress --group mamba-ssm --locked --no-dev
|
||||
--mount=type=bind,source=.,target=/build-context,readonly \
|
||||
if [ -d /build-context/.git/modules ]; then mkdir -p /app/.git && ln -s /build-context/.git/modules /app/.git/modules; fi \
|
||||
&& \
|
||||
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
|
||||
&& \
|
||||
if [ -L /app/.git/modules ]; then rm /app/.git/modules && rmdir /app/.git 2>/dev/null || true; fi \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" /app/deps/verifiers/pyproject.toml \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
|
||||
&& \
|
||||
EXTRA_DISAGG_FLAG=""; if [ "$INCLUDE_DISAGG_EXTRAS" = "1" ]; then EXTRA_DISAGG_FLAG="--extra disagg"; fi \
|
||||
&& \
|
||||
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --extra modelexpress $EXTRA_DISAGG_FLAG --group mamba-ssm --locked --no-dev
|
||||
|
||||
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
|
||||
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
|
||||
# (#2883); rebuilding against our UCX is the documented fix. Only needed for
|
||||
# the disaggregated P/D path — default off so training-only / single-node
|
||||
# inference builds are unaffected. Enable via `--build-arg INCLUDE_NIXL_FROM_SOURCE=1`.
|
||||
ARG INCLUDE_NIXL_FROM_SOURCE=0
|
||||
ARG NIXL_VERSION=0.10.1
|
||||
RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
|
||||
VIRTUAL_ENV=/app/.venv uv pip install pip \
|
||||
&& git clone --depth 1 --branch ${NIXL_VERSION} https://github.com/ai-dynamo/nixl.git /tmp/nixl \
|
||||
&& cd /tmp/nixl \
|
||||
&& PKG_CONFIG_PATH=/opt/ucx/lib/pkgconfig \
|
||||
LD_LIBRARY_PATH=/opt/ucx/lib:/opt/ucx/lib/ucx \
|
||||
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/app/deps \
|
||||
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu12-*.whl \
|
||||
&& 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
|
||||
|
||||
FROM python:3.12-slim
|
||||
# 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
|
||||
# archives since nvcc JIT (TileLang/FlashInfer build their own kernels) and torch
|
||||
# (uses pinned nvidia-* wheels) needs them. Keeps nvcc/nvvm/ptxas + headers +
|
||||
# libcudart/libnvrtc/libcudadevrt for JIT compile+link.
|
||||
FROM builder AS cuda-trim
|
||||
RUN find /usr/local/cuda-12.8/targets/*/lib \
|
||||
\( -name 'libcublas*' -o -name 'libcusparse*' -o -name 'libcufft*' \
|
||||
-o -name 'libcusolver*' -o -name 'libcurand*' -o -name 'libnpp*' \
|
||||
-o -name 'libnvjpeg*' -o -name 'libnvblas*' \) -delete \
|
||||
&& find /usr/local/cuda-12.8 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
|
||||
|
||||
# CUDA 13 runtime libs source
|
||||
FROM nvidia/cuda:13.0.1-runtime-ubuntu24.04 AS cuda13
|
||||
RUN mkdir -p /cu13 && cp -d $(find /usr/local \
|
||||
-name 'libcudart.so.13*' -o -name 'libnvrtc.so.13*' -o -name 'libnvrtc-builtins.so.13*') /cu13/
|
||||
|
||||
# Runtime image
|
||||
FROM nvidia/cuda:12.8.1-base-ubuntu24.04
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
--no-install-recommends \
|
||||
--force-yes \
|
||||
python3.12 \
|
||||
python3.12-venv \
|
||||
python3.12-dev \
|
||||
build-essential \
|
||||
wget \
|
||||
clang \
|
||||
tmux \
|
||||
iperf \
|
||||
openssh-server \
|
||||
git \
|
||||
git-lfs \
|
||||
gpg \
|
||||
sudo \
|
||||
@@ -110,13 +185,30 @@ RUN apt-get update && apt-get install -y \
|
||||
libibverbs1 \
|
||||
ibverbs-providers \
|
||||
librdmacm1 \
|
||||
&& ln -sf /usr/bin/python3.12 /usr/local/bin/python \
|
||||
&& apt-get clean autoclean \
|
||||
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
|
||||
# CUDA 12.8 toolkit (TileLang's runtime nvcc JIT)
|
||||
COPY --from=cuda-trim /usr/local/cuda-12.8 /usr/local/cuda-12.8
|
||||
RUN ln -sfn /usr/local/cuda-12.8 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
|
||||
ENV CUDA_HOME=/usr/local/cuda
|
||||
ENV PATH="/usr/local/cuda/bin:${PATH}"
|
||||
|
||||
# CUDA 13 runtime libs for deep-gemm
|
||||
COPY --from=cuda13 /cu13/ /opt/cuda13/lib64/
|
||||
RUN echo /opt/cuda13/lib64 > /etc/ld.so.conf.d/cuda13.conf \
|
||||
&& ldconfig \
|
||||
&& ldconfig -p | grep -q libcudart.so.13 \
|
||||
&& ldconfig -p | grep -q libnvrtc.so.13
|
||||
|
||||
|
||||
ARG USER_ID=1000
|
||||
ARG GROUP_ID=1000
|
||||
RUN groupadd --gid $GROUP_ID appuser && \
|
||||
|
||||
RUN userdel -r ubuntu 2>/dev/null || true; \
|
||||
groupdel ubuntu 2>/dev/null || true; \
|
||||
groupadd --gid $GROUP_ID appuser && \
|
||||
useradd --uid $USER_ID --gid appuser --create-home --shell /bin/bash appuser && \
|
||||
usermod -aG sudo appuser && \
|
||||
echo "appuser ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
|
||||
@@ -136,10 +228,6 @@ COPY --from=builder /opt/ucx /opt/ucx
|
||||
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
|
||||
RUN chmod +x /app/docker-entrypoint.sh
|
||||
|
||||
RUN rm /app/.venv/bin/python && ln -s /usr/local/bin/python /app/.venv/bin/python
|
||||
RUN rm /app/.venv/bin/python3 && ln -s /usr/local/bin/python /app/.venv/bin/python3
|
||||
RUN rm /app/.venv/bin/python3.12 && ln -s /usr/local/bin/python /app/.venv/bin/python3.12
|
||||
|
||||
# Place executables in the environment at the front of the path
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
ENV UCX_HOME=/opt/ucx
|
||||
|
||||
@@ -38,6 +38,7 @@ PRIME-RL is a framework for large-scale reinforcement learning. It is designed t
|
||||
5. Multi-node deployment with Slurm and Kubernetes support.
|
||||
6. Multimodal support for VLMs such as Qwen3-VL.
|
||||
7. Hackable, modular, and extensible by design.
|
||||
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/glm5_llmd/README.md).
|
||||
|
||||
|
||||
## Models support
|
||||
@@ -221,6 +222,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
|
||||
3. [**Intellect-3.1**](examples/Intellect-3.1/README.md): Reproduce our `INTELLECT-3.1` training run.
|
||||
4. [**MiniMax-M2.5 SWE**](examples/minimax_m2.5_swe/README.md): Train `MiniMax-M2.5` on agentic SWE tasks.
|
||||
5. [**High-throughput GLM-5**](examples/glm5_pd_disag/README.md): Train `GLM-5` with PD disaggregation and FP8 inference on SWE.
|
||||
6. [**High-throughput GLM-5 (llm-d)**](examples/glm5_llmd/README.md): One-line SLURM deployment for `GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload — the faster way to run `GLM-5`.
|
||||
|
||||
## Docs
|
||||
|
||||
|
||||
+16
-16
@@ -15,34 +15,34 @@
|
||||
"cp": 1,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "0b37bc923",
|
||||
"timestamp": "2026-05-19T01:28:25+00:00",
|
||||
"commit_sha": "c88d08fdf",
|
||||
"timestamp": "2026-06-24T22:50:40+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 276.12556480802596
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 22.77046832707997,
|
||||
"std": 0.03172890658906481,
|
||||
"min": 22.750797215697055,
|
||||
"max": 22.80707156937409
|
||||
"mean": 20.802552047875178,
|
||||
"std": 0.16199364988631793,
|
||||
"min": 20.664358307416567,
|
||||
"max": 20.98082222151257
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 2719.4358949662887,
|
||||
"std": 3.7893259921987053,
|
||||
"min": 2717.086609671837,
|
||||
"max": 2723.8073540657224
|
||||
"mean": 2484.411208996455,
|
||||
"std": 19.346608946709658,
|
||||
"min": 2467.9069802355616,
|
||||
"max": 2505.7016937694384
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 48.285218452724315,
|
||||
"std": 0.06726350421944344,
|
||||
"min": 48.207625919021666,
|
||||
"max": 48.327002701349556
|
||||
"mean": 52.79691480938345,
|
||||
"std": 0.4071756223542672,
|
||||
"min": 52.35017399210483,
|
||||
"max": 53.14720633160323
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 24.248046875,
|
||||
"pct": 51.15428047554115
|
||||
"gib": 11.728515625,
|
||||
"pct": 24.742767157118376
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+16
-16
@@ -15,34 +15,34 @@
|
||||
"cp": 1,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "0b37bc923",
|
||||
"timestamp": "2026-05-19T01:32:27+00:00",
|
||||
"commit_sha": "c88d08fdf",
|
||||
"timestamp": "2026-06-24T22:55:54+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 291.91085167229176
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 21.824271379711288,
|
||||
"std": 0.07444985226850119,
|
||||
"min": 21.739369034306105,
|
||||
"max": 21.878404774433935
|
||||
"mean": 17.217465998339005,
|
||||
"std": 0.02905058130694137,
|
||||
"min": 17.19503698271855,
|
||||
"max": 17.250282374540514
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 10425.733211800512,
|
||||
"std": 35.565645418564436,
|
||||
"min": 10385.174276894972,
|
||||
"max": 10451.593425935866
|
||||
"mean": 8225.003435798719,
|
||||
"std": 13.877833769765575,
|
||||
"min": 8214.288808538377,
|
||||
"max": 8240.68023789224
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 50.39627862814814,
|
||||
"std": 0.1756523472528039,
|
||||
"min": 50.26670710090548,
|
||||
"max": 50.59620195720345
|
||||
"mean": 63.90305413212627,
|
||||
"std": 0.11015530079183487,
|
||||
"min": 63.77801387012005,
|
||||
"max": 63.985770548693836
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 17.490234375,
|
||||
"pct": 36.897831788841806
|
||||
"gib": 6.298828125,
|
||||
"pct": 13.288163877053583
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
max_steps = 500
|
||||
seq_len = 8192
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
|
||||
[wandb]
|
||||
project = "acereason-math"
|
||||
name = "stage1"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 1024
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
group_size = 1
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2024"
|
||||
group_size = 32
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2025"
|
||||
group_size = 32
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
@@ -1,54 +0,0 @@
|
||||
max_steps = 1000
|
||||
seq_len = 16384
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
resume_step = 500
|
||||
|
||||
[wandb]
|
||||
project = "acereason-math"
|
||||
name = "stage2"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 2048
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_completion_tokens = 16384
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
group_size = 1
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2024"
|
||||
group_size = 32
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2025"
|
||||
group_size = 32
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
@@ -24,7 +24,7 @@ args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_tur
|
||||
[inference]
|
||||
|
||||
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
|
||||
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
|
||||
# <think> blocks. Match that with renderer thinking_retention.
|
||||
[orchestrator.renderer]
|
||||
name = "auto"
|
||||
preserve_all_thinking = true
|
||||
thinking_retention = "all"
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
# Trainer config for multi-run RL integration test
|
||||
max_concurrent_runs = 2
|
||||
enable_token_export = true
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
seq_len = 65536
|
||||
fused_lm_head_token_chunk_size = 8192
|
||||
optim_cpu_offload = false
|
||||
|
||||
[model.lora]
|
||||
rank = 8
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Smoke test for the RL-entrypoint OPD (on-policy distillation) training mode.
|
||||
# The student inference deployment is launched by the rl entrypoint on GPU 0;
|
||||
# the teacher inference server is started externally by the test fixture (see
|
||||
# Smoke test for the RL-entrypoint opd algorithm (on-policy distillation).
|
||||
# The policy inference deployment is launched by the rl entrypoint on GPU 0;
|
||||
# the frozen reference server is started externally by the test fixture (see
|
||||
# tests/integration/test_reverse_text_rl_opd.py) on the same GPU. Trainer
|
||||
# takes GPU 1. Training config mirrors `reverse_text/start.toml`.
|
||||
|
||||
max_steps = 5
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
@@ -15,10 +15,16 @@ project = "reverse-text-ci"
|
||||
name = "ci-rl-opd"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "opd"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "opd"
|
||||
|
||||
[orchestrator.algo.teacher]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
@@ -38,12 +44,6 @@ max_completion_tokens = 128
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Smoke test for the RL-entrypoint SFT (on-policy hard distillation) training
|
||||
# mode. The student inference deployment is launched by the rl entrypoint on
|
||||
# GPU 0; the teacher inference server is started externally by the test
|
||||
# fixture (see tests/integration/test_reverse_text_rl_sft.py) on the same GPU.
|
||||
# Trainer takes GPU 1. Training config mirrors `reverse_text/start.toml`.
|
||||
# Smoke test for the RL-entrypoint sft algorithm (hard distillation).
|
||||
# The policy inference deployment is launched by the rl entrypoint on GPU 0;
|
||||
# the frozen sampling server is started externally by the test fixture (see
|
||||
# tests/integration/test_reverse_text_rl_sft.py) on the same GPU. Trainer
|
||||
# takes GPU 1. Training config mirrors `reverse_text/start.toml`.
|
||||
|
||||
max_steps = 5
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
@@ -15,10 +15,26 @@ project = "reverse-text-ci"
|
||||
name = "ci-rl-sft"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "sft"
|
||||
|
||||
# sft's teacher IS the model it samples from.
|
||||
[orchestrator.algo.sampling.source]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
# The student's renderer tokenizes the teacher's messages into the student's
|
||||
# token space (backfill). Use `default` (wraps the student tokenizer's
|
||||
# apply_chat_template) so the CE target is faithful to the student's actual
|
||||
# chat template. The stock `qwen3` renderer reimplements the Qwen format and
|
||||
# injects an empty `<think></think>` block, which this model's custom template
|
||||
# does not emit — corrupting the distillation target.
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -35,12 +51,6 @@ max_completion_tokens = 128
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
# Run on 8xH200
|
||||
# Similar to configs/acereason_math/stage1.toml, but
|
||||
# - 300 instead of 500 steps
|
||||
# - No checkpointing
|
||||
# - No evals
|
||||
max_steps = 300
|
||||
seq_len = 8192
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 1024
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "acereason-math"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference]
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
@@ -21,8 +21,9 @@ group_size = 16
|
||||
max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
|
||||
name = "color-codeword"
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
|
||||
[trainer]
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# Algorithm — Debug Configs
|
||||
|
||||
Minimal end-to-end configs for the algorithms against bundled verifiers envs, using `PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT` as the policy.
|
||||
|
||||
| Config | Algorithm | Frozen model | Notes |
|
||||
|---|---|---|---|
|
||||
| `grpo.toml` | `grpo` | none | |
|
||||
| `max_rl.toml` | `max_rl` | none | GRPO with mean-normalized advantages (maximum-likelihood RL) |
|
||||
| `opd.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
|
||||
| `opd_lora.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
|
||||
| `sft_distill.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
|
||||
| `sft_distill_lora.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
|
||||
| `self_distill.toml` | `opsd` | none (self-distills against the live policy) | SDFT; demo from reverse-text's `answer` field |
|
||||
| `echo.toml` | `echo` | none | multi-turn `alphabet-sort`; CE on observation tokens |
|
||||
| `mixed_grpo_opd.toml` | `grpo` + `opd` (per env) | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | two envs, one run; heterogeneous batches (with/without `ref_logprobs`) |
|
||||
|
||||
The policy inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local frozen model (used by `opd*.toml`, `sft_distill.toml` / `sft_distill_lora.toml`, and `mixed_grpo_opd.toml`) is **not** auto-launched — start it manually on GPU 1.
|
||||
|
||||
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for `opd`, `[orchestrator.algo.sampling.source]` for `sft` — with `name` + `base_url`. `opsd` declares none (it self-distills against the live policy). prime-rl never hosts them; only the trainable policy's server is managed by the `rl` entrypoint.
|
||||
|
||||
## Start the local frozen model
|
||||
|
||||
Needed for `opd*.toml`, `sft_distill.toml` / `sft_distill_lora.toml`, and `mixed_grpo_opd.toml`:
|
||||
|
||||
```bash
|
||||
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
|
||||
```
|
||||
|
||||
## Run the debug configs
|
||||
|
||||
Every config writes to the default `outputs/` directory, so running two back-to-back — or re-running one — fails with `FileExistsError`. Pass a distinct `--output-dir outputs/<algo>` per config (recommended for a sweep) or `--clean-output-dir` to wipe and restart.
|
||||
|
||||
```bash
|
||||
# GRPO (no frozen model)
|
||||
uv run rl @ configs/debug/algorithms/grpo.toml --output-dir outputs/grpo
|
||||
|
||||
# MaxRL (no frozen model)
|
||||
uv run rl @ configs/debug/algorithms/max_rl.toml --output-dir outputs/max_rl
|
||||
|
||||
# OPD (needs the frozen model on port 8001)
|
||||
uv run rl @ configs/debug/algorithms/opd.toml --output-dir outputs/opd
|
||||
uv run rl @ configs/debug/algorithms/opd_lora.toml --output-dir outputs/opd_lora
|
||||
|
||||
# SFT distillation (needs the frozen model on port 8001)
|
||||
uv run rl @ configs/debug/algorithms/sft_distill.toml --output-dir outputs/sft_distill
|
||||
uv run rl @ configs/debug/algorithms/sft_distill_lora.toml --output-dir outputs/sft_distill_lora
|
||||
|
||||
# Self-distillation against the live policy (no frozen model)
|
||||
uv run rl @ configs/debug/algorithms/self_distill.toml --output-dir outputs/self_distill
|
||||
|
||||
# ECHO (no frozen model; multi-turn env)
|
||||
uv run rl @ configs/debug/algorithms/echo.toml --output-dir outputs/echo
|
||||
|
||||
# Mixed per-env algorithms: GRPO + OPD in one run (needs the frozen model on port 8001)
|
||||
uv run rl @ configs/debug/algorithms/mixed_grpo_opd.toml --output-dir outputs/mixed_grpo_opd
|
||||
```
|
||||
|
||||
See [docs/algorithms.md](../../../docs/algorithms.md) for what each algorithm does and how to author your own.
|
||||
@@ -0,0 +1,50 @@
|
||||
# ECHO on the multi-turn alphabet-sort env (bundled with verifiers): GRPO on
|
||||
# action tokens + weighted CE on the env's observation tokens.
|
||||
# uv run rl @ configs/debug/algorithms/echo.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 4096
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "algorithms-debug"
|
||||
name = "debug-echo"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 32
|
||||
group_size = 4
|
||||
|
||||
# alphabet-sort's feedback arrives as user messages, so train the user role
|
||||
# instead of echo's tool default.
|
||||
[orchestrator.algo]
|
||||
type = "echo"
|
||||
|
||||
[orchestrator.algo.roles.user]
|
||||
alpha = 0.1
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "alphabet-sort"
|
||||
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
# ECHO learns from observation tokens even when the GRPO advantage collapses
|
||||
# to zero — keep zero-advantage rollouts in the batch.
|
||||
[[orchestrator.post_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
enforce = false
|
||||
|
||||
# Qwen3 finetune with the standard PI template patch; always re-emits prior
|
||||
# <think> blocks, matched by renderer thinking_retention.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
thinking_retention = "all"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-6
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -5,14 +5,16 @@ seq_len = 2048
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
project = "algorithms-debug"
|
||||
name = "debug-rl"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "rl"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
@@ -5,27 +5,39 @@ seq_len = 2048
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text-v1"
|
||||
project = "algorithms-debug"
|
||||
name = "debug-max-rl"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "max_rl"
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
args = { v1 = true }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -0,0 +1,63 @@
|
||||
# Mixed per-env algorithms in one run: a GRPO env and an OPD env, both on
|
||||
# reverse-text. Exercises heterogeneous train batches — OPD samples ship
|
||||
# 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
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/algorithms/mixed_grpo_opd.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "algorithms-debug"
|
||||
name = "debug-mixed-grpo-opd"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
name = "reverse-text-grpo"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
name = "reverse-text-opd"
|
||||
|
||||
[orchestrator.train.env.algo]
|
||||
type = "opd"
|
||||
|
||||
[orchestrator.train.env.algo.teacher]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -1,9 +1,9 @@
|
||||
# Start the teacher inference server first (on a separate GPU):
|
||||
# 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
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/training_modes/opd.toml
|
||||
# uv run rl @ configs/debug/algorithms/opd.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
@@ -12,14 +12,21 @@ seq_len = 2048
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
project = "algorithms-debug"
|
||||
name = "debug-opd"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "opd"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "opd"
|
||||
|
||||
[orchestrator.algo.teacher]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
@@ -39,12 +46,6 @@ max_completion_tokens = 128
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
+11
-10
@@ -1,9 +1,9 @@
|
||||
# Start the teacher inference server first (on a separate GPU):
|
||||
# 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
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/training_modes/opd_lora.toml
|
||||
# uv run rl @ configs/debug/algorithms/opd_lora.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
@@ -12,14 +12,21 @@ seq_len = 2048
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
project = "algorithms-debug"
|
||||
name = "debug-opd-lora"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "opd"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "opd"
|
||||
|
||||
[orchestrator.algo.teacher]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
@@ -39,12 +46,6 @@ max_completion_tokens = 128
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Self-distillation (SDFT, https://arxiv.org/abs/2601.19897) against the live
|
||||
# policy itself: the reference for each completion is the current model
|
||||
# conditioned on the expert demonstration — no extra deployment needed.
|
||||
# reverse-text carries the demonstration in its top-level `answer` field.
|
||||
# uv run rl @ configs/debug/algorithms/self_distill.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "algorithms-debug"
|
||||
name = "debug-self-distill"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 32
|
||||
group_size = 1
|
||||
|
||||
# reverse-text's demo lives in the "answer" column.
|
||||
[orchestrator.algo]
|
||||
type = "opsd"
|
||||
demo_key = "answer"
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -1,9 +1,9 @@
|
||||
# Start the teacher inference server first (on a separate GPU):
|
||||
# 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
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/training_modes/sft.toml
|
||||
# uv run rl @ configs/debug/algorithms/sft_distill.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
@@ -12,14 +12,29 @@ seq_len = 2048
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
project = "algorithms-debug"
|
||||
name = "debug-sft"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
group_size = 4
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "sft"
|
||||
|
||||
# sft's teacher IS the model it samples from.
|
||||
[orchestrator.algo.sampling.source]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
# The student's renderer tokenizes the teacher's messages into the student's
|
||||
# token space (backfill). Use `default` (wraps the student tokenizer's
|
||||
# apply_chat_template) so the CE target is faithful to the student's actual
|
||||
# chat template. The stock `qwen3` renderer injects an empty `<think></think>`
|
||||
# block this model's custom template never emits, corrupting the target.
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -36,12 +51,6 @@ max_completion_tokens = 128
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
+19
-10
@@ -1,9 +1,9 @@
|
||||
# Start the teacher inference server first (on a separate GPU):
|
||||
# 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
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/training_modes/sft_lora.toml
|
||||
# uv run rl @ configs/debug/algorithms/sft_distill_lora.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
@@ -12,14 +12,29 @@ seq_len = 2048
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
project = "algorithms-debug"
|
||||
name = "debug-sft-lora"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
group_size = 4
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "sft"
|
||||
|
||||
# sft's teacher IS the model it samples from.
|
||||
[orchestrator.algo.sampling.source]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
# The student's renderer tokenizes the teacher's messages into the student's
|
||||
# token space (backfill). Use `default` (wraps the student tokenizer's
|
||||
# apply_chat_template) so the CE target is faithful to the student's actual
|
||||
# chat template. The stock `qwen3` renderer injects an empty `<think></think>`
|
||||
# block this model's custom template never emits, corrupting the target.
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -36,12 +51,6 @@ max_completion_tokens = 128
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
|
||||
@@ -22,8 +22,8 @@ name = "hendrycks-math"
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2024"
|
||||
name = "aime2024"
|
||||
taskset = { id = "aime24-v1" }
|
||||
group_size = 16
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
@@ -9,7 +9,6 @@ project = "reverse-text-debug"
|
||||
name = "debug-multi-env"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "rl"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
|
||||
@@ -40,8 +40,9 @@ enforce = false
|
||||
max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
|
||||
name = "color-codeword"
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
|
||||
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
|
||||
# MODEL_RENDERER_MAP to Qwen3VLRenderer at runtime; no explicit name needed.
|
||||
|
||||
@@ -5,3 +5,4 @@ batch_size = 2
|
||||
|
||||
[model]
|
||||
seq_len = 1024
|
||||
compile = "None"
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
max_steps = 5
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
compile = "None"
|
||||
|
||||
[data]
|
||||
type = "fake"
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
# Training Mode — Debug Configs
|
||||
|
||||
Minimal end-to-end configs for the three training modes (`rl` / `opd` / `sft`) against the `reverse-text` env, using `PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT` as the student.
|
||||
|
||||
| Config | Mode | Teacher | Notes |
|
||||
|---|---|---|---|
|
||||
| `rl.toml` | `rl` | none | |
|
||||
| `opd.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
|
||||
| `opd_lora.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
|
||||
| `sft.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
|
||||
| `sft_lora.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
|
||||
| `sft_external.toml` | `sft` | PI inference (`openai/gpt-5-mini`) | external OAI endpoint; no local teacher |
|
||||
|
||||
The student inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local teacher (used by everything except `rl.toml` and `sft_external.toml`) is **not** auto-launched — start it manually on GPU 1.
|
||||
|
||||
## Start the local teacher
|
||||
|
||||
Needed for `opd*.toml` and `sft.toml` / `sft_lora.toml`:
|
||||
|
||||
```bash
|
||||
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
|
||||
```
|
||||
|
||||
## Run the debug configs
|
||||
|
||||
```bash
|
||||
# RL (no teacher)
|
||||
uv run rl @ configs/debug/training_modes/rl.toml
|
||||
|
||||
# OPD (needs teacher on port 8001)
|
||||
uv run rl @ configs/debug/training_modes/opd.toml
|
||||
uv run rl @ configs/debug/training_modes/opd_lora.toml
|
||||
|
||||
# SFT hard distill (needs teacher on port 8001)
|
||||
uv run rl @ configs/debug/training_modes/sft.toml
|
||||
uv run rl @ configs/debug/training_modes/sft_lora.toml
|
||||
|
||||
# SFT hard distill from openai/gpt-5-mini via PI inference
|
||||
# (requires PRIME_API_KEY + PRIME_TEAM_ID in env; no local teacher needed)
|
||||
uv run rl @ configs/debug/training_modes/sft_external.toml
|
||||
```
|
||||
|
||||
See [docs/training.md](../../docs/training.md#training-modes-rl--opd--sft-via-orchestrator) for what each mode does.
|
||||
@@ -1,55 +0,0 @@
|
||||
# SFT from openai/gpt-5-mini via PI inference.
|
||||
# Requires PRIME_API_KEY + PRIME_TEAM_ID in the environment.
|
||||
#
|
||||
# Run with:
|
||||
# uv run rl @ configs/debug/training_modes/sft_external.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-sft-external"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
group_size = 4
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
extra_body = { reasoning_effort = "minimal" }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "openai/gpt-5-mini"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["https://api.pinference.ai/api/v1"]
|
||||
api_key_var = "PRIME_API_KEY"
|
||||
|
||||
[orchestrator.teacher.client.headers_from_env]
|
||||
X-Prime-Team-ID = "PRIME_TEAM_ID"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -0,0 +1,42 @@
|
||||
# v1 port of examples/alphabet_sort/rl.toml — identical except the env block, which loads
|
||||
# the v1 `alphabet-sort-v1` taskset (multi-turn via a colocated vf.User) instead of the v0
|
||||
# `primeintellect/alphabet-sort` env. Harness runs on the subprocess runtime.
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[wandb]
|
||||
project = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
|
||||
[trainer.model]
|
||||
impl = "auto"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 32
|
||||
alpha = 64
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "alphabet-sort"
|
||||
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
|
||||
[inference] # Default inference config
|
||||
@@ -0,0 +1,54 @@
|
||||
# Debug v1 RL run: the v1 `general-agent-v1` taskset (GeneralAgentSolverTaskset) driven by the
|
||||
# default harness, with the agent and its tool server colocated in a modal sandbox. Copied from
|
||||
# configs/general_agent/rl_qwen3_4b.toml and rewired for v1 (taskset + harness + renderer; the
|
||||
# v0 `id = "general-agent-solver-rlm"` env becomes the v1 taskset + a separate harness).
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 32768
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[wandb]
|
||||
project = "general-agent-debug"
|
||||
name = "qwen3-4b-v1"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
keep_last = 1
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
cp = 2
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 8
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
# v1 general-agent solver taskset; the tool server is colocated in the harness's modal sandbox.
|
||||
taskset = { id = "general-agent-v1", tools = { colocated = true } }
|
||||
harness = { id = "default", runtime = { type = "modal" } }
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 32768
|
||||
|
||||
[inference.parallel]
|
||||
dp = 4
|
||||
@@ -0,0 +1,124 @@
|
||||
# v1 RL ablation: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, bash_edit harness on
|
||||
# a prime sandbox runtime; eval on SWE-Bench Verified. Router replay is enabled
|
||||
# (trainer.enable_router_replay replays the routed-expert decisions returned by inference via
|
||||
# enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe model, which supports routed_experts.
|
||||
#
|
||||
# 2 train + 4 infer nodes. Trainer uses cp=8 (ulysses) plus
|
||||
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), optimizer
|
||||
# CPU offload, and skip-gather / skip-optimizer checkpointing. Derived from
|
||||
# configs/debug/v1/scaleswe.toml + GLM-4.5-Air model settings from the int5 opencode configs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 65536
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/triton-cache-$USER-$SLURM_JOB_ID"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-swe"
|
||||
project_dir = "."
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (label == SLURM job name).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "$SLURM_JOB_NAME" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
project = "swe-ablations"
|
||||
name = "glm45air-scaleswe"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 8
|
||||
cp_style = "ulysses"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "scaleswe"
|
||||
taskset = { id = "scaleswe-v1" }
|
||||
harness = { id = "bash_edit", runtime = { type = "prime", labels = ["glm45air-swe"] } }
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash_edit harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
skip_first_step = false
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "swebench-verified"
|
||||
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
|
||||
harness = { id = "bash_edit", runtime = { type = "prime", labels = ["glm45air-swe"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
enable_prefix_caching = true
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm_cache_$(whoami)"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/flashinfer-$(whoami)"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 65536
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -0,0 +1,41 @@
|
||||
# GSM8K (v1) — the v1 port of configs/gsm8k/rl.toml. Trains Qwen3-0.6B on GSM8K through the
|
||||
# v1 env server: the orchestrator spawns a v1 EnvServer for the gsm8k-v1 taskset and trains on
|
||||
# the returned Traces. Runs on 2 GPUs (1 inference, 1 training):
|
||||
# uv run inference --model.name PrimeIntellect/Qwen3-0.6B # Inference pane (GPU 0)
|
||||
# uv run rl @ configs/debug/v1/gsm8k.toml --ckpt # Trainer pane (GPU 1)
|
||||
|
||||
max_steps = 100
|
||||
seq_len = 2048
|
||||
|
||||
[wandb]
|
||||
project = "gsm8k-debug"
|
||||
name = "gsm8k-v1"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
taskset = { id = "gsm8k-v1", split = "train" }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
num_examples = 256
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
taskset = { id = "gsm8k-v1", split = "test" }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
[inference] # Default inference config
|
||||
@@ -0,0 +1,55 @@
|
||||
# v1 analog of examples/hendrycks_sanity/rl.toml — identical config with only
|
||||
# the env sections swapped to v1 taskset/harness syntax (math-env taskset,
|
||||
# default harness, modal runtime). Submits to slurm by default; pass --no-slurm
|
||||
# to run locally.
|
||||
|
||||
output_dir = "/beegfs/mika/hendrycks-sanity-v1"
|
||||
max_steps = 200
|
||||
|
||||
[wandb]
|
||||
project = "hendrycks-sanity"
|
||||
name = "v1"
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[slurm]
|
||||
job_name = "hendrycks-modal"
|
||||
partition = "all"
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 8
|
||||
seq_len = 8192
|
||||
max_inflight_rollouts = 256
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "hendrycks-math"
|
||||
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
harness = { id = "default", runtime = { type = "modal" } }
|
||||
timeout = { scoring = 300 }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "aime2024"
|
||||
taskset = { id = "aime24-v1" }
|
||||
harness = { id = "default", runtime = { type = "modal" } }
|
||||
timeout = { scoring = 300 }
|
||||
group_size = 32
|
||||
|
||||
[trainer.model]
|
||||
seq_len = 16384
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 8192
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
@@ -1,3 +1,5 @@
|
||||
# Qwen3.5-4B SWE RL on the v1 `r2e-gym-v1` taskset through the rlm harness on the prime runtime.
|
||||
|
||||
output_dir = "/beegfs/mika/rlm-swe-qwen35-4b"
|
||||
max_steps = 400
|
||||
seq_len = 65536
|
||||
@@ -58,29 +60,12 @@ enable_thinking = true
|
||||
temperature = 1.0
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "rlm_swe"
|
||||
name = "rlm-swe-r2e"
|
||||
num_workers = 4
|
||||
|
||||
[orchestrator.train.env.args]
|
||||
labels = ["rlm-swe-qwen35-4b"]
|
||||
taskset = { id = "r2e-gym-v1" }
|
||||
harness = { id = "rlm", runtime = { type = "prime", labels = ["rlm-swe-qwen35-4b"] } }
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "rlm_swe"
|
||||
name = "rlm-swe-swebench-verified-quick"
|
||||
num_workers = 4
|
||||
timeout = 3600
|
||||
|
||||
[orchestrator.eval.env.args]
|
||||
task_type = "swebench"
|
||||
dataset_name = "PrimeIntellect/SWE-Bench-Verified-Quick"
|
||||
labels = ["rlm-swe-qwen35-4b"]
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
@@ -0,0 +1,41 @@
|
||||
# Debug RL run on the v1 env server (reverse-text starter).
|
||||
# The orchestrator spawns a v1 EnvServer per env (it never loads the env
|
||||
# itself), dispatches rollouts by task index, and trains on the returned Traces
|
||||
# (renderer-tokenized). Light settings for a quick end-to-end smoke.
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text"
|
||||
name = "v1"
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
taskset = { id = "reverse-text-v1" }
|
||||
# reverse-text is a pure-text single-turn env: disable the bash tool (the model answers
|
||||
# directly) and use the subprocess runtime (no docker).
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
|
||||
# No eval block, mirroring examples/reverse_text/rl.toml — this is a train-only
|
||||
# smoke. Add an [orchestrator.eval] block (with an interval) to exercise eval.
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -0,0 +1,118 @@
|
||||
# v1 RL run: Qwen3.6-35B-A3B (MoE) on the v1 `scaleswe-v1` SWE taskset, rlm harness on a prime
|
||||
# sandbox runtime. Each scaleswe row ships its own Docker image (NEEDS_CONTAINER) which the
|
||||
# Environment injects into the prime sandbox; the agent edits the repo + runs tests there (no MCP
|
||||
# toolset). Router replay is enabled: trainer.enable_router_replay replays the routed-expert
|
||||
# decisions returned by inference (enable_return_routed_experts).
|
||||
#
|
||||
# Built from configs/debug/v1/r2e_gym.toml (the v1 SWE structure) + the MoE parallelism from
|
||||
# configs/general_agent/rl_qwen3_30b_a3b.toml. The deployment/parallelism is a starting point off
|
||||
# the 30B-A3B reference — confirm/adjust for your cluster and the 35B / 65k-context footprint.
|
||||
|
||||
max_steps = 400
|
||||
seq_len = 65536
|
||||
|
||||
[slurm]
|
||||
job_name = "scaleswe-qwen36-35b-a3b-rlm"
|
||||
project_dir = "."
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (label == SLURM job name).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "$SLURM_JOB_NAME" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 2
|
||||
|
||||
[wandb]
|
||||
project = "scaleswe-debug"
|
||||
name = "qwen36-35b-a3b-rlm"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3.6-35B-A3B"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
# NCCL collective watchdog timeout — raised from default 600s: scaleswe's slow
|
||||
# multi-node startup (step-0 swebench eval + slow first SWE batch) was tripping the
|
||||
# 600s _ALLGATHER_BASE watchdog → SIGABRT trainer crash.
|
||||
dist_timeout_seconds = 3600
|
||||
# Replay the routed-expert decisions returned by inference (enable_return_routed_experts)
|
||||
# so the trainer's MoE routing matches the rollout's — cuts trainer/inference mismatch on A3B.
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
cp = 2
|
||||
# Qwen3.6 is a hybrid/linear-attention model — ring CP is unsupported; ulysses
|
||||
# all-to-all on Q/K/V works with the non-softmax kernels.
|
||||
cp_style = "ulysses"
|
||||
# Chunk the LM head over tokens to avoid materializing the full [seq, vocab] logits
|
||||
# (65k seq × large vocab) — big activation-memory saver. 1024 matches the SWE configs.
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3.6"
|
||||
enable_thinking = true
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 1.0
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "scaleswe"
|
||||
# v1 scaleswe SWE taskset; rlm harness in a prime sandbox using the row's injected Docker image.
|
||||
taskset = { id = "scaleswe-v1" }
|
||||
harness = { id = "rlm", runtime = { type = "prime", labels = ["scaleswe-qwen36-35b-a3b-rlm"] } }
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Eval: SWE-Bench Verified (first 100 tasks) every 20 steps, rlm harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "swebench-verified"
|
||||
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
|
||||
harness = { id = "rlm", runtime = { type = "prime", labels = ["scaleswe-qwen36-35b-a3b-rlm"] } }
|
||||
num_examples = 100
|
||||
group_size = 1
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
enable_prefix_caching = true
|
||||
# Return per-token routed-expert decisions to the trainer for router replay
|
||||
# (pairs with trainer.enable_router_replay).
|
||||
enable_return_routed_experts = true
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 65536
|
||||
# Qwen3.6 is not matched by the auto tool-parser resolver; set explicitly so vLLM
|
||||
# enables auto tool choice (the scaleswe SWE agent sends tool_choice="auto").
|
||||
tool_call_parser = "qwen3_coder"
|
||||
|
||||
[inference.parallel]
|
||||
dp = 2
|
||||
tp = 4
|
||||
@@ -1,167 +0,0 @@
|
||||
# DeepScaler
|
||||
|
||||
This is a reproduction of the [DeepScaleR](https://pretty-radio-b75.notion.site/DeepScaleR-Surpassing-O1-Preview-with-a-1-5B-Model-by-Scaling-RL-19681902c1468005bed8ca303013a4e2) experiments. They use RL to train from `Deepseek-R1-Distill-Qwen-1.5B` to 43.1% on AIME2024, surpassing OpenAI’s o1-preview with just 1.5B parameters.
|
||||
|
||||
## Setup
|
||||
|
||||
Install the environment using the `prime` CLI.
|
||||
|
||||
```bash
|
||||
prime env install primeintellect/deepscaler
|
||||
```
|
||||
|
||||
Verify that the environment is installed correctly.
|
||||
|
||||
```bash
|
||||
uv run python -c "import deepscaler"
|
||||
```
|
||||
|
||||
## Training
|
||||
|
||||
A key insight from the paper is that they train in **stages of increasing context length**. In stages 1, 2 and 3, they train with context lengths of 8192, 16384 and 24576 tokens, respectively. We match their training setup here.
|
||||
|
||||
### Stage 1
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh -s stage1 -o outputs/stage1
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
uv run rl @ configs/deepscaler/stage1.toml \
|
||||
--output-dir outputs/stage1
|
||||
```
|
||||
|
||||
### Stage 2
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh -s stage2 -o outputs/stage2
|
||||
```
|
||||
|
||||
```bash
|
||||
mkdir -p outputs/stage2/checkpoints
|
||||
ln -s outputs/stage1/checkpoints/step_500 outputs/stage2/checkpoints/step_500
|
||||
mkdir -p outputs/stage2/weights
|
||||
ln -s outputs/stage1/weights/step_500 outputs/stage2/weights/step_500
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
uv run rl @ configs/deepscaler/stage2.toml \
|
||||
--output-dir outputs/stage2
|
||||
```
|
||||
|
||||
### Stage 3
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh -s stage3 -o outputs/stage3
|
||||
```
|
||||
|
||||
```bash
|
||||
mkdir -p outputs/stage3/checkpoints
|
||||
ln -s outputs/stage2/checkpoints/step_1000 outputs/stage3/checkpoints/step_1000
|
||||
mkdir -p outputs/stage3/weights
|
||||
ln -s outputs/stage2/weights/step_1000 outputs/stage3/weights/step_1000
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
uv run rl @ configs/deepscaler/stage3.toml \
|
||||
--output-dir outputs/stage3
|
||||
```
|
||||
|
||||
## Evals
|
||||
|
||||
They evaluate on a series of math benchmarks, including Math500, AIME24, AMC23, Minerva Math and Olympiad Math. We will focus on `math500` and `aime2024` for the reproduction, as these are already implemented as evaluation environments on the Environment Hub and also the most prominent benchmarks. We uploaded the weight checkpoints to HF as `DeepSeek-R1-Distill-Qwen-1.5B-DeepScaleR-XXX` and evaluate the base model and each checkpoint.
|
||||
|
||||

|
||||
|
||||
| Model | AIME 2024 | MATH 500 |
|
||||
|-------|-----------|----------|
|
||||
| DeepSeek-R1-Distill-Qwen-1.5B | 27.3% (16389±10200) | 81.4% (5450±7327) |
|
||||
| DeepScaleR-100 | 30.8% (14510±9591) | 83.4% (4694±6311) |
|
||||
| DeepScaleR-200 | 28.3% (11929±8630) | 83.2% (3610±4774) |
|
||||
| DeepScaleR-300 | 30.6% (9898±7050) | 84.2% (3270±4027) |
|
||||
| DeepScaleR-400 | 30.6% (9726±7077) | 83.6% (3283±4024) |
|
||||
| DeepScaleR-500 | 33.1% (9686±6563) | 84.0% (3081±3438) |
|
||||
| DeepScaleR-600 | 32.7% (9726±6222) | 86.6% (3205±3167) |
|
||||
| DeepScaleR-700 | 32.5% (10162±5887) | 87.8% (3569±3953) |
|
||||
| DeepScaleR-800 | 33.8% (10666±6032) | 85.4% (3835±3727) |
|
||||
| DeepScaleR-900 | 28.3% (13375±6546) | 80.8% (5480±5887) |
|
||||
| O1-Preview | 40.0% (N/A) | 81.4% (N/A) |
|
||||
|
||||
Start the inference server
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run this in the `Inference` pane
|
||||
uv run inference --model.name ... --max-model-len 32768
|
||||
```
|
||||
|
||||
*Note: The model checkpoints are uploaded to `mikasenghaas/DeepSeek-R1-Distill-Qwen-1.5B-DeepScaleR-XXX`.*
|
||||
|
||||
```bash
|
||||
uv run eval @ configs/deepscaler/eval.toml --model.name ...
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Raw results</summary>
|
||||
<pre><code>
|
||||
Base Model
|
||||
Evaluated math500 in 1547.25s (Avg@1=0.8140, Pass@1: 0.8140, Completion Length: 5450.29 (±7327.93, ∈[266.00, 32734.00]), Truncated: 3.8%)
|
||||
Evaluated aime2024 in 1546.06s (Avg@16=0.2729, Pass@8: 0.6130, Completion Length: 16389.57 (±10200.73, ∈[1643.00, 32699.00]), Truncated: 15.2%)
|
||||
|
||||
Step 100 (Stage 1)
|
||||
Evaluated math500 in 1280.38s (Avg@1=0.8340, Pass@1: 0.8340, Completion Length: 4694.13 (±6311.37, ∈[225.00, 32729.00]), Truncated: 2.2%)
|
||||
Evaluated aime2024 in 1279.09s (Avg@16=0.3083, Pass@8: 0.6363, Completion Length: 14510.24 (±9591.44, ∈[1606.00, 32696.00]), Truncated: 10.4%)
|
||||
|
||||
Step 200 (Stage 1)
|
||||
Evaluated math500 in 942.63s (Avg@1=0.8320, Pass@1: 0.8320, Completion Length: 3610.20 (±4774.83, ∈[404.00, 32649.00]), Truncated: 0.8%)
|
||||
Evaluated aime2024 in 942.34s (Avg@16=0.2833, Pass@8: 0.6043, Completion Length: 11929.71 (±8630.59, ∈[1770.00, 32701.00]), Truncated: 6.7%)
|
||||
|
||||
Step 300 (Stage 1)
|
||||
Evaluated math500 in 737.77s (Avg@1=0.8420, Pass@1: 0.8420, Completion Length: 3270.25 (±4027.97, ∈[415.00, 32732.00]), Truncated: 0.4%)
|
||||
Evaluated aime2024 in 736.54s (Avg@16=0.3063, Pass@8: 0.6350, Completion Length: 9898.05 (±7050.03, ∈[1606.00, 32696.00]), Truncated: 3.5%)
|
||||
|
||||
Step 400 (Stage 1)
|
||||
Evaluated math500 in 727.78s (Avg@1=0.8360, Pass@1: 0.8360, Completion Length: 3283.45 (±4024.46, ∈[282.00, 32721.00]), Truncated: 0.4%)
|
||||
Evaluated aime2024 in 726.83s (Avg@16=0.3063, Pass@8: 0.6567, Completion Length: 9726.12 (±7077.99, ∈[1266.00, 32686.00]), Truncated: 3.3%)
|
||||
|
||||
Step 500 (Stage 1)
|
||||
Evaluated math500 in 660.66s (Avg@1=0.8540, Pass@1: 0.8540, Completion Length: 2961.01 (±3426.75, ∈[543.00, 32695.00]), Truncated: 0.6%)
|
||||
Evaluated aime2024 in 658.95s (Avg@16=0.3000, Pass@8: 0.6460, Completion Length: 9121.69 (±6423.23, ∈[1323.00, 32687.00]), Truncated: 3.1%)
|
||||
|
||||
Step 500 (Stage 2)
|
||||
Evaluated math500 in 370.32s (Avg@1=0.8400, Pass@1: 0.8400, Completion Length: 3081.88 (±3438.49, ∈[614.00, 32709.00]), Truncated: 0.4%)
|
||||
Evaluated aime2024 in 368.68s (Avg@16=0.3312, Pass@8: 0.6287, Completion Length: 9686.62 (±6563.93, ∈[1140.00, 32686.00]), Truncated: 2.5%)
|
||||
|
||||
Step 600 (Stage 2)
|
||||
Evaluated math500 in 334.98s (Avg@1=0.8660, Pass@1: 0.8660, Completion Length: 3205.39 (±3167.25, ∈[554.00, 22164.00]), Truncated: 0.0%)
|
||||
Evaluated aime2024 in 354.83s (Avg@16=0.3271, Pass@8: 0.6353, Completion Length: 9726.84 (±6222.77, ∈[1162.00, 32683.00]), Truncated: 1.9%)
|
||||
|
||||
Step 700 (Stage 2)
|
||||
Evaluated math500 in 377.43s (Avg@1=0.8780, Pass@1: 0.8780, Completion Length: 3569.39 (±3953.57, ∈[618.00, 32611.00]), Truncated: 0.4%)
|
||||
Evaluated aime2024 in 375.57s (Avg@16=0.3250, Pass@8: 0.6550, Completion Length: 10162.39 (±5887.47, ∈[1428.00, 32672.00]), Truncated: 1.5%)
|
||||
|
||||
Step 800 (Stage 2)
|
||||
Evaluated math500 in 400.01s (Avg@1=0.8540, Pass@1: 0.8540, Completion Length: 3835.00 (±3727.86, ∈[563.00, 23701.00]), Truncated: 0.0%)
|
||||
Evaluated aime2024 in 398.19s (Avg@16=0.3375, Pass@8: 0.6860, Completion Length: 10666.42 (±6032.30, ∈[1898.00, 32686.00]), Truncated: 1.0%)
|
||||
|
||||
Step 850 (Stage 2)
|
||||
Evaluated math500 in 445.40s (Avg@1=0.8640, Pass@1: 0.8640, Completion Length: 4216.45 (±4022.84, ∈[611.00, 23277.00]), Truncated: 0.0%)
|
||||
Evaluated aime2024 in 446.29s (Avg@16=0.3250, Pass@8: 0.6350, Completion Length: 11313.77 (±5997.51, ∈[1695.00, 32686.00]), Truncated: 1.9%)
|
||||
|
||||
Step 900 (Stage 2)
|
||||
Evaluated math500 in 564.56s (Avg@1=0.8080, Pass@1: 0.8080, Completion Length: 5480.47 (±5887.06, ∈[662.00, 32729.00]), Truncated: 1.8%)
|
||||
SUCCESS Evaluated aime2024 in 562.67s (Avg@16=0.2833, Pass@8: 0.6003, Completion Length: 13375.38 (±6546.80, ∈[1706.00, 32687.00]), Truncated: 4.0%)
|
||||
|
||||
Step 950 (Stage 3)
|
||||
Evaluated math500 in 755.59s (Avg@1=0.7200, Pass@1: 0.7200, Completion Length: 8146.41 (±7986.20, ∈[748.00, 32736.00]), Truncated: 4.6%)
|
||||
Evaluated aime2024 in 751.49s (Avg@16=0.1833, Pass@8: 0.4207, Completion Length: 16031.10 (±6904.70, ∈[2366.00, 32699.00]), Truncated: 4.8%)
|
||||
</code>
|
||||
</pre>
|
||||
</details>
|
||||
<br/>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 126 KiB |
@@ -1,39 +0,0 @@
|
||||
max_steps = 500
|
||||
seq_len = 8192
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[wandb]
|
||||
project = "deepscaler"
|
||||
name = "stage1"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 1024
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "deepscaler"
|
||||
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
@@ -1,40 +0,0 @@
|
||||
max_steps = 1000
|
||||
seq_len = 16384
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[wandb]
|
||||
project = "deepscaler"
|
||||
name = "stage2"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
resume_step = 500
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 1024
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_completion_tokens = 16384
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "deepscaler"
|
||||
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
@@ -1,40 +0,0 @@
|
||||
max_steps = 1500
|
||||
seq_len = 24576
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[wandb]
|
||||
project = "deepscaler"
|
||||
name = "stage3"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
resume_step = 1000
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 1024
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_completion_tokens = 24576
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "deepscaler"
|
||||
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
@@ -8,7 +8,7 @@ To test the elastic inference pool without having the `rl` entrypoint start the
|
||||
uv run rl @ examples/alphabet_sort/rl_elastic.toml
|
||||
```
|
||||
|
||||
The config uses `[orchestrator.client.elastic]` with `hostname = "localhost"` and `port = 8000`. The orchestrator will wait for at least one ready server before starting rollouts.
|
||||
The config uses `[orchestrator.model.client.elastic]` with `hostname = "localhost"` and `port = 8000`. The orchestrator will wait for at least one ready server before starting rollouts.
|
||||
|
||||
2. **Start the inference server manually** (in a separate terminal or on another machine):
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ group_size = 8
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[orchestrator.client.elastic]
|
||||
[orchestrator.model.client.elastic]
|
||||
hostname = "localhost"
|
||||
port = 8000
|
||||
sync_interval = 5.0
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
# math-python
|
||||
|
||||
## Setup
|
||||
|
||||
Install the environment as local packages
|
||||
|
||||
```bash
|
||||
uv pip install -e ~/research-environments/environments/math_env
|
||||
uv pip install -e ~/research-environments/environments/code_env
|
||||
uv pip install -e ~/research-environments/environments/science_env
|
||||
uv pip install -e ~/research-environments/environments/logic_env
|
||||
```
|
||||
|
||||
## RL
|
||||
|
||||
```bash
|
||||
uv run --no-sync rl @ configs/env_mix/env_mix.toml --log.level debug
|
||||
```
|
||||
@@ -1,52 +0,0 @@
|
||||
max_steps = 300
|
||||
seq_len = 8192
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[wandb]
|
||||
project = "env-mix-debug"
|
||||
name = "env-mix"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 16
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "math"
|
||||
args = { min_avg_reward = 0.1, rubric_max_workers = 128 }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "code-env"
|
||||
name = "code"
|
||||
args = { min_avg_reward = 0.1 }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "science-env"
|
||||
name = "science"
|
||||
args = { min_avg_reward = 0.1, pool_size = 128, rubric_max_workers = 128 }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "logic-env"
|
||||
name = "logic"
|
||||
args = { min_avg_reward = 0.1 }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "math-python"
|
||||
args = { min_avg_reward = 0.1, sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox_memory_gb = 1, sandbox_disk_size_gb = 1, pip_install_packages = "numpy sympy", python_tool = true, rubric_max_workers = 128 }
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference]
|
||||
api_server_count = 8
|
||||
gpu_memory_utilization = 0.8
|
||||
|
||||
[inference.model]
|
||||
tool_call_parser = "hermes"
|
||||
max_model_len = 8192
|
||||
@@ -0,0 +1,50 @@
|
||||
# GLM-5.2-FP8 16-node P/D, FULL STACK: mooncake + llm-d router, vLLM 0.23.
|
||||
# Step 3 / goal target. Topology mirrors the proven original glm5.1_llmd_inference
|
||||
# (job 348 succeeded): 8 prefill nodes (4 replicas x 2) + 8 decode nodes (1 replica).
|
||||
#
|
||||
# Launch: uv run inference @ configs/glm5.2_16node_llmd/inference.toml
|
||||
|
||||
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"
|
||||
|
||||
[kv_cache_offload.cpu]
|
||||
num_bytes = 1_000_000_000_000
|
||||
|
||||
[deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 8
|
||||
num_prefill_replicas = 4
|
||||
num_decode_nodes = 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.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
|
||||
|
||||
[slurm]
|
||||
job_name = "glm5.2-16node-llmd"
|
||||
partition = "all"
|
||||
@@ -25,7 +25,7 @@ args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max
|
||||
[inference] # Default inference config
|
||||
|
||||
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
|
||||
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
|
||||
# <think> blocks. Match that with renderer thinking_retention.
|
||||
[orchestrator.renderer]
|
||||
name = "auto"
|
||||
preserve_all_thinking = true
|
||||
thinking_retention = "all"
|
||||
|
||||
@@ -27,7 +27,8 @@ interval = 10
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
name = "math500"
|
||||
taskset = { id = "math500-v1" }
|
||||
num_examples = 30
|
||||
group_size = 4
|
||||
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
max_steps = 500
|
||||
|
||||
[wandb]
|
||||
project = "math-group-debug"
|
||||
name = "math-group"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
ratio = 0.5
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "acereason-math"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem" }
|
||||
ratio = 0.5
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2024"
|
||||
name = "aime2024"
|
||||
num_examples = 30
|
||||
group_size = 4
|
||||
|
||||
[trainer.model]
|
||||
seq_len = 4096
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 2048
|
||||
|
||||
|
||||
@@ -62,7 +62,8 @@ interval = 10
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
name = "math500"
|
||||
taskset = { id = "math500-v1" }
|
||||
num_examples = 30
|
||||
group_size = 4
|
||||
|
||||
|
||||
@@ -61,7 +61,8 @@ interval = 10
|
||||
max_completion_tokens = 4096
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
name = "math500"
|
||||
taskset = { id = "math500-v1" }
|
||||
num_examples = 30
|
||||
group_size = 4
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# Wordle (classic v0 TextArena env) on 2 GPUs (1 trainer + 1 inference), run via the
|
||||
# legacy bridge. The Wordle-SFT model plays a full ~6-turn game per rollout; the bridge
|
||||
# serves each multi-turn rollout to the orchestrator as a vf.Trace.
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 8192
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[wandb]
|
||||
project = "wordle"
|
||||
name = "wordle"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wordle"
|
||||
name = "wordle"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
[inference] # single inference GPU (no data parallelism)
|
||||
|
||||
# Qwen3 finetune with the standard PI template patch (byte-identical to
|
||||
# PrimeIntellect/Qwen3-0.6B base); always re-emits prior <think> blocks.
|
||||
# Match that with renderer thinking_retention.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
thinking_retention = "all"
|
||||
Vendored
+1
-1
Submodule deps/pydantic-config updated: 896ade4e69...99f47c6cc0
Vendored
+1
-1
Submodule deps/renderers updated: e6dba5ad6c...a5efbb97e4
Vendored
+1
-1
Submodule deps/research-environments updated: 4c08260f07...bae0ffe5ae
Vendored
+1
-1
Submodule deps/verifiers updated: 0ad8b4d523...62ba2212df
+7
-3
@@ -25,7 +25,7 @@ impl = "custom" # or "hf" to force the HF path
|
||||
|
||||
| Family | HF config types | EP | CP |
|
||||
|---|---|---|---|
|
||||
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | ✅ | ✅ |
|
||||
| GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ |
|
||||
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
|
||||
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
|
||||
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
|
||||
@@ -38,6 +38,8 @@ impl = "custom" # or "hf" to force the HF path
|
||||
|
||||
The custom path enables you to set EP, CP, selective activation checkpointing, FP8 training (`model.fp8 = true`, requires SM90+), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
|
||||
|
||||
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
|
||||
|
||||
### Expert Parallelism Backends
|
||||
|
||||
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
|
||||
@@ -137,9 +139,11 @@ curl -s http://<decode_node>:8200/metrics | grep num_requests_waiting
|
||||
|
||||
If prefill queues and decode is idle, add prefill nodes (and vice versa).
|
||||
|
||||
**UCX 1.19 requirement.** NVSHMEM needs UCX ≥ 1.19 for multi-GPU CUDA. If your cluster doesn't ship with UCX >=1.19, you can build it from source with the following command:
|
||||
**Required setup for disaggregated P/D (NIXL/UCX).** The pip-wheel NIXL's bundled UCX segfaults on the prefill→decode KV transfer (`signal 11: invalid permissions for mapped object` in `libucs.so`) — reproduced on vLLM 0.22 and 0.23, with/without mooncake, with/without llm-d. Building NIXL against UCX 1.19.x from source is therefore **required** (not optional) for disaggregated P/D.
|
||||
|
||||
```bash
|
||||
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
|
||||
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
|
||||
```
|
||||
|
||||
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version.
|
||||
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel.
|
||||
+203
-94
@@ -1,25 +1,151 @@
|
||||
# Algorithms
|
||||
|
||||
This page covers the math and the configurable algorithmic components: how off-policy training works, the default loss and advantage functions, how to plug in your own, the filters applied between rollout and training, and how multi-turn rollouts get merged into training samples.
|
||||
This page covers the math and the configurable algorithmic components: the algorithm abstraction and its algorithms, how off-policy training works, the loss components and advantage functions, how to plug in your own, the filters applied between rollout and training, and how multi-turn rollouts get merged into training samples.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [The Algorithm Abstraction](#the-algorithm-abstraction)
|
||||
- [Model References](#model-references)
|
||||
- [The Algorithms](#the-algorithms)
|
||||
- [Customizing Components](#customizing-components)
|
||||
- [Per-Env Algorithms](#per-env-algorithms)
|
||||
- [The Algorithm Classes](#the-algorithm-classes)
|
||||
- [Async / Off-Policy Training](#async--off-policy-training)
|
||||
- [Loss](#loss)
|
||||
- [Default Loss](#default-loss)
|
||||
- [Loss Components](#loss-components)
|
||||
- [Default RL Loss](#default-rl-loss)
|
||||
- [Custom Loss](#custom-loss)
|
||||
- [Advantage](#advantage)
|
||||
- [Default Advantage](#default-advantage)
|
||||
- [Custom Advantage](#custom-advantage)
|
||||
- [Authoring an Algorithm](#authoring-an-algorithm)
|
||||
- [Reference Scoring](#reference-scoring)
|
||||
- [Filters](#filters)
|
||||
- [Difficulty Pools](#difficulty-pools)
|
||||
- [Online Difficulty Filtering](#online-difficulty-filtering)
|
||||
- [Multi-Turn Trajectories](#multi-turn-trajectories)
|
||||
- [Extension Property](#extension-property)
|
||||
- [Best-Effort Interleaving](#best-effort-interleaving)
|
||||
- [Renderers](#renderers)
|
||||
- [Discontinuous Trajectories](#discontinuous-trajectories)
|
||||
|
||||
## The Algorithm Abstraction
|
||||
|
||||
A training algorithm in `prime-rl` is configured under `[orchestrator.algo]`, where **`type` names the algorithm** (`grpo`, `opd`, `sft`, …) and the class defaults are its vetted setting. It has two parts:
|
||||
|
||||
1. **Sampling** (`algo.sampling`) — how train rollouts are produced: which model generates them. `source` is a [model reference](#model-references): `"policy"` (the live policy, the default) or an inline frozen hosted model. Group sizing stays on the env config (`group_size`).
|
||||
2. **The per-token training signal** — credit assignment and loss routing, fused; the algorithm's own parameters sit directly on `algo`. One mapping from a finalized rollout to per-token *(loss component, weight)* pairs — the credit a token gets and the loss that consumes it are two coordinates of the same output. Group-relative algorithms compute credit on the orchestrator and ship per-token advantage streams; reference-KL algorithms query a reference model at batch-ship time (bounded concurrency) and ship its prefill logprobs for the trainer to evaluate against the live policy. The `type` determines which loss component consumes the action tokens (`rl` / `ce` / `ref_kl`) and what happens to env-provided observation tokens in multi-turn rollouts (masked out by default; `echo` trains on them with weighted CE).
|
||||
|
||||
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, packer, or trainer hot path.
|
||||
|
||||
### Model References
|
||||
|
||||
`prime-rl` hosts exactly one model: the trainable policy (`[orchestrator.model]`). Every other model an algorithm uses is an external OpenAI-compatible endpoint, declared *inline on the component that uses it*. A model reference is either the string `"policy"` (the live policy) or a frozen hosted model (`name` + `base_url`):
|
||||
|
||||
```toml
|
||||
[orchestrator.algo]
|
||||
type = "opd"
|
||||
|
||||
[orchestrator.algo.teacher] # opd's teacher: the frozen model it scores against
|
||||
name = "Qwen/Qwen3-32B"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
```
|
||||
|
||||
Model *roles* are algorithm-local vocabulary — each algorithm names its reference on the field where the model is actually used, and there is no shared `teacher` slot. `opd` declares a `teacher` field (the frozen model whose reverse KL the policy distills toward); `sft`'s teacher *is* its `sampling.source` (the frozen model it imitates); `opsd` self-distills against the live policy and names no model at all. No role exists outside the algorithm that declares it: the dispatcher, sink, and trainer branch on liveness alone, never on what an algorithm calls a model.
|
||||
|
||||
So for `opd` set `[orchestrator.algo.teacher]`; for `sft` set `[orchestrator.algo.sampling.source]`; `opsd` needs neither. `opd`'s teacher must be a frozen endpoint — it is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero); `opsd`'s teacher *is* the live policy by definition (self-distillation conditioned on a demonstration), so it exposes no reference to configure.
|
||||
|
||||
Liveness is a property of the reference, not of any role: rollouts sampled from `"policy"` get version-salted prefix caches, carry sampling logprobs for importance ratios, and age off-policy as weights update; rollouts and scores from frozen models get a stable prefix cache and never go stale. Frozen models are externally hosted (`base_url` is required) — `prime-rl` never launches or updates them, and each env's algorithm builds its own client pool to the endpoints it declares.
|
||||
|
||||
### The Algorithms
|
||||
|
||||
The `algo.type` names the algorithm, and each type's class defaults are its vetted setting — picking a type with no other keys IS the algorithm:
|
||||
|
||||
```toml
|
||||
[orchestrator.algo]
|
||||
type = "grpo" # the default
|
||||
```
|
||||
|
||||
| `type` | Sampling | Loss | What it is |
|
||||
|---|---|---|---|
|
||||
| `grpo` | policy | `rl` on actions | Standard group-relative RL. |
|
||||
| `max_rl` | policy | `rl` on actions | MaxRL ([arXiv:2602.02710](https://arxiv.org/abs/2602.02710)): GRPO's centered reward normalized by the group **mean** instead of the standard deviation — the gradient is unbiased for the order-`group_size` truncation of the maximum-likelihood objective, upweighting hard examples like `1/p`. |
|
||||
| `opd` | policy | `ref_kl` on actions | On-policy distillation ([Thinking Machines](https://thinkingmachines.ai/blog/on-policy-distillation/)): the policy samples, per-token reverse KL against a reference model as the gradient signal. Needs a `teacher`. |
|
||||
| `sft` | *(the teacher)* | `ce` on actions | Hard distillation: a frozen model generates rollouts, the policy trains with CE on its tokens. Needs a frozen `sampling.source` (the teacher it samples from). |
|
||||
| `opsd` | policy | `ref_kl` on actions | SDFT ([arXiv:2601.19897](https://arxiv.org/abs/2601.19897)): the model is its own reference, conditioned on an expert demonstration. The teacher *is* the live policy (the paper's setting, no extra deployment) — no model to configure. |
|
||||
| `echo` | policy | `rl` on actions + weighted `ce` on observations | ECHO: standard GRPO plus a cross-entropy loss on env-provided tokens already present in the rollout, selected by message role (needs the renderer's role attribution). Defaults to tool-response bodies at `alpha = 0.1` (ECHO's λ); set `roles` to train other roles, each at its own weight. |
|
||||
|
||||
### Customizing Components
|
||||
|
||||
Every key beyond `type` is visibly your own assembly — there is no preset layer to diverge from. The vetted setting is the class defaults; what you set is what runs:
|
||||
|
||||
```toml
|
||||
# echo on tool AND user feedback tokens, each at its own weight.
|
||||
# Setting any role replaces the whole table.
|
||||
[orchestrator.algo]
|
||||
type = "echo"
|
||||
|
||||
[orchestrator.algo.roles.tool]
|
||||
alpha = 0.25
|
||||
|
||||
[orchestrator.algo.roles.user]
|
||||
alpha = 0.05
|
||||
```
|
||||
|
||||
A new algorithm is a named class in code, not a config that points at an import path — see [Authoring an Algorithm](#authoring-an-algorithm).
|
||||
|
||||
Echo also takes an optional user-supplied token filter that narrows the role selection per rollout — e.g. dropping warning lines from tool output, or tokens the sampler found unlikely:
|
||||
|
||||
```toml
|
||||
[orchestrator.algo.filter]
|
||||
import_path = "my_module.drop_warnings"
|
||||
kwargs = { patterns = ["WARNING"] }
|
||||
```
|
||||
|
||||
```python
|
||||
# my_module.py — sees the raw rollout (message text, sampling logprobs);
|
||||
# returns one keep-mask per trainable branch, spanning that branch's
|
||||
# token_ids. False = never echo-trained.
|
||||
def drop_warnings(rollout, *, patterns: list[str]) -> list[list[bool]]: ...
|
||||
```
|
||||
|
||||
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and aborts after repeated zero-trainable batches), not at config time.
|
||||
|
||||
### Per-Env Algorithms
|
||||
|
||||
Both components resolve per environment. Each env inherits `[orchestrator.algo]` unless it sets its own, so a single run can mix algorithms across envs — e.g. GRPO on math, ECHO on a terminal env:
|
||||
|
||||
```toml
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env" # inherits grpo
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "terminal-env"
|
||||
algo = { type = "echo" } # this env runs its own algorithm
|
||||
```
|
||||
|
||||
### The Algorithm Classes
|
||||
|
||||
At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_rl.orchestrator.sampler`) from the `sampling` component — the pool rollouts are generated from, and the home of future sampling strategies like replay buffers or branching — and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
|
||||
|
||||
| `algo.type` | Class | hook(s) — stage |
|
||||
|---|---|---|
|
||||
| `grpo` | `GRPOAlgorithm` | `score_group`: group-norm credit (optional length penalty) |
|
||||
| `echo` | `EchoAlgorithm` | `score_rollout`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
|
||||
| `max_rl` | `MaxRLAlgorithm` | `score_group`: mean-normalized group credit |
|
||||
| `opd` | `OPDAlgorithm` | `score_rollout`: own-context prefill under the teacher |
|
||||
| `opsd` | `OPSDAlgorithm` | `score_rollout`: demo-conditioned prefill under the live policy |
|
||||
| `sft` | `SFTDistillAlgorithm` | `score_group`: group-norm credit (feeds filters) |
|
||||
|
||||
Each class owns its hooks outright — reading one top to bottom reads the algorithm, and everything on the class is an override point. The two hooks are one scope-and-timing ladder — the wider scope is unlocked by a later barrier, so the two axes coincide. Each is handed the `Rollout` directly — the env's typed trace (`reward`, `nodes`, `num_turns`, ...) with `samples` attached, plus `assign_advantages` to write credit:
|
||||
|
||||
- `async score_rollout(rollout)` — one rollout, **on arrival** (as it's tokenized, before its group is complete): rollout-local credit (`rollout.assign_advantages(...)`, scalar broadcast or per-token), observation ce weights, **or** model I/O — query a reference pool (e.g. `self.teacher_pool`, connected in `setup()` via `self.connect(...)`, or the live `self.policy_pool` for opsd) and attach per-token results (e.g. teacher logprobs) with bounded concurrency. No siblings. `echo` weights observation tokens here, identifying env-provided observation nodes by their non-sampled status and source step role attribution, applying the optional user filter, and writing the `ce_weights` stream. Model I/O runs *before* the pre-batch filters, so it pays compute on rollouts that may then be filtered out.
|
||||
- `score_group(group)` — the cohort, **before filtering** (filters read the streams), synchronous: group-relative credit (GRPO/MaxRL baselines). `group` is a list of `Rollout`.
|
||||
|
||||
The pipeline drives the hooks through two non-virtual methods it never looks inside: `algorithm.finalize_rollout(rollout)` per arrival (rollout-local scoring + reference I/O) and `algorithm.finalize_group(rollouts)` per group (scoring + wire stamping; after this the records are frozen — groups die at stamping). Sample construction (interleaving) is pure pipeline — observation-token provenance is available through structural attribution (`node.sampled`, `node.is_content`) for any algorithm that trains on env-provided tokens.
|
||||
|
||||
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy pool (`self.policy_pool`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
|
||||
|
||||
## Async / Off-Policy Training
|
||||
|
||||
`prime-rl` is asynchronous by default. The trainer and inference always run one step overlapped: while the trainer is producing $\pi_n$ from rollouts at step $n$, inference is already generating the rollouts for step $n+1$ using $\pi_{n-1}$. With matched trainer and inference step times this produces fully-overlapped pipeline parallelism — neither side ever idles.
|
||||
@@ -35,7 +161,21 @@ Step indices are 0-indexed so the gap holds at startup — inference is exactly
|
||||
|
||||
## Loss
|
||||
|
||||
### Default Loss
|
||||
### Loss Components
|
||||
|
||||
The training loss is a **sum of three components**, each with its own per-token weight stream and its own normalization:
|
||||
|
||||
$$
|
||||
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
|
||||
$$
|
||||
|
||||
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the group-relative algorithms (`grpo`, `max_rl`, and `echo`'s action tokens).
|
||||
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
|
||||
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
|
||||
|
||||
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens, so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
|
||||
|
||||
### Default RL Loss
|
||||
|
||||
The default RL loss is a DPPO policy-gradient term combined with a KL regularizer similar to Kimi-K2.5. For each prompt $x_j$ we sample a group of $G$ rollouts $\{y_i\}_{i=1}^G$, score them to get $s_i$, then optimize:
|
||||
|
||||
@@ -66,20 +206,14 @@ The knobs (under `[trainer.loss]` with `type = "default"`):
|
||||
| Knob | Default | What it does |
|
||||
|---|---|---|
|
||||
| `dppo_mask_low` / `dppo_mask_high` | 0.2 / 0.2 | Lower / upper thresholds for DPPO-style token-level masking. |
|
||||
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 for pure distillation (no RL signal). |
|
||||
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
|
||||
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
|
||||
|
||||
The trainer dispatches automatically based on the batch's training mode (set by the orchestrator via `orchestrator.training_mode`):
|
||||
|
||||
- `rl` mode → DPPO + KL with the advantage signal.
|
||||
- `opd` mode → KL distillation against the teacher's per-token logprobs. The teacher must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
|
||||
- `sft` mode → standard token-level NLL on teacher-generated rollouts.
|
||||
|
||||
Set `[trainer.loss] type = "default"` and configure via the knobs above. SFT and OPD modes ignore the policy-gradient–specific fields.
|
||||
Set `[trainer.loss] type = "default"` and configure via the knobs above. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
|
||||
|
||||
### Custom Loss
|
||||
|
||||
The loss is computed **per sequence**: you write a function that takes one sequence's tensors and returns a scalar loss. The trainer iterates and aggregates.
|
||||
`[trainer.loss] type = "custom"` replaces the `rl` component. The loss is computed **per sequence**: you write a function that takes one sequence's tensors and returns a scalar loss. The trainer iterates and aggregates. `inputs.loss_mask` selects exactly the rl member tokens (for a plain GRPO run, all trainable tokens).
|
||||
|
||||
```python
|
||||
# my_module.py
|
||||
@@ -116,9 +250,10 @@ The dataclasses:
|
||||
class LossInputs:
|
||||
trainer_logprobs: Float[Tensor, "seq"] # current policy
|
||||
inference_logprobs: Float[Tensor, "seq"] # rollout-time policy
|
||||
teacher_logprobs: Float[Tensor, "seq"] | None # only set in OPD mode
|
||||
ref_logprobs: Float[Tensor, "seq"] | None # set by reference-scoring algorithms
|
||||
advantages: Float[Tensor, "seq"]
|
||||
loss_mask: Bool[Tensor, "seq"]
|
||||
loss_mask: Bool[Tensor, "seq"] # this component's member tokens
|
||||
loss_weights: Float[Tensor, "seq"] | None # the component's weight stream (None = 1.0)
|
||||
|
||||
@dataclass
|
||||
class LossOutputs:
|
||||
@@ -130,58 +265,71 @@ Anything you put in `metrics` is averaged across sequences and logged with the o
|
||||
|
||||
## Advantage
|
||||
|
||||
The per-token training signal is set by `algo.type` and the [algorithm](#the-algorithm-abstraction)'s parameters — every signal is a per-token advantage stream, varying in evaluation site (orchestrator vs. trainer). The `algo.type` values:
|
||||
|
||||
| Type | Component | Effect |
|
||||
|---|---|---|
|
||||
| `grpo` | `rl` | Group-norm: reward minus per-group baseline, optional length penalty. |
|
||||
| `max_rl` | `rl` | Mean-normalized group credit (maximum-likelihood RL). |
|
||||
| `echo` | `rl` + `ce` | Group-norm on action tokens, plus weighted CE on env-provided tokens selected by message role (each role's `alpha` is its ECHO λ), optionally narrowed by a user filter. |
|
||||
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`model`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream; `group_size` only fans out sampling. |
|
||||
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream. |
|
||||
| `sft` | `ce` | Cross-entropy on the sampled tokens. Assigns no advantage — trains on every sampled token. |
|
||||
|
||||
### Default Advantage
|
||||
|
||||
The default advantage is per-group reward minus per-group baseline (DR-GRPO without std normalization). For each prompt's group of `group_size` rollouts, every token in rollout $i$ receives advantage $s_i - \bar{s}$ where $\bar{s}$ is the group mean.
|
||||
|
||||
This is intentionally simple — it does the right thing for most envs. Switch to a [custom advantage](#custom-advantage) when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …).
|
||||
This is intentionally simple — it does the right thing for most envs. Write a named algorithm class when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …) — see [Authoring an Algorithm](#authoring-an-algorithm).
|
||||
|
||||
Two built-in **length penalties** can be layered on top of any advantage to discourage rambling:
|
||||
A **length penalty** (`length_penalty` on the `grpo`-family algorithms) can be layered on top to discourage rambling. The `linear` penalty subtracts a single `pass_rate`-scaled penalty from each reward before the GRPO baseline, combining output tokens (`num_output_tokens_weight`), input / context tokens (`num_input_tokens_weight`), and turns (`num_turns_weight`) — each normalized by the group's own max for that quantity, with `num_input_tokens_weight` and `num_turns_weight` defaulting to `0.1`.
|
||||
|
||||
- `[orchestrator.length_penalty] type = "tokens"` — penalizes long completions in tokens, with configurable target and slope.
|
||||
- `[orchestrator.length_penalty] type = "turns"` — penalizes long multi-turn rollouts by turn count.
|
||||
```toml
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "linear"
|
||||
```
|
||||
|
||||
|
||||
### Custom Advantage
|
||||
### Authoring an Algorithm
|
||||
|
||||
Advantages are computed **per group**. You write a function that takes one group of rollouts and returns one advantage scalar per rollout. The orchestrator handles groups of varying size automatically — partial-group training kicks in when some rollouts in a group errored.
|
||||
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class. The hook receives the group's `Rollout`s (each the env's typed `verifiers.Trace` — turns, tool calls, metadata in `info` — with `samples` attached) and writes credit via `assign_advantages`:
|
||||
|
||||
```python
|
||||
# my_module.py
|
||||
import statistics
|
||||
from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
|
||||
# src/prime_rl/orchestrator/algo/my_algo.py
|
||||
import torch
|
||||
|
||||
def normalized_advantage(inputs: AdvantageInputs, eps: float = 1e-8) -> AdvantageOutputs:
|
||||
rewards = [r["reward"] for r in inputs.rollouts]
|
||||
mean = statistics.fmean(rewards)
|
||||
std = statistics.pstdev(rewards) if len(rewards) > 1 else 0.0
|
||||
return AdvantageOutputs(advantages=[(r - mean) / (std + eps) for r in rewards])
|
||||
from prime_rl.orchestrator.algo.base import Algorithm
|
||||
|
||||
|
||||
class MyAlgorithm(Algorithm):
|
||||
async def score_group(self, group):
|
||||
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
|
||||
advantages = ... # one value per rollout
|
||||
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
|
||||
rollout.assign_advantages(advantage)
|
||||
```
|
||||
|
||||
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick the hook by *when* your signal is ready: `score_rollout` for per-arrival credit or credit that needs a model call (it's `async`), `score_group` for group-relative credit (GRPO/MaxRL). `assign_advantages` takes a scalar (broadcast over the rollout's trainable tokens — the common case) or a full-length per-token list aligned to the concatenated sample token_ids (process rewards, step-level credit; `0.0` off-mask).
|
||||
|
||||
Each per-token list must match the rollout's completion-token count exactly — validated loudly when the view writes it. Advantage-based filters and metrics derive from the streams (the zero-advantage filter checks for all-zero streams; logged distributions use per-rollout means). Signals that depend on the live policy's weights (like OPD's reverse KL) cannot be precomputed here; those are reference-scoring algorithms, evaluated in the trainer.
|
||||
|
||||
### Reference Scoring
|
||||
|
||||
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_rollout`: as each rollout arrives they query a reference (the sample's own context for `opd`, the demo-conditioned context for `opsd`) and attach per-token reference logprobs to each sample. Rollouts are consumed serially by the orchestrator's main loop and each carries only a handful of samples, so the in-flight request count is naturally bounded — no explicit concurrency cap:
|
||||
|
||||
- `opd` — score each sample's own context under the `teacher` (a frozen [model reference](#model-references)) via prefill; fills `ref_logprobs` for the `ref_kl` loss component (on-policy distillation). The `teacher` is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero).
|
||||
- `opsd` — SDFT: prepend an expert demonstration as a leading system message (`template`, with a `{demonstration}` placeholder) and score the sample under that demo-conditioned context. The sample is scored verbatim (`hint_block + token_ids`, slicing the hint's logprobs back off), so the join is BPE-clean and it's robust to tool/multimodal prompts and any number of turns. The scoring reference *is* the live policy — self-distillation names no teacher. opsd builds its own renderer to tokenize the hint block: the tokenizer is always the live policy's (not configurable — there is no separate model), and only the `renderer` family is settable (defaults to `"auto"`, resolved from the policy tokenizer; set it to match a non-auto policy renderer). The demonstration is read from the example's `info[demo_key]`, falling back to a top-level rollout field of the same name (e.g. `answer`).
|
||||
|
||||
```toml
|
||||
[orchestrator.advantage]
|
||||
type = "custom"
|
||||
import_path = "my_module.normalized_advantage"
|
||||
kwargs = { eps = 1e-8 }
|
||||
[orchestrator.algo]
|
||||
type = "opsd"
|
||||
demo_key = "demonstration"
|
||||
```
|
||||
|
||||
`AdvantageInputs.rollouts` is a list of `verifiers.RolloutOutput`, so you have access to the full rollout (turns, tool calls, custom metadata) — not just the reward. Use this for anything reward-shaping-like that needs trajectory context.
|
||||
|
||||
### Per-Env Advantage
|
||||
|
||||
`advantage` can be set per training environment. Each env inherits the top-level `[orchestrator.advantage]` when it doesn't set its own, so mixed-env runs can give each env its own advantage computation:
|
||||
|
||||
```toml
|
||||
[orchestrator.advantage]
|
||||
type = "default" # the default every env inherits unless it overrides
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env" # inherits the default above
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "agent-env"
|
||||
advantage = { type = "custom", import_path = "my_module.normalized_advantage" }
|
||||
```
|
||||
Scoring runs at arrival, *before* the pre-batch filters, so a rollout that is later filtered still cost its reference compute — accepted for the simpler one-rollout-at-a-time shape (advantage-based filters never fire for opd/opsd anyway, since neither assigns an advantage).
|
||||
|
||||
## Filters
|
||||
|
||||
@@ -193,58 +341,19 @@ Filters drop rollouts between scoring and training. Built-ins (composable):
|
||||
| `repetition` | Drops rollouts with high n-gram repetition. |
|
||||
| `zero_advantage` | Drops rollouts whose advantage is zero, so the trainer doesn't waste tokens on them. |
|
||||
|
||||
The default `[orchestrator]` config already includes all three filters with their defaults. To override, set `filters` explicitly — the list replaces the defaults wholesale:
|
||||
The default `[orchestrator]` config registers all three in both filter slots: `post_batch_filters` enforce by default (flagged rollouts are recorded but not shipped to the trainer), while `pre_batch_filters` run in monitor mode (`enforce = false`); flip `enforce = true` there to drop matching rollouts before they consume a slot in the batch. Setting a slot replaces its defaults wholesale:
|
||||
|
||||
```toml
|
||||
[[orchestrator.filters]]
|
||||
[[orchestrator.post_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
|
||||
[[orchestrator.filters]]
|
||||
[[orchestrator.post_batch_filters]]
|
||||
type = "repetition"
|
||||
threshold = 0.4
|
||||
```
|
||||
|
||||
Filtered rollouts still appear in W&B distributions, just not in the trainer batch — useful for spotting whether filtering is doing its job.
|
||||
|
||||
## Difficulty Pools
|
||||
|
||||
Difficulty pools gradually retire problems the model has solved or never solves. After each rollout, the average reward across a problem's group is compared to two thresholds:
|
||||
|
||||
- `buffer.easy_threshold` — at or above this, the problem moves into the `easy` pool and is no longer sampled.
|
||||
- `buffer.hard_threshold` — at or below this, the problem moves into the `hard` pool and is no longer sampled.
|
||||
- Otherwise the problem stays in `normal` and remains in the sampling rotation.
|
||||
|
||||
Pool assignments persist across checkpoints (`easy_examples.jsonl` / `hard_examples.jsonl` under each step's orchestrator checkpoint). When you resume — or want to broaden the curriculum mid-run — `buffer.easy_fraction` / `buffer.hard_fraction` randomly lift that fraction of pooled problems back into `normal` so they re-enter sampling.
|
||||
|
||||
```toml
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 0.95
|
||||
hard_threshold = 0.05
|
||||
easy_fraction = 0.0 # default; bump on resume to bring some easy problems back
|
||||
hard_fraction = 0.0 # default; bump on resume to bring some hard problems back
|
||||
```
|
||||
|
||||
Watch `pool/{env}/{easy,normal,hard}` (current pool ratios) and `evicted_examples/{env}/{easy,hard}` (per-step eviction rate).
|
||||
|
||||
## Online Difficulty Filtering
|
||||
|
||||
Online difficulty filtering (ODF) drops collapsed-advantage groups on the way *into* the buffer. Set `buffer.online_difficulty_filtering = true` (default `false`) to enable:
|
||||
|
||||
- Average reward across the group is **0.0** (every rollout failed) → drop the group, count under `filtered_rollouts/{env}/hard`.
|
||||
- Average reward **1.0** (every rollout succeeded) → drop, count under `filtered_rollouts/{env}/easy`.
|
||||
- Otherwise → into the buffer.
|
||||
|
||||
These are exactly the groups whose within-group advantage collapses to zero — DR-GRPO produces no gradient signal for them, so the trainer would burn step time on tokens it can't learn from.
|
||||
|
||||
```toml
|
||||
[orchestrator.buffer]
|
||||
online_difficulty_filtering = true
|
||||
```
|
||||
|
||||
**Tradeoff: trainer stability vs. inference speed.** With ODF on, every rollout that reaches the trainer carries non-zero advantage — each trainer step's effective batch is predictable and the gradient signal is denser. The cost is paid on the inference side: rollouts get produced and then thrown away, so the orchestrator has to oversample to keep the trainer fed. If the orchestrator is your bottleneck (`time/wait_for_batch` high on the trainer), ODF can starve the loop. Bump `orchestrator.oversampling_factor` so inference produces enough groups per step to absorb the drops.
|
||||
|
||||
ODF is orthogonal to the [pools](#difficulty-pools): ODF reacts to the *current* group's reward distribution, the pools track the *running* per-problem average. Many configs use both — ODF for per-step density, pools for long-horizon curriculum cleanup.
|
||||
|
||||
## Multi-Turn Trajectories
|
||||
|
||||
Multi-turn rollouts (tool use, browser environments, long conversations) used to be stitched into a single fake "single-turn" sample, which silently corrupted the importance ratio when chat templates didn't roundtrip. Since [`verifiers` v0.1.8](https://github.com/PrimeIntellect-ai/verifiers/releases/tag/v0.1.8), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
|
||||
|
||||
+36
-2
@@ -2,7 +2,7 @@
|
||||
|
||||
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
|
||||
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `token_export` flag) that aren't surfaced here.
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -17,7 +17,8 @@ Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeInt
|
||||
- [Optional Sub-Configs](#optional-sub-configs)
|
||||
- [None](#none)
|
||||
- [Discriminated Unions](#discriminated-unions)
|
||||
- [Environments (`[[orchestrator.train.env]]`)](#environments-orchestratortrainenv)
|
||||
- [Environments](#environments-orchestratortrainenv)
|
||||
- [Environment Variables](#environment-variables)
|
||||
- [Examples](#examples)
|
||||
|
||||
## Sources and Precedence
|
||||
@@ -165,6 +166,39 @@ args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
|
||||
The same `id` can appear multiple times across train and eval (or with different `args`) — useful for evaluating on a held-out split of the env you're training on, or comparing two configurations of the same env side by side. When `id` is reused, set a distinct `name` on each entry; `name` defaults to `id` and must be unique across all envs in the same group.
|
||||
|
||||
### Environment Variables
|
||||
|
||||
OS environment variables exported into launched component process(es). In `rl` configs, top-level `[env_vars]` applies to trainer, inference, and orchestrator:
|
||||
|
||||
```toml
|
||||
[env_vars]
|
||||
HF_HUB_OFFLINE = "1"
|
||||
TOKENIZERS_PARALLELISM = "false"
|
||||
```
|
||||
|
||||
Component-specific tables layer on top:
|
||||
|
||||
```toml
|
||||
[trainer.env_vars]
|
||||
NCCL_DEBUG = "INFO"
|
||||
PYTORCH_CUDA_ALLOC_CONF = "expandable_segments:False"
|
||||
|
||||
[inference.env_vars]
|
||||
VLLM_USE_DEEP_GEMM = "1"
|
||||
|
||||
[orchestrator.env_vars]
|
||||
PI_USAGE_BASE_URL = "https://..."
|
||||
```
|
||||
|
||||
The `rl` launcher applies these the same way in both single-node and multi-node (SLURM) runs. Precedence, low to high:
|
||||
|
||||
1. The launcher's own defaults — **your `env_vars` override these**.
|
||||
2. Your top-level `[env_vars]`.
|
||||
3. Your `[component.env_vars]`.
|
||||
4. Orchestration-critical vars the launcher always sets last — `CUDA_VISIBLE_DEVICES` (GPU partitioning) and `WANDB_SHARED_*` (the single shared W&B run) — **these cannot be overridden** from `env_vars`.
|
||||
|
||||
For standalone `sft` and `inference` configs, `[env_vars]` applies to that entrypoint's process(es). For disaggregated P/D inference, the role-specific [`deployment.{prefill,decode}_env_vars`](inference.md) layer on top of any shared inference env vars.
|
||||
|
||||
## Examples
|
||||
|
||||
The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples) are the canonical, kept-up-to-date references — the rest of the repo's TOMLs (under `configs/`) are CI- and debug-internal and may drift. Each example directory has its own README with the full launch story.
|
||||
|
||||
+25
-8
@@ -30,7 +30,7 @@ We support 3 distinct deployment shapes:
|
||||
|
||||
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
|
||||
|
||||
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `router_port`, `backend_port`, etc.
|
||||
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `backend_port`, and a `[...deployment.router]` block, etc.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
@@ -102,7 +102,7 @@ tp = 2
|
||||
dp = 4
|
||||
```
|
||||
|
||||
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing will be handled by the `vllm-router` instance running on the same node as the 1st replica. We aim to support more advanced routing options, such as `llm-d` or `dynamo` in the future. You can read more about the supported routing options in the [router](#router) section.
|
||||
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a router instance running on the same node as the 1st replica — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[...deployment.router]` block. You can read more about the supported routing options in the [router](#router) section.
|
||||
|
||||
### Wide-EP
|
||||
|
||||
@@ -167,21 +167,34 @@ This will run 3 inference replicas, each running on 6 nodes. Each replica will r
|
||||
|
||||
## Router
|
||||
|
||||
We use our own fork of [vllm-router](https://github.com/PrimeIntellect-ai/router) as the request handler. We plan to support more advanced proxy options in the future.
|
||||
Multi-node and disaggregated deployments front their vLLM backends with a router, configured via a discriminated `[...deployment.router]` block (`type = "vllm-router" | "llm-d"`):
|
||||
|
||||
Right now, router handles 2 most important things:
|
||||
```toml
|
||||
[inference.deployment.router] # or [deployment.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)
|
||||
```
|
||||
|
||||
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`.
|
||||
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy. Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
|
||||
|
||||
Both backends support the 2 most important things:
|
||||
- Request routing - KV cache re-use and balanced routing
|
||||
- P/D disaggregation - handling the prefill and decode stages separately
|
||||
|
||||
### Routing policies
|
||||
The 2 policies you might want to configure are:
|
||||
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - this works by hashing a request header to determine where to route the request to. You can configure what to hash by setting
|
||||
`orchestrator.student.client.extra_headers_from_state` to the header the `router` expects to be set.
|
||||
`orchestrator.model.client.extra_headers_from_state` to the header the `router` expects to be set.
|
||||
|
||||
We set it to a sensible default, that works with all verifiers environments.
|
||||
|
||||
```toml
|
||||
[orchestrator.student.client.extra_headers_from_state]
|
||||
[orchestrator.model.client.extra_headers_from_state]
|
||||
X-Session-ID = "trajectory_id" # this is the default - each rollout has a unique trajectory_id and router expects X-Session-ID
|
||||
```
|
||||
|
||||
@@ -232,16 +245,20 @@ For optimal P/D disaggregation deployment, we automatically set the decode `all2
|
||||
|
||||
For KV cache transfer, we utilize the NIXL connector. This is the default and only currently supported connector. We aim to support more advanced options, such as D->P transfer, or Mooncake Connector in the future.
|
||||
|
||||
> **Required:** The pip-wheel NIXL's bundled UCX segfaults on the prefill→decode KV transfer. You must build NIXL against UCX 1.19.x from source — see [Disaggregated Prefill/Decode Inference](advanced.md#disaggregated-prefilldecode-inference) in the Advanced docs for the full setup.
|
||||
|
||||
For configuring various knobs with environment variables, we enable you to configure prefill and decode environment variables separately. This is useful if you want to configure different environment variables for the prefill and decode stages.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
|
||||
prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip"}
|
||||
decode_env_overrides = {"VLLM_DEEP_GEMM_WARMUP"="skip"}
|
||||
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip"}
|
||||
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.
|
||||
|
||||
|
||||
+19
-30
@@ -41,7 +41,7 @@ uv run rl @ rl.toml \
|
||||
--inference.parallel.dp 6
|
||||
```
|
||||
|
||||
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next, teacher last. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
|
||||
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.
|
||||
|
||||
For quick A/B ablations on the same node, run two RL instances side-by-side in separate tmux sessions, each pinned to half the GPUs and a separate inference port:
|
||||
|
||||
@@ -54,7 +54,7 @@ CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --output-dir outputs/exp1
|
||||
bash scripts/tmux.sh -s exp2 -o outputs/exp2
|
||||
CUDA_VISIBLE_DEVICES=2,3 uv run rl @ rl.toml \
|
||||
--inference.server.port 8001 \
|
||||
--orchestrator.client.base-url http://localhost:8001/v1 \
|
||||
--orchestrator.model.client.base-url http://localhost:8001/v1 \
|
||||
--output-dir outputs/exp2
|
||||
```
|
||||
|
||||
@@ -92,10 +92,12 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
|
||||
|
||||
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
|
||||
|
||||
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is <= 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
ep = 8 # EP degree; must divide num_experts
|
||||
ep = 8 # explicit EP degree; must divide num_experts
|
||||
ep_comm_backend = "torch" # or "deepep"
|
||||
```
|
||||
|
||||
@@ -121,7 +123,7 @@ cp_style = "ulysses" # "ring"
|
||||
| `trainer.model.ac.mode = "selective"` | medium | small |
|
||||
| `trainer.model.ac_offloading` | extra | a bit more |
|
||||
|
||||
Enable selective AC (custom impl only) for the best memory/throughput tradeoff:
|
||||
AC and AC offloading are enabled by default (full mode). For the best memory/throughput tradeoff, switch to selective AC (custom impl only):
|
||||
|
||||
```toml
|
||||
[trainer.model.ac]
|
||||
@@ -129,55 +131,40 @@ mode = "selective"
|
||||
targets = ["norm", "attn_proj"] # see Reference for the full list per architecture
|
||||
```
|
||||
|
||||
We reccomend also using `ac_offloading` and `ac_offloading.max_inflight_activations = 5` to further reduce the memory footprint in tradeoff for some throughput. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput:
|
||||
|
||||
```toml
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
```
|
||||
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
|
||||
|
||||
### Optimizer Offloading
|
||||
|
||||
Offloading optimizer states to CPU is a near-free memory win at low GPU counts:
|
||||
Offloading optimizer states to CPU is enabled by default (`optim_cpu_offload = true`) — a near-free memory win at low GPU counts:
|
||||
|
||||
```toml
|
||||
[trainer.optim]
|
||||
# any optimizer type
|
||||
type = "adamw"
|
||||
|
||||
[trainer.model]
|
||||
optim_cpu_offload = true
|
||||
optim_cpu_offload = true # already the default
|
||||
```
|
||||
|
||||
Mutually exclusive with `fsdp_cpu_offload`. Also incompatible with `trainer.max_concurrent_runs > 1` (multi-tenant training). Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
|
||||
Mutually exclusive with `fsdp_cpu_offload`. Also incompatible with `trainer.max_concurrent_runs > 1` (multi-tenant training) — set `optim_cpu_offload = false` for multi-run. Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
|
||||
|
||||
### LM Head Chunking
|
||||
|
||||
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization:
|
||||
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization. It defaults to `1024` for RL training:
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
fused_lm_head_token_chunk_size = "auto" # picks 8192 for RL
|
||||
# or explicit:
|
||||
# fused_lm_head_token_chunk_size = 1024 # smaller = lower memory, more launches
|
||||
# fused_lm_head_token_chunk_size = "disabled" # default; vanilla LM head
|
||||
fused_lm_head_token_chunk_size = 1024 # default
|
||||
# fused_lm_head_token_chunk_size = "disabled" # vanilla LM head
|
||||
```
|
||||
|
||||
`auto` is a safe starting point for RL. Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. Only available with `model.impl = "custom"`, and currently RL-only — the SFT trainer rejects integer values.
|
||||
Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. SFT training silently disables this (not supported yet). Only available with `model.impl = "custom"`.
|
||||
|
||||
## Memory-Tight Recipe
|
||||
|
||||
The kitchen-sink config for fitting large MoE on limited GPUs at acceptable throughput:
|
||||
The kitchen-sink config for fitting large MoE on limited GPUs at acceptable throughput. AC, AC offloading, compile, fused LM head chunking, optimizer offload, and EP auto-resolution are on by default — only CP needs to be set explicitly (and EP overridden if auto-resolution is not desired):
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
ep = 8
|
||||
cp = 2
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
@@ -186,12 +173,14 @@ freq = 1
|
||||
max_inflight_activations = 1
|
||||
```
|
||||
|
||||
Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
|
||||
The defaults already cover: fused LM head chunking (`1024`), `torch.compile` (fullgraph=False), AC (full mode), AC offloading (`max_inflight_activations=5`), and optimizer CPU offload. Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
|
||||
|
||||
## SLURM
|
||||
|
||||
The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]` table is present — there's no separate entrypoint.
|
||||
|
||||
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
|
||||
|
||||
### Activation
|
||||
|
||||
A SLURM config is usually a thin overlay that adds `[slurm]` (and `[deployment]` for multi-node) on top of a base config. Configs are composed left-to-right via the `@` CLI syntax — see [Configuration § TOML Composition](configuration.md#toml-composition):
|
||||
@@ -237,7 +226,7 @@ gpus_per_node = 8
|
||||
|
||||
Full multi-node configs ship in [`examples/multinode/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/multinode):
|
||||
|
||||
- [`rl.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/multinode/rl.toml) — two-node RL run with NCCL weight broadcast on a 30B MoE student.
|
||||
- [`rl.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/multinode/rl.toml) — two-node RL run with NCCL weight broadcast on a 30B MoE policy.
|
||||
- [`sft.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/multinode/sft.toml) — two-node SFT against the same model.
|
||||
|
||||
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), and the launcher prints one URL per node. Front the URLs with a router or point clients at any of them.
|
||||
|
||||
+18
-13
@@ -1,6 +1,6 @@
|
||||
# Training
|
||||
|
||||
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer, the SFT trainer, and the related on-policy distillation mode. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md).
|
||||
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md).
|
||||
|
||||
> **AI agents working in this repo:** the equivalent runbooks are at [`skills/training/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/skills/training) — top-level routing in [`skills/training/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/SKILL.md), launch details in [`skills/training/start-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/start-run/SKILL.md), and check-in / restart procedures in [`skills/training/monitor-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/monitor-run/SKILL.md).
|
||||
|
||||
@@ -10,7 +10,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover
|
||||
- [RL Trainer](#rl-trainer)
|
||||
- [Launch](#launch)
|
||||
- [Useful Knobs](#useful-knobs)
|
||||
- [Training Modes (RL / OPD / SFT)](#training-modes-rl--opd--sft)
|
||||
- [Algorithms](#algorithms)
|
||||
- [Important Metrics](#important-metrics)
|
||||
- [SFT Trainer](#sft-trainer)
|
||||
- [Dataset Format](#dataset-format)
|
||||
@@ -59,7 +59,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
| `orchestrator.batch_size` | Tasks per trainer step. |
|
||||
| `orchestrator.group_size` | Rollouts generated per task. |
|
||||
| `orchestrator.max_off_policy_steps` | How many distinct policies may have contributed to one rollout before it's discarded (default 8). The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `errored_rollouts` and `mismatch_kl/all/mean` when tuning. |
|
||||
| `orchestrator.training_mode` | `rl` (default), `opd`, or `sft`. See [Training modes](#training-modes-rl--opd--sft). |
|
||||
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
|
||||
| `[[orchestrator.train.env]]` | Training environments. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Environments](configuration.md#environments-orchestratortrainenv). |
|
||||
| `[[orchestrator.eval.env]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
|
||||
|
||||
@@ -81,24 +81,29 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
|
||||
| `--dry-run` | Resolve + validate the full config, write per-process TOMLs to `<output_dir>/configs/`, and exit without launching. The fastest way to debug a misbehaving config. |
|
||||
|
||||
### Training Modes (RL / OPD / SFT)
|
||||
### Algorithms
|
||||
|
||||
The RL entrypoint supports three training modes, switched via `orchestrator.training_mode`:
|
||||
The RL entrypoint supports several training algorithms, switched via `[orchestrator.algo]`'s `type` (see [Algorithms](algorithms.md#the-algorithm-abstraction) for the full reference, model references, and per-algorithm customization):
|
||||
|
||||
| Mode | Student | Teacher | Use case |
|
||||
|---|---|---|---|
|
||||
| `rl` | Required | Forbidden | Standard RL |
|
||||
| `opd` | Required | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): student generates rollouts, trainer minimizes KL to teacher logprobs |
|
||||
| `sft` | Required | Required, any OpenAI-compatible endpoint | Hard-distill: teacher generates rollouts, student trains on them |
|
||||
| `algo.type` | Frozen model | Use case |
|
||||
|---|---|---|
|
||||
| `grpo` (default) | None | Standard group-relative RL |
|
||||
| `max_rl` | None | [MaxRL](https://arxiv.org/abs/2602.02710): GRPO with mean-normalized advantages (maximum-likelihood RL) |
|
||||
| `opd` | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): the policy generates rollouts, the trainer minimizes per-token reverse KL to a reference model |
|
||||
| `sft` | Required, any OpenAI-compatible endpoint | Hard-distill: a frozen model generates rollouts, the policy trains on its tokens |
|
||||
| `opsd` | None — the live policy is its own reference (no deployment) | [SDFT](https://arxiv.org/abs/2601.19897): the model is its own reference conditioned on expert demonstrations |
|
||||
| `echo` | None | GRPO plus cross-entropy on env-observation tokens |
|
||||
|
||||
The `rl` entrypoint only manages student-policy inference. For OPD and (local-vLLM) SFT, start the teacher inference server manually and point `[orchestrator.teacher.client]` at it:
|
||||
A new algorithm is a named class in code, not a config — see [Algorithms § Authoring an Algorithm](algorithms.md#authoring-an-algorithm).
|
||||
|
||||
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for `opd` (the frozen model scored against), `[orchestrator.algo.sampling.source]` for `sft` (the model it samples from) — each with `name` + `base_url`. `opsd` declares no frozen model: it self-distills against the live policy. The `rl` entrypoint only manages policy inference — start frozen-model servers yourself and point `base_url` at them:
|
||||
|
||||
```bash
|
||||
CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
--model.name <teacher> --server.port 8001
|
||||
--model.name <frozen-model> --server.port 8001
|
||||
```
|
||||
|
||||
The standalone `uv run sft` entrypoint is the more traditional SFT path — pure dataset-based, no teacher, no orchestrator. Use `orchestrator.training_mode = "sft"` only when you want a teacher to generate the supervision on the fly.
|
||||
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.
|
||||
|
||||
### Important Metrics
|
||||
|
||||
|
||||
@@ -58,21 +58,3 @@ PS: If using the tmux helper, you can run the command in the `Terminal` (window
|
||||
```bash
|
||||
uv run rl @ examples/Intellect-3.1/rl.toml --output-dir /shared/outputs/intellect-3.1
|
||||
```
|
||||
|
||||
Output of the command:
|
||||
```
|
||||
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/intellect-3.1/configs [rl.py::515]
|
||||
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/intellect-3.1/rl.sbatch [rl.py::534]
|
||||
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/intellect-3.1/rl.sbatch [rl.py::540]
|
||||
XXX:XX:XX SUCCESS Submitted batch job YYYY
|
||||
|
||||
Logs:
|
||||
Trainer: tail -F /shared/outputs/intellect-3.1/logs/trainer.log
|
||||
Orchestrator: tail -F /shared/outputs/intellect-3.1/logs/orchestrator.log
|
||||
Inference: tail -F /shared/outputs/intellect-3.1/logs/inference.log
|
||||
Envs: tail -F /shared/outputs/intellect-3.1/logs/envs/*/*/*.log
|
||||
Train: tail -F /shared/outputs/intellect-3.1/logs/envs/train/*/*.log
|
||||
swe: tail -F /shared/outputs/intellect-3.1/logs/envs/train/swe/*.log
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# High-throughput GLM-5 with llm-d
|
||||
|
||||
This example trains `GLM-5.1` with RL on agentic SWE tasks using P/D disaggregation, FP8 inference, and a Mooncake distributed CPU KV store — fronted by the upstream [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy).
|
||||
|
||||
**llm-d is the faster way to run GLM-5.** It is the recommended router backend for large GLM-5 runs: its `active-request-scorer` is an in-flight load balancer that spreads requests across ranks immediately, instead of relying on metrics that are scraped on a delay (as the default `vllm-router` does). Combined with prefix-cache affinity for grouped rollouts, this keeps prefill and decode ranks evenly loaded under the bursty request pattern of RL. If you want the simpler default router instead, see the [GLM-5 PD disaggregation example](../glm5_pd_disag/README.md).
|
||||
|
||||
## Requirements
|
||||
|
||||
You need access to a Slurm cluster with at least **32 nodes** (16 trainer + 16 inference, 8 GPUs each) and a shared filesystem. In this guide we assume the NFS is mounted at `/shared`; you can change it to your own path.
|
||||
|
||||
You also need prime-rl cloned on your cluster into the shared filesystem.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
```
|
||||
|
||||
### Install llm-d
|
||||
|
||||
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
|
||||
|
||||
```bash
|
||||
bash scripts/install_llmd.sh
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
```bash
|
||||
touch .env
|
||||
echo "WANDB_API_KEY=your_wandb_api_key" >> .env
|
||||
echo "HUGGINGFACE_TOKEN=your_huggingface_token" >> .env
|
||||
```
|
||||
|
||||
### sandbox
|
||||
|
||||
The SWE environment is configured to use Prime Intellect Sandboxes. You can find more information about the sandboxes [here](https://docs.primeintellect.ai/sandboxes/overview). You will need to create a sandbox account and add the credentials to the `.env` file. Alternatively, you can adapt the code of the environment to use your own sandbox implementation.
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
This config is tuned for our cluster — a few values **must** be adapted to yours before you run. Search the config for these markers:
|
||||
|
||||
- **`output_dir`** (`# FILL IN`) — point it at your shared filesystem.
|
||||
- **`[slurm] partition`** (`# FILL IN`) — set it to your cluster's Slurm partition.
|
||||
- **`[inference.kv_cache_offload] device_name`** (`# do it yourself`) — the list of RDMA NICs for Mooncake. Auto-detection is unreliable, so set it by hand from `nvidia-smi topo -m` on your nodes.
|
||||
|
||||
A few more knobs you may want to tune for your hardware:
|
||||
|
||||
- **Trainer parallelism** — this config assumes **16 trainer nodes** at **131K** sequence length with `cp = 4` (context parallel) and the `adamw` optimizer. If you have fewer trainer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` accordingly.
|
||||
- **Scorer weights** (`[inference.deployment.router]`) — the `scorers` / `prefill_scorer_overrides` / `decode_scorer_overrides` weights follow the upstream llm-d P/D guide and are a good starting point; tune them if your prefill/decode balance drifts.
|
||||
- **Mooncake CPU pool** (`[inference.kv_cache_offload.cpu] num_bytes`) — defaults to 1TB/node; lower it if your nodes have less RAM.
|
||||
|
||||
## Tmux session
|
||||
|
||||
We recommend using the tmux helper to start the run and look at the logs.
|
||||
|
||||
From your Slurm head node:
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh glm5-llmd /shared/outputs/glm5-llmd
|
||||
```
|
||||
|
||||
You can then attach to it by doing `tmux attach -t glm5-llmd`.
|
||||
|
||||
## Start the run
|
||||
|
||||
Run the following command to start the RL training:
|
||||
|
||||
PS: If using the tmux helper, you can run the command in the `Terminal` (window 0) pane and look at the logs in the `Logs` (window 1) pane.
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/glm5_llmd/rl.toml --output-dir /shared/outputs/glm5-llmd
|
||||
```
|
||||
@@ -0,0 +1,129 @@
|
||||
max_steps = 10000000
|
||||
seq_len = 131072
|
||||
output_dir = "/shared/outputs/glm5-llmd" # FILL IN: point at your shared filesystem
|
||||
clean_output_dir = true
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
[wandb]
|
||||
project = "glm5-llmd"
|
||||
name = "base"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
port = 29502
|
||||
timeout = 12000
|
||||
quantize_in_weight_transfer = true
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 16
|
||||
num_infer_nodes = 16
|
||||
gpus_per_node = 8
|
||||
num_infer_replicas = 1
|
||||
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 8
|
||||
num_prefill_replicas = 4
|
||||
num_decode_nodes = 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"}
|
||||
|
||||
# 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.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
|
||||
|
||||
[slurm]
|
||||
job_name = "glm5-llmd"
|
||||
partition = "all" # FILL IN: set to your cluster's partition
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 1800
|
||||
enable_token_export = true
|
||||
|
||||
[trainer.model]
|
||||
name = "zai-org/GLM-5.1"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2" # ignored with GLM5
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
cp = 4 # context parallel for the 131K seq len
|
||||
ep = 8
|
||||
optim_cpu_offload = true
|
||||
fp8 = true
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.optim]
|
||||
type = "adamw"
|
||||
lr = 1e-6
|
||||
weight_decay = 0.0
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
max_inflight_rollouts = 2048
|
||||
max_off_policy_steps = 8 # 16/32 can be better, 8 is more CPU stable
|
||||
|
||||
[orchestrator.model]
|
||||
name = "zai-org/GLM-5.1-FP8"
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-5.1"
|
||||
clear_thinking = false
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 1.0
|
||||
extra_body = {chat_template_kwargs = {clear_thinking = false}}
|
||||
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "r2e"
|
||||
taskset = { id = "r2e-gym-v1" }
|
||||
harness = { id = "rlm", 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
|
||||
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
|
||||
|
||||
[inference.kv_cache_offload.cpu]
|
||||
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
|
||||
@@ -54,21 +54,3 @@ PS: If using the tmux helper, you can run the command in the `Terminal` (window
|
||||
```bash
|
||||
uv run rl @ examples/glm5_pd_disag/rl.toml --output-dir /shared/outputs/glm5-pd-disag
|
||||
```
|
||||
|
||||
Output of the command:
|
||||
```
|
||||
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/glm5-pd-disag/configs [rl.py::515]
|
||||
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/glm5-pd-disag/rl.sbatch [rl.py::534]
|
||||
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/glm5-pd-disag/rl.sbatch [rl.py::540]
|
||||
XXX:XX:XX SUCCESS Submitted batch job YYYY
|
||||
|
||||
Logs:
|
||||
Trainer: tail -F /shared/outputs/glm5-pd-disag/logs/trainer.log
|
||||
Orchestrator: tail -F /shared/outputs/glm5-pd-disag/logs/orchestrator.log
|
||||
Inference: tail -F /shared/outputs/glm5-pd-disag/logs/inference.log
|
||||
Envs: tail -F /shared/outputs/glm5-pd-disag/logs/envs/*/*/*.log
|
||||
Train: tail -F /shared/outputs/glm5-pd-disag/logs/envs/train/*/*.log
|
||||
swe: tail -F /shared/outputs/glm5-pd-disag/logs/envs/train/swe/*.log
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ group_size = 16
|
||||
oversampling_factor = 3
|
||||
max_off_policy_steps = 16
|
||||
|
||||
[orchestrator.student.model]
|
||||
[orchestrator.model]
|
||||
name = "zai-org/GLM-5-FP8"
|
||||
|
||||
[orchestrator.eval]
|
||||
|
||||
@@ -54,21 +54,3 @@ PS: If using the tmux helper, you can run the command in the `Terminal` (window
|
||||
```bash
|
||||
uv run rl @ examples/minimax_m2.5_swe/rl.toml --output-dir /shared/outputs/minimax-swe
|
||||
```
|
||||
|
||||
Output of the command:
|
||||
```
|
||||
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/minimax-swe/configs [rl.py::515]
|
||||
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/minimax-swe/rl.sbatch [rl.py::534]
|
||||
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/minimax-swe/rl.sbatch [rl.py::540]
|
||||
XXX:XX:XX SUCCESS Submitted batch job YYYY
|
||||
|
||||
Logs:
|
||||
Trainer: tail -F /shared/outputs/minimax-swe/logs/trainer.log
|
||||
Orchestrator: tail -F /shared/outputs/minimax-swe/logs/orchestrator.log
|
||||
Inference: tail -F /shared/outputs/minimax-swe/logs/inference.log
|
||||
Envs: tail -F /shared/outputs/minimax-swe/logs/envs/*/*/*.log
|
||||
Train: tail -F /shared/outputs/minimax-swe/logs/envs/train/*/*.log
|
||||
swe: tail -F /shared/outputs/minimax-swe/logs/envs/train/swe/*.log
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -46,21 +46,3 @@ PS: If using the tmux helper, you can run the command in the `Terminal` (window
|
||||
```bash
|
||||
uv run rl @ examples/qwen30b_math/rl.toml --output-dir /shared/outputs/qwen30b-math
|
||||
```
|
||||
|
||||
Output of the command:
|
||||
```
|
||||
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/qwen30b-math/configs [rl.py::515]
|
||||
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/qwen30b-math/rl.sbatch [rl.py::534]
|
||||
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/qwen30b-math/rl.sbatch [rl.py::540]
|
||||
XXX:XX:XX SUCCESS Submitted batch job YYYY
|
||||
|
||||
Logs:
|
||||
Trainer: tail -F /shared/outputs/qwen30b-math/logs/trainer.log
|
||||
Orchestrator: tail -F /shared/outputs/qwen30b-math/logs/orchestrator.log
|
||||
Inference: tail -F /shared/outputs/qwen30b-math/logs/inference.log
|
||||
Envs: tail -F /shared/outputs/qwen30b-math/logs/envs/*/*/*.log
|
||||
Train: tail -F /shared/outputs/qwen30b-math/logs/envs/train/*/*.log
|
||||
math: tail -F /shared/outputs/qwen30b-math/logs/envs/train/math/*.log
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -54,21 +54,3 @@ PS: If using the tmux helper, you can run the command in the `Terminal` (window
|
||||
```bash
|
||||
uv run rl @ examples/qwen30b_swe/rl.toml --output-dir /shared/outputs/qwen30b-swe
|
||||
```
|
||||
|
||||
Output of the command:
|
||||
```
|
||||
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/qwen30b-swe/configs [rl.py::515]
|
||||
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/qwen30b-swe/rl.sbatch [rl.py::534]
|
||||
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/qwen30b-swe/rl.sbatch [rl.py::540]
|
||||
XXX:XX:XX SUCCESS Submitted batch job YYYY
|
||||
|
||||
Logs:
|
||||
Trainer: tail -F /shared/outputs/qwen30b-swe/logs/trainer.log
|
||||
Orchestrator: tail -F /shared/outputs/qwen30b-swe/logs/orchestrator.log
|
||||
Inference: tail -F /shared/outputs/qwen30b-swe/logs/inference.log
|
||||
Envs: tail -F /shared/outputs/qwen30b-swe/logs/envs/*/*/*.log
|
||||
Train: tail -F /shared/outputs/qwen30b-swe/logs/envs/train/*/*.log
|
||||
swe: tail -F /shared/outputs/qwen30b-swe/logs/envs/train/swe/*.log
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ dp = 6
|
||||
|
||||
# Qwen3 finetune with the standard PI template patch (byte-identical to
|
||||
# PrimeIntellect/Qwen3-0.6B base); always re-emits prior <think> blocks.
|
||||
# Match that with the qwen3 renderer's preserve_all_thinking.
|
||||
# Match that with renderer thinking_retention.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
preserve_all_thinking = true
|
||||
thinking_retention = "all"
|
||||
|
||||
@@ -10,6 +10,7 @@ dependencies = [
|
||||
"renderers>=0.1.8.dev28",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.1.15.dev390",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
"""Algorithm abstraction: sampling and the per-token training signal.
|
||||
|
||||
An algorithm is a named, self-contained config — a discriminated union keyed
|
||||
on ``type`` (``grpo``, ``max_rl``, ``opd``, ``opsd``, ``sft``, ``echo``).
|
||||
The bundle *is* the algorithm: each variant carries
|
||||
its sampling component and its credit-assignment / loss-routing parameters,
|
||||
and its class defaults are the vetted setting — ``type = "opd"`` with a
|
||||
teacher IS on-policy distillation; any key you set is visibly your own
|
||||
assembly. There is no separate ``advantage`` sub-component and no preset layer.
|
||||
|
||||
Each algorithm fixes two things:
|
||||
|
||||
1. **Sampling** — which model generates train rollouts. ``sampling.source`` is
|
||||
a model reference: ``"policy"`` (the live policy) or an inline frozen hosted
|
||||
model.
|
||||
2. **The per-token training signal** — credit assignment and loss routing,
|
||||
fused: one mapping from a finalized rollout to per-token ``(loss component,
|
||||
weight)``. Group-relative algorithms compute scalars on the orchestrator and
|
||||
ship numbers; reference-KL algorithms ship reference prefill logprobs and the
|
||||
trainer evaluates the per-token signal against the live policy. The algorithm
|
||||
determines which loss component consumes the action tokens (``rl`` / ``ce`` /
|
||||
``ref_kl``, via the ``action_loss_type`` class declaration) and what happens
|
||||
to env-provided observation tokens (masked out by default; ``echo`` trains on
|
||||
them with weighted CE).
|
||||
|
||||
prime-rl only ever hosts the trainable policy. Every other model an algorithm
|
||||
uses is an external OpenAI-compatible endpoint, declared inline on the
|
||||
algorithm that uses it (a :class:`FrozenModelConfig`). Model roles like
|
||||
"teacher" are algorithm-local vocabulary over these references; the pipeline
|
||||
branches on liveness alone. The trainer is algorithm-blind: the loss is a sum
|
||||
of three components (rl, ce, ref_kl), each normalized by its own global token
|
||||
count; per-token component weights ship on the wire and the trainer just
|
||||
executes them.
|
||||
"""
|
||||
|
||||
from typing import Annotated, Any, ClassVar, Literal, TypeAlias
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class FrozenModelConfig(ClientConfig):
|
||||
"""An externally hosted model behind an OpenAI-compatible endpoint: the
|
||||
client config plus the served model's ``name``.
|
||||
|
||||
prime-rl never launches or updates these — only the trainable policy is
|
||||
ever hosted by prime-rl itself. Frozen models are reachable-but-unmanaged:
|
||||
``base_url`` is required, their weights never change, and rollouts or
|
||||
scores from them never go stale (stable prefix cache, no off-policy
|
||||
aging)."""
|
||||
|
||||
name: str
|
||||
"""Served model name, sent as the ``model`` field of every request."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_explicit_endpoint(self):
|
||||
if "base_url" not in self.model_fields_set and not self.is_elastic:
|
||||
raise ValueError(
|
||||
"a frozen model reference needs base_url — frozen models are externally "
|
||||
"hosted; prime-rl only ever hosts the trainable policy."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
ModelReference: TypeAlias = Literal["policy"] | FrozenModelConfig
|
||||
"""``"policy"`` (the live policy — weight-updated: prefix caches salted per
|
||||
version, sampling logprobs carried, rollouts age off-policy) or an inline
|
||||
externally-hosted frozen model."""
|
||||
|
||||
ActionLossType: TypeAlias = Literal["rl", "ce", "ref_kl"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sampling
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class SamplingConfig(BaseConfig):
|
||||
source: ModelReference = "policy"
|
||||
"""Model reference for train rollout generation: ``"policy"`` (the live
|
||||
policy — prefix caches salted per version, sampling logprobs requested,
|
||||
rollouts age off-policy) or an inline frozen hosted model (stable prefix
|
||||
cache, no sampling logprobs, rollouts never go stale)."""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Shared sub-configs (length penalty, echo roles)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class LinearLengthPenaltyConfig(BaseConfig):
|
||||
"""Linear ``pass_rate``-scaled penalty subtracted from each reward before the GRPO baseline — the sum of three terms (completion tokens, input tokens, turns), each normalized by the group's own max for that quantity and disabled by setting its coefficient to 0."""
|
||||
|
||||
type: Literal["linear"] = "linear"
|
||||
|
||||
num_output_tokens_weight: float = Field(0.25, ge=0, allow_inf_nan=False)
|
||||
"""Scale on the output-token term. Each reward is reduced by ``num_output_tokens_weight * pass_rate * (rollout num_output_tokens / group's max num_output_tokens)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative; 0 disables the term."""
|
||||
|
||||
num_input_tokens_weight: float = Field(0.1, ge=0, allow_inf_nan=False)
|
||||
"""Scale on the input-token term — tokens the model conditioned on but did not generate (``num_total_tokens - num_output_tokens``: prompts, tool responses), as a fraction of the group's max input tokens. 0 disables the term."""
|
||||
|
||||
num_turns_weight: float = Field(0.1, ge=0, allow_inf_nan=False)
|
||||
"""Scale on the turns term (``pass_rate * (rollout num_turns / group's max num_turns)``). 0 disables the term."""
|
||||
|
||||
|
||||
LengthPenaltyConfig: TypeAlias = LinearLengthPenaltyConfig
|
||||
|
||||
|
||||
class EchoRoleConfig(BaseConfig):
|
||||
"""Echo CE supervision for one message role."""
|
||||
|
||||
alpha: float = Field(0.1, gt=0)
|
||||
"""Per-token ce weight for this role's env-provided tokens (ECHO's lambda)."""
|
||||
|
||||
|
||||
class EchoRolesConfig(BaseConfig):
|
||||
"""Which env-provided message roles train, each at its own weight.
|
||||
Setting any role replaces the whole table — unset roles stay disabled."""
|
||||
|
||||
system: EchoRoleConfig | None = None
|
||||
user: EchoRoleConfig | None = None
|
||||
assistant: EchoRoleConfig | None = None
|
||||
tool: EchoRoleConfig | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_a_role(self):
|
||||
if self.system is None and self.user is None and self.assistant is None and self.tool is None:
|
||||
raise ValueError("echo needs at least one role enabled (system, user, assistant, or tool)")
|
||||
return self
|
||||
|
||||
|
||||
class EchoFilterConfig(BaseConfig):
|
||||
"""User-supplied per-token filter narrowing the role-selected echo tokens.
|
||||
|
||||
The callable is imported at startup and invoked once per rollout as
|
||||
``filter_fn(rollout, **kwargs) -> list[list[bool]]`` — one keep-mask per
|
||||
trainable branch, each spanning that branch's ``token_ids``. Tokens with
|
||||
``False`` never receive echo weight; the
|
||||
filter can only narrow the role selection, not widen it. The raw rollout
|
||||
exposes message text and sampling logprobs, so content filters (e.g.
|
||||
dropping tool-output warnings) and sampling-probability filters need no
|
||||
extra framework surface."""
|
||||
|
||||
import_path: str
|
||||
"""Import path to the filter callable (e.g. ``my_module.drop_warnings``)."""
|
||||
|
||||
kwargs: dict[str, Any] = Field(default_factory=dict)
|
||||
"""Kwargs forwarded to the filter."""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The algorithms (a discriminated union keyed on ``type``)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class BaseAlgoConfig(BaseConfig):
|
||||
"""Base for every algorithm: the shared sampling component and the
|
||||
cross-cutting source/loss compatibility check. Each subclass sets ``type``
|
||||
(the discriminator), declares its loss routing (``action_loss_type``), and
|
||||
adds its own parameters — including any reference model it needs, named
|
||||
where that model is actually used (opd scores against a frozen ``teacher``;
|
||||
sft samples from its ``sampling.source``; opsd self-distills against the
|
||||
live policy and names no model).
|
||||
|
||||
The bundle IS the algorithm — there is no separate ``advantage``
|
||||
sub-component. ``algo.type`` names it, and the class defaults are the
|
||||
vetted setting."""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
sampling: SamplingConfig = SamplingConfig()
|
||||
"""Sampling component: which model generates train rollouts."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_sampling_source(self):
|
||||
"""The on-policy loss types (rl, ref_kl) need the live policy's own
|
||||
sampling logprobs, so they must sample from ``"policy"``; only sft (ce)
|
||||
may sample from a frozen model."""
|
||||
if self.action_loss_type in ("rl", "ref_kl") and self.sampling.source != "policy":
|
||||
raise ValueError(
|
||||
f"algorithm '{self.type}' trains with the "
|
||||
f"{self.action_loss_type} loss type but sampling.source is a frozen model — "
|
||||
"the importance ratio and trust region need the live policy's own sampling logprobs. "
|
||||
"Use the 'sft' algorithm to distill frozen-model tokens."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class GRPOAlgoConfig(BaseAlgoConfig):
|
||||
type: Literal["grpo"] = "grpo"
|
||||
"""GRPO: scalar advantage = reward minus the per-group mean baseline,
|
||||
consumed by the ``rl`` loss component on the rollout's action tokens."""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
length_penalty: LengthPenaltyConfig | None = None
|
||||
"""Linear length penalty subtracted from each reward before the GRPO baseline (see ``LinearLengthPenaltyConfig``): a ``pass_rate``-scaled sum of output-token, input-token, and turns terms, each normalized by the group's own max for that quantity. None disables it."""
|
||||
|
||||
|
||||
class EchoAlgoConfig(GRPOAlgoConfig):
|
||||
type: Literal["echo"] = "echo" # type: ignore[assignment]
|
||||
"""ECHO: group-relative advantage on action tokens (GRPO), plus weighted
|
||||
CE on env-provided tokens of later turns (tool output, user feedback),
|
||||
selected by message role via the renderer's per-token ``is_content``
|
||||
attribution (renderers that don't attribute content fall back to weighting
|
||||
the whole non-sampled span). Selected tokens feed the ``ce`` loss component
|
||||
at their role's ``alpha`` and stay outside the rl mask and its denominator."""
|
||||
|
||||
roles: EchoRolesConfig = EchoRolesConfig(tool=EchoRoleConfig())
|
||||
"""The role table. The default — tool-response bodies at ``alpha = 0.1``
|
||||
— is the vetted ECHO setting."""
|
||||
|
||||
filter: EchoFilterConfig | None = None
|
||||
"""Optional user-supplied filter narrowing the role-selected tokens."""
|
||||
|
||||
|
||||
class MaxRLAlgoConfig(BaseAlgoConfig):
|
||||
type: Literal["max_rl"] = "max_rl"
|
||||
"""MaxRL (arXiv:2602.02710): scalar advantage = (reward − group mean) /
|
||||
group mean, consumed by the ``rl`` loss component. Normalizing by the
|
||||
mean instead of GRPO's standard deviation makes the policy gradient
|
||||
unbiased for the order-``group_size`` truncation of the maximum-likelihood
|
||||
objective: low-pass-rate examples get ~1/p weight, and ``group_size`` is
|
||||
the truncation order interpolating REINFORCE (1) → exact maximum
|
||||
likelihood (∞). Designed for non-negative (canonically binary) rewards;
|
||||
a group with mean reward 0 carries zero advantages everywhere (the
|
||||
zero-advantage filter drops it, matching the paper's K=0 convention)."""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
|
||||
class OPDAlgoConfig(BaseAlgoConfig):
|
||||
type: Literal["opd"] = "opd"
|
||||
"""On-policy distillation: the per-token signal is the reverse KL to
|
||||
a reference model, evaluated in the trainer from reference prefill
|
||||
logprobs scored over each sample's own context (``ref_logprobs`` on the
|
||||
wire, ``ref_kl`` loss component). No scalar advantage is assigned —
|
||||
rollouts keep ``advantages=None`` (advantage-based filters never fire) and
|
||||
samples ship no advantage stream. ``group_size`` only fans out sampling."""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "ref_kl"
|
||||
|
||||
teacher: FrozenModelConfig
|
||||
"""The teacher — an inline frozen hosted model (``name`` + ``base_url``)
|
||||
whose reverse KL the policy distills toward. Required, and necessarily a
|
||||
frozen endpoint: scoring the policy under itself yields zero KL signal, so
|
||||
``"policy"`` is not even representable here (use ``opsd`` for
|
||||
demo-conditioned self-teaching)."""
|
||||
|
||||
|
||||
class OPSDAlgoConfig(BaseAlgoConfig):
|
||||
type: Literal["opsd"] = "opsd"
|
||||
"""On-policy self-distillation (SDFT, https://arxiv.org/abs/2601.19897):
|
||||
the per-token signal is the reverse KL against the live policy conditioned
|
||||
on an expert demonstration. The teacher *is* the policy — self-distillation
|
||||
names no separate model — scoring each sample with the demonstration
|
||||
prepended as a leading system message. The sample is scored verbatim (no
|
||||
re-rendering), so it's robust to tool/multimodal prompts and works for any
|
||||
number of turns. No scalar advantage is assigned — rollouts keep
|
||||
``advantages=None`` (advantage-based filters never fire) and samples ship no
|
||||
advantage stream."""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "ref_kl"
|
||||
|
||||
demo_key: str = "demonstration"
|
||||
"""Key holding the expert demonstration text — looked up in the example's
|
||||
``info`` dict first, then as a top-level rollout field (e.g. ``answer``)."""
|
||||
|
||||
template: str = "Here is an example of an expert response:\n<demonstration>\n{demonstration}\n</demonstration>"
|
||||
"""Content of the leading system message carrying the demonstration.
|
||||
Receives ``{demonstration}``; the original question stays in the (verbatim)
|
||||
user turn, so it isn't templated here."""
|
||||
|
||||
renderer: RendererConfig = AutoRendererConfig()
|
||||
"""Renderer family for the hint block. The tokenizer is always the live
|
||||
policy's (self-distillation has no separate model — not configurable).
|
||||
Defaults to ``"auto"`` (resolved from the policy tokenizer); set explicitly
|
||||
to match a non-auto policy renderer."""
|
||||
|
||||
|
||||
class SFTAlgoConfig(BaseAlgoConfig):
|
||||
type: Literal["sft"] = "sft"
|
||||
"""SFT distillation: cross-entropy on the sampled tokens. The ``ce`` loss
|
||||
ignores advantages and SFT assigns none — it trains on every sampled token.
|
||||
Reward-based filtering, if wanted, is an explicit filter, not smuggled
|
||||
through an unused advantage stream."""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "ce"
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_frozen_source(self):
|
||||
"""sft's teacher is the model it samples from — ``sampling.source`` must
|
||||
be a frozen hosted model, not the policy (CE on the policy's own tokens
|
||||
is not a distillation target)."""
|
||||
if self.sampling.source == "policy":
|
||||
raise ValueError(
|
||||
f"algorithm '{self.type}' needs a teacher to sample rollouts from — "
|
||||
"CE on the policy's own tokens is not a distillation target. Set "
|
||||
"sampling.source to an inline hosted model (name + base_url)."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
AlgoConfig: TypeAlias = Annotated[
|
||||
GRPOAlgoConfig | EchoAlgoConfig | MaxRLAlgoConfig | OPDAlgoConfig | OPSDAlgoConfig | SFTAlgoConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
"""The training algorithm: sampling plus the per-token training signal (credit
|
||||
assignment and loss routing, fused). The ``type`` selects the algorithm, and
|
||||
its class defaults are the vetted setting.
|
||||
|
||||
- ``grpo`` — policy group sampling, group-relative advantage, RL loss (the default).
|
||||
- ``max_rl`` — GRPO with mean-normalized advantages (maximum-likelihood RL).
|
||||
- ``opd`` — on-policy distillation: policy samples, per-token reverse KL against a reference model. Needs ``teacher``.
|
||||
- ``opsd`` — SDFT: policy samples, demo-conditioned reverse KL against the live policy (the teacher is the policy itself).
|
||||
- ``sft`` — a frozen model samples, the policy trains with CE on its tokens. Needs a frozen ``sampling.source``.
|
||||
- ``echo`` — GRPO on action tokens + weighted CE on tool-response observation tokens.
|
||||
|
||||
A new credit-assignment scheme is a new named algorithm in code (subclass
|
||||
``Algorithm``, register it), not a config that points at an import path.
|
||||
"""
|
||||
@@ -1,25 +1,14 @@
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import model_validator
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class EnvServerConfig(BaseConfig):
|
||||
env: EnvConfig = EnvConfig()
|
||||
env: EnvConfig
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
env_install_prerelease: bool = False
|
||||
"""Allow pre-release versions when installing environments. Passes ``--prerelease`` to ``prime env install``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_num_workers(self):
|
||||
if self.env.num_workers == "auto":
|
||||
self.env.num_workers = 1
|
||||
return self
|
||||
|
||||
@@ -5,7 +5,7 @@ from typing import Annotated, Any, Literal, TypeAlias
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic_config import BaseConfig
|
||||
|
||||
from prime_rl.configs.shared import BaseModelConfig, LogConfig, SlurmConfig
|
||||
from prime_rl.configs.shared import BaseModelConfig, EnvVars, LogConfig, SlurmConfig
|
||||
from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
|
||||
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
|
||||
|
||||
@@ -167,8 +167,26 @@ All2AllBackend = Literal[
|
||||
]
|
||||
|
||||
|
||||
# Known llm-d EPP scorer plugins (used to guard the ``scorers`` map against typos).
|
||||
KNOWN_SCORERS = frozenset(
|
||||
{
|
||||
"prefix-cache-scorer",
|
||||
"precise-prefix-cache-scorer",
|
||||
"queue-scorer",
|
||||
"kv-cache-utilization-scorer",
|
||||
"active-request-scorer",
|
||||
"load-aware-scorer",
|
||||
"running-requests-size-scorer",
|
||||
"token-load-scorer",
|
||||
"latency-scorer",
|
||||
"session-affinity-scorer",
|
||||
"lora-affinity-scorer",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class VllmRouterConfig(BaseConfig):
|
||||
"""PrimeIntellect vllm-router fronting the per-rank (external-LB) endpoints."""
|
||||
"""PrimeIntellect vllm-router."""
|
||||
|
||||
type: Literal["vllm-router"] = "vllm-router"
|
||||
|
||||
@@ -179,9 +197,57 @@ class VllmRouterConfig(BaseConfig):
|
||||
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
|
||||
|
||||
|
||||
# Discriminated on ``type`` so additional router backends can be added to the
|
||||
# union (a single member needs no discriminator yet).
|
||||
RouterConfig: TypeAlias = VllmRouterConfig
|
||||
class LlmdRouterConfig(BaseConfig):
|
||||
"""llm-d router backend (EPP + Envoy)."""
|
||||
|
||||
type: Literal["llm-d"] = "llm-d"
|
||||
|
||||
port: int = 8000
|
||||
"""Port the Envoy gateway listens on — becomes the client-facing router URL."""
|
||||
|
||||
scorers: dict[str, float] = {
|
||||
"prefix-cache-scorer": 3.0,
|
||||
"active-request-scorer": 2.0,
|
||||
}
|
||||
"""EPP scorer name → weight, applied to every routing profile (before the per-profile P/D overrides). Defaults to prefix-cache affinity plus in-flight (active-request) load balancing. Unknown scorer names are rejected."""
|
||||
|
||||
prefill_scorer_overrides: dict[str, float] = {
|
||||
"queue-scorer": 2.0,
|
||||
"kv-cache-utilization-scorer": 2.0,
|
||||
}
|
||||
"""P/D only: scorer → weight merged onto ``scorers`` for the prefill profile (a per-profile weight overrides the base)."""
|
||||
|
||||
decode_scorer_overrides: dict[str, float] = {}
|
||||
"""P/D only: scorer → weight merged onto ``scorers`` for the decode profile (a per-profile weight overrides the base); empty by default."""
|
||||
|
||||
non_cached_tokens: int = 16
|
||||
"""P/D only: requests with fewer than this many non-cached prompt tokens skip remote prefill and run decode-only."""
|
||||
|
||||
decode_sidecar_port: int = 8300
|
||||
"""P/D only: port the decode-side llm-d sidecar listens on."""
|
||||
|
||||
@property
|
||||
def prefill_scorers(self) -> dict[str, float]:
|
||||
"""Effective prefill-profile scorers: ``scorers`` merged with ``prefill_scorer_overrides``."""
|
||||
return {**self.scorers, **self.prefill_scorer_overrides}
|
||||
|
||||
@property
|
||||
def decode_scorers(self) -> dict[str, float]:
|
||||
"""Effective decode-profile scorers: ``scorers`` merged with ``decode_scorer_overrides``."""
|
||||
return {**self.scorers, **self.decode_scorer_overrides}
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_scorers(self):
|
||||
unknown = (
|
||||
set(self.scorers) | set(self.prefill_scorer_overrides) | set(self.decode_scorer_overrides)
|
||||
) - KNOWN_SCORERS
|
||||
if unknown:
|
||||
raise ValueError(f"Unknown llm-d scorer(s): {sorted(unknown)}. Known scorers: {sorted(KNOWN_SCORERS)}.")
|
||||
return self
|
||||
|
||||
|
||||
# Discriminated on ``type`` so the launch path can pick the router backend.
|
||||
RouterConfig: TypeAlias = Annotated[VllmRouterConfig | LlmdRouterConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class BaseInferenceDeploymentConfig(BaseConfig):
|
||||
@@ -234,12 +300,18 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
decode_port: int = 8200
|
||||
"""Port for decode vLLM instances."""
|
||||
|
||||
prefill_env_overrides: dict[str, str] = {}
|
||||
prefill_env_vars: EnvVars = {}
|
||||
"""Extra environment variables exported only on prefill nodes."""
|
||||
|
||||
decode_env_overrides: dict[str, str] = {}
|
||||
decode_env_vars: EnvVars = {}
|
||||
"""Extra environment variables exported only on decode nodes."""
|
||||
|
||||
prefill_vllm_overrides: dict[str, Any] = {}
|
||||
"""Extra vLLM config options merged into --vllm-extra only for prefill ranks (SLURM only)."""
|
||||
|
||||
decode_vllm_overrides: dict[str, Any] = {}
|
||||
"""Extra vLLM config options merged into --vllm-extra only for decode ranks (SLURM only)."""
|
||||
|
||||
@property
|
||||
def num_nodes(self) -> int:
|
||||
return self.num_prefill_nodes + self.num_decode_nodes
|
||||
@@ -280,6 +352,9 @@ class InferenceConfig(BaseConfig):
|
||||
log: LogConfig = LogConfig()
|
||||
"""Logging configuration."""
|
||||
|
||||
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``."""
|
||||
|
||||
@@ -369,6 +444,18 @@ class InferenceConfig(BaseConfig):
|
||||
raise ValueError("Must use SLURM for multi-node / disaggregated deployment.")
|
||||
return self
|
||||
|
||||
@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)."""
|
||||
router = getattr(self.deployment, "router", None)
|
||||
if router is not None and router.type == "llm-d" and self.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. "
|
||||
"Use router type 'vllm-router' for routed-expert runs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_kv_cache_offload(self):
|
||||
if self.kv_cache_offload is not None:
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
import math
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import AliasChoices, Field, model_serializer, model_validator
|
||||
from pydantic_core.core_schema import SerializerFunctionWrapHandler
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import AliasChoices, Field, model_validator
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
from prime_rl.configs.algorithm import (
|
||||
AlgoConfig,
|
||||
GRPOAlgoConfig,
|
||||
)
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
ClientConfig,
|
||||
EnvVars,
|
||||
FileSystemTransportConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
@@ -41,6 +45,9 @@ class ModelConfig(BaseModelConfig):
|
||||
lora: LoRAConfig | None = None
|
||||
"""Per-run LoRA configuration. If None, LoRA is disabled."""
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
"""Client of the live deployment (``[orchestrator.model.client]``)."""
|
||||
|
||||
|
||||
class TrainSamplingConfig(BaseConfig):
|
||||
temperature: float = Field(1.0, ge=0)
|
||||
@@ -143,67 +150,12 @@ class EvalSamplingConfig(BaseConfig):
|
||||
return data
|
||||
|
||||
|
||||
class TokensLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["tokens"] = "tokens"
|
||||
|
||||
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on model completion tokens. Finite and non-negative."""
|
||||
|
||||
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
|
||||
|
||||
|
||||
class TurnsLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["turns"] = "turns"
|
||||
|
||||
|
||||
LengthPenaltyConfig: TypeAlias = Annotated[
|
||||
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class DefaultAdvantageConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
length_penalty: LengthPenaltyConfig | None = None
|
||||
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseConfig):
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
import_path: str
|
||||
"""Import path to the advantage function (e.g. ``my_module.my_advantage``)."""
|
||||
|
||||
kwargs: dict[str, Any] = Field(default_factory=dict)
|
||||
"""Kwargs forwarded to the advantage function."""
|
||||
|
||||
|
||||
AdvantageConfig: TypeAlias = Annotated[
|
||||
DefaultAdvantageConfig | CustomAdvantageConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class EnvConfig(BaseConfig):
|
||||
id: str = "reverse-text"
|
||||
"""Registered verifiers environment ID (e.g. ``math-env``, ``primeintellect/math-env``). May include an ``@version`` suffix for installation."""
|
||||
|
||||
class EnvConfig(vf.EnvServerConfig):
|
||||
name: str | None = None
|
||||
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the ``id`` without ``@version``. Must be unique across all envs in the same group."""
|
||||
|
||||
args: dict = {}
|
||||
"""Keyword arguments forwarded to ``vf.load_environment``. See the environment's docstring for accepted args."""
|
||||
|
||||
extra_env_kwargs: dict[str, Any] = {}
|
||||
"""Extra kwargs passed to the env (e.g. ``seq_len``, ``max_total_completion_tokens``). Auto-populated by the orchestrator; user overrides are generally discouraged. The main use case is matching ``extra_env_kwargs`` when running an env in an isolated environment server."""
|
||||
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
|
||||
|
||||
address: str | None = None
|
||||
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically."""
|
||||
|
||||
num_workers: int | Literal["auto"] = "auto"
|
||||
"""Worker processes for the spawned env server. ``auto`` scales to 1 worker per 256 concurrent rollouts. Ignored when ``address`` is set."""
|
||||
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically. The ``pool`` sizes the spawned server."""
|
||||
|
||||
ratio: float | None = Field(None, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
|
||||
@@ -211,41 +163,53 @@ class EnvConfig(BaseConfig):
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Times the env server retries a failed rollout before returning an error."""
|
||||
|
||||
max_total_completion_tokens: int = -1
|
||||
"""Maximum total completion tokens across all turns in a multi-turn rollout. ``-1`` disables. Auto-populated into ``extra_env_kwargs``."""
|
||||
|
||||
timeout: float | None = Field(None, validation_alias=AliasChoices("timeout", "timeout_seconds"))
|
||||
"""Per-rollout wall-clock timeout in seconds. None disables."""
|
||||
|
||||
state_columns: list[str] = []
|
||||
"""Extra ``State`` fields to persist into the saved rollout records (in addition to the always-saved ``trajectory`` and ``sampling_args``). Values must be JSON-serializable."""
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _migrate_num_workers(cls, data):
|
||||
"""Back-compat: the removed ``num_workers`` maps onto ``pool`` — an int becomes a
|
||||
fixed ``static`` pool, ``"auto"`` falls through to the default ``elastic`` pool. An
|
||||
explicit ``pool`` always wins."""
|
||||
if isinstance(data, dict) and "num_workers" in data:
|
||||
num_workers = data.pop("num_workers")
|
||||
if "pool" not in data and num_workers != "auto":
|
||||
data["pool"] = {"type": "static", "num_workers": num_workers}
|
||||
return data
|
||||
|
||||
@property
|
||||
def stripped_id(self) -> str:
|
||||
"""Environment ID without the @version suffix."""
|
||||
return self.id.split("@")[0]
|
||||
def is_legacy(self) -> bool:
|
||||
"""A v0/legacy env (run via the bridge): an ``id`` is set and no v1 ``taskset`` is."""
|
||||
return not self.taskset.id
|
||||
|
||||
@property
|
||||
def env_id(self) -> str:
|
||||
"""The env identifier — the v1 taskset id (v1) or the legacy env id (v0)."""
|
||||
return self.taskset.id or self.id or ""
|
||||
|
||||
@property
|
||||
def resolved_name(self) -> str:
|
||||
return self.name or self.stripped_id
|
||||
return self.name or self.env_id
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env_name(self):
|
||||
if self.resolved_name == "all":
|
||||
def validate_env(self):
|
||||
if not self.taskset.id and not self.id:
|
||||
raise ValueError('no env configured — set taskset = { id = "<id>" } (v1) or id = "<id>" (v0/legacy)')
|
||||
if self.resolved_name == "agg":
|
||||
raise ValueError(
|
||||
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
|
||||
'Environment name "agg" is reserved for cross-env metric aggregation. Use a different name or id.'
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_max_total_completion_tokens(self):
|
||||
self.extra_env_kwargs["max_total_completion_tokens"] = self.max_total_completion_tokens
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_timeout(self):
|
||||
if self.timeout is not None:
|
||||
self.extra_env_kwargs["timeout_seconds"] = self.timeout
|
||||
def resolve_legacy_env_kwargs(self):
|
||||
"""For a v0/legacy env, surface the v1 knobs the legacy bridge applies via
|
||||
``extra_env_kwargs`` (``env.set_kwargs(...)``): the per-rollout wall-clock timeout and
|
||||
the multi-turn completion-token budget. (``max_seq_len`` is added per train run in
|
||||
``OrchestratorConfig.resolve_env_config``, which knows ``seq_len``.)"""
|
||||
if self.is_legacy:
|
||||
if self.timeout.rollout is not None:
|
||||
self.extra_env_kwargs["timeout_seconds"] = self.timeout.rollout
|
||||
if self.max_output_tokens is not None:
|
||||
self.extra_env_kwargs["max_total_completion_tokens"] = self.max_output_tokens
|
||||
return self
|
||||
|
||||
|
||||
@@ -257,10 +221,10 @@ class TrainEnvConfig(EnvConfig):
|
||||
"""Rollouts generated per example for GRPO group-relative advantages.
|
||||
Inherits from ``orchestrator.group_size`` when unset."""
|
||||
|
||||
advantage: AdvantageConfig | None = None
|
||||
"""Advantage strategy for this env's GRPO groups. Inherits from the top-level
|
||||
``orchestrator.advantage`` when unset; set a different ``default``/``custom``
|
||||
config to give this env its own advantage computation."""
|
||||
algo: AlgoConfig | None = None
|
||||
"""Training algorithm for this env. Inherits from the top-level
|
||||
``orchestrator.algo`` when unset; set ``type`` (and its params) to give
|
||||
this env its own algorithm."""
|
||||
|
||||
|
||||
class EvalEnvConfig(EnvConfig):
|
||||
@@ -278,21 +242,19 @@ class EvalEnvConfig(EnvConfig):
|
||||
|
||||
|
||||
class TrainConfig(BaseConfig):
|
||||
env: list[TrainEnvConfig] = [TrainEnvConfig()]
|
||||
env: list[TrainEnvConfig] = Field(default_factory=list)
|
||||
"""Training environments."""
|
||||
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Shared training sampling configuration."""
|
||||
|
||||
num_workers: int | Literal["auto"] = "auto"
|
||||
"""Default worker processes for env servers. Can be overridden per env."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Default retries for failed rollouts. Can be overridden per env."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_workers, and max_retries."""
|
||||
"""Resolve per-env overrides: inherit group-level sampling and max_retries (the
|
||||
worker ``pool`` is configured per env, defaulting to elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
if "sampling" not in env.model_fields_set:
|
||||
@@ -300,8 +262,6 @@ class TrainConfig(BaseConfig):
|
||||
else:
|
||||
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
|
||||
env.sampling = TrainSamplingConfig(**merged)
|
||||
if "num_workers" not in env.model_fields_set:
|
||||
env.num_workers = self.num_workers
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
return self
|
||||
@@ -327,7 +287,7 @@ class TrainConfig(BaseConfig):
|
||||
|
||||
|
||||
class EvalConfig(BaseConfig):
|
||||
env: list[EvalEnvConfig] = [EvalEnvConfig()]
|
||||
env: list[EvalEnvConfig] = Field(default_factory=list)
|
||||
"""Evaluation environments."""
|
||||
|
||||
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
|
||||
@@ -339,9 +299,6 @@ class EvalConfig(BaseConfig):
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
|
||||
"""Default rollouts per example. Can be overridden per env."""
|
||||
|
||||
num_workers: int | Literal["auto"] = "auto"
|
||||
"""Default worker processes for env servers. Can be overridden per env."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Default retries for failed rollouts. Can be overridden per env."""
|
||||
|
||||
@@ -354,7 +311,8 @@ class EvalConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_workers, max_retries, num_examples, group_size, and interval. Then resolve auto num_workers."""
|
||||
"""Resolve per-env overrides: inherit group-level sampling, max_retries, num_examples,
|
||||
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
if "sampling" not in env.model_fields_set:
|
||||
@@ -368,17 +326,8 @@ class EvalConfig(BaseConfig):
|
||||
env.group_size = self.group_size
|
||||
if "interval" not in env.model_fields_set:
|
||||
env.interval = self.interval
|
||||
if "num_workers" not in env.model_fields_set:
|
||||
env.num_workers = self.num_workers
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
# Resolve auto num_workers now that num_examples and group_size are set
|
||||
if env.num_workers == "auto":
|
||||
if env.num_examples == -1:
|
||||
env.num_workers = 4
|
||||
else:
|
||||
max_concurrent = env.num_examples * env.group_size
|
||||
env.num_workers = max(1, math.ceil(max_concurrent / 256))
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -498,50 +447,33 @@ class OrchestratorExperimentalConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class RolloutModelConfig(BaseConfig):
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
|
||||
|
||||
class OrchestratorConfig(BaseConfig):
|
||||
training_mode: Literal["rl", "opd", "sft"] = "rl"
|
||||
"""Training mode. ``rl``: student generates rollouts, no teacher. ``opd``: student generates rollouts, teacher computes logprobs (teacher_tau > 0). ``sft``: teacher generates rollouts, student inference pool used for evals and weight sync."""
|
||||
algo: AlgoConfig = GRPOAlgoConfig()
|
||||
"""Training algorithm: sampling plus the per-token training signal (credit
|
||||
assignment and loss routing, fused — its ``type`` names the algorithm).
|
||||
Defaults to ``grpo``. Override per env via ``[[orchestrator.train.env]]``'s
|
||||
``algo``."""
|
||||
|
||||
student: RolloutModelConfig = Field(RolloutModelConfig(), validation_alias=AliasChoices("student", "model"))
|
||||
"""Student rollout participant (model + client) — the model being trained."""
|
||||
|
||||
teacher: RolloutModelConfig | None = Field(None, validation_alias=AliasChoices("teacher", "teacher_model"))
|
||||
"""Teacher rollout participant (model + client). Role depends on ``training_mode``: ``opd`` — teacher computes logprobs; ``sft`` — teacher generates rollouts."""
|
||||
model: ModelConfig = ModelConfig()
|
||||
"""The model being trained: its model fields plus the client of the live
|
||||
vLLM deployment (``[orchestrator.model] name = ...`` with
|
||||
``[orchestrator.model.client]``). Algorithm components reference it as
|
||||
``"policy"``."""
|
||||
|
||||
train: TrainConfig = TrainConfig()
|
||||
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
renderer: RendererConfig | None = AutoRendererConfig()
|
||||
"""Typed renderer config (``renderers.RendererConfig`` discriminated
|
||||
union). Defaults to ``"auto"``, which resolves from
|
||||
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. ``None``
|
||||
opts into MITO (``openai_chat_completions``)."""
|
||||
renderer: RendererConfig = AutoRendererConfig()
|
||||
"""Typed renderer config (``renderers.RendererConfig`` discriminated union), required —
|
||||
training is renderer-only. Defaults to ``"auto"``, which resolves from
|
||||
``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. Only meaningful when ``renderer`` is not ``None``."""
|
||||
|
||||
@model_serializer(mode="wrap")
|
||||
def _preserve_mito_renderer(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
|
||||
"""Emit ``renderer = "None"`` (string) when MITO so
|
||||
``model_dump(exclude_none=True)`` round-trips: dumped TOML has
|
||||
``renderer = "None"``, and on reload
|
||||
``BaseConfig._none_str_to_none`` coerces it back to ``None``.
|
||||
Without this, a MITO orchestrator config saved to
|
||||
``control/orch.toml`` would lose the renderer key entirely and
|
||||
reload as the default ``AutoRendererConfig()`` (TITO)."""
|
||||
result = handler(self)
|
||||
if self.renderer is None:
|
||||
result["renderer"] = "None"
|
||||
return result
|
||||
serializes."""
|
||||
|
||||
optim: OptimizerConfig = OptimizerConfig()
|
||||
"""Per-run optimizer configuration for multi-run training."""
|
||||
@@ -549,8 +481,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
eval: EvalConfig | None = None
|
||||
"""Evaluation configuration."""
|
||||
|
||||
advantage: AdvantageConfig | None = DefaultAdvantageConfig()
|
||||
|
||||
pre_batch_filters: list[FilterConfig] = [
|
||||
GibberishFilterConfig(enforce=False),
|
||||
RepetitionFilterConfig(enforce=False),
|
||||
@@ -571,6 +501,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for the orchestrator process(es). Merged on top of the launcher defaults."""
|
||||
|
||||
wandb: WandbWithExtrasConfig | None = None
|
||||
|
||||
prime_monitor: PrimeMonitorConfig | None = None
|
||||
@@ -579,7 +512,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
"""Collect inference-server metrics (requires wandb)."""
|
||||
|
||||
inference_metrics_roles: list[Literal["prefill", "decode"]] | None = None
|
||||
"""Role for each student admin client when collecting P/D inference metrics."""
|
||||
"""Role for each policy admin client when collecting P/D inference metrics."""
|
||||
|
||||
ckpt: CheckpointConfig | None = None
|
||||
"""Checkpoint configuration."""
|
||||
@@ -630,72 +563,8 @@ class OrchestratorConfig(BaseConfig):
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
env_install_prerelease: bool = False
|
||||
"""Allow pre-release versions when installing environments (e.g. ``verifiers>=0.1.12.dev5``). Passes ``--prerelease`` to ``prime env install``."""
|
||||
|
||||
experimental: OrchestratorExperimentalConfig = OrchestratorExperimentalConfig()
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def fold_student_shortcuts(cls, data: Any) -> Any:
|
||||
"""Accept top-level ``[orchestrator.model]`` / ``[orchestrator.client]``
|
||||
as shorthand for the student sub-config. Useful for ergonomic rl configs
|
||||
where ``[orchestrator.student.*]`` is overkill, and required for
|
||||
pre-refactor configs that used the flat layout to keep parsing:
|
||||
|
||||
- [orchestrator.client.*] -> [orchestrator.student.client.*]
|
||||
- [orchestrator.model.<k>] -> [orchestrator.student.model.<k>]
|
||||
(where <k> is any ModelConfig field)
|
||||
|
||||
Teacher must always be configured under [orchestrator.teacher.*]
|
||||
(no equivalent shortcut), because rl mode forbids a teacher and we
|
||||
don't want the same shortcut to silently route to two different roles.
|
||||
"""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
|
||||
def deep_merge(dst: dict, src: dict) -> None:
|
||||
"""In-place recursive merge of ``src`` into ``dst``. ``src`` wins at the leaf."""
|
||||
for k, v in src.items():
|
||||
if isinstance(v, dict) and isinstance(dst.get(k), dict):
|
||||
deep_merge(dst[k], v)
|
||||
else:
|
||||
dst[k] = v
|
||||
|
||||
# 1. Re-nest top-level [orchestrator.client] under student.client.
|
||||
legacy_client = data.pop("client", None)
|
||||
if isinstance(legacy_client, dict):
|
||||
student = data.setdefault("student", {})
|
||||
if isinstance(student, dict):
|
||||
deep_merge(student.setdefault("client", {}), legacy_client)
|
||||
else:
|
||||
# Mismatched types - put it back and let pydantic surface the error.
|
||||
data["client"] = legacy_client
|
||||
|
||||
# 2. Consolidate the legacy `model` alias into `student` so the
|
||||
# flat-layout fix-up below sees a single target. Deep-merge with the
|
||||
# legacy keys winning so a CLI `--model.<k>` overrides TOML `student.model.<k>`.
|
||||
legacy_model = data.pop("model", None)
|
||||
if legacy_model is not None:
|
||||
existing = data.get("student")
|
||||
if existing is None:
|
||||
data["student"] = legacy_model
|
||||
elif isinstance(existing, dict) and isinstance(legacy_model, dict):
|
||||
deep_merge(existing, legacy_model)
|
||||
else:
|
||||
# Mismatched types - put it back and let pydantic surface the error.
|
||||
data["model"] = legacy_model
|
||||
|
||||
# 3. Re-nest flat ModelConfig keys under student.model.
|
||||
model_only_keys = set(ModelConfig.model_fields)
|
||||
student = data.get("student")
|
||||
if isinstance(student, dict):
|
||||
flat = {k: student.pop(k) for k in list(student) if k in model_only_keys}
|
||||
if flat:
|
||||
student.setdefault("model", {}).update(flat)
|
||||
|
||||
return data
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _env_to_train(cls, data: Any) -> Any:
|
||||
@@ -726,15 +595,15 @@ class OrchestratorConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_tokenizer(self):
|
||||
if self.tokenizer.name is None:
|
||||
self.tokenizer.name = self.student.model.name
|
||||
self.tokenizer.name = self.model.name
|
||||
if self.tokenizer.trust_remote_code is None:
|
||||
self.tokenizer.trust_remote_code = self.student.model.trust_remote_code
|
||||
self.tokenizer.trust_remote_code = self.model.trust_remote_code
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_session_headers(self):
|
||||
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
|
||||
self.student.client.extra_headers_from_state.setdefault("X-Session-ID", "trajectory_id")
|
||||
self.model.client.extra_headers_from_state.setdefault("X-Session-ID", "trajectory_id")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -758,49 +627,32 @@ class OrchestratorConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _force_no_renderer_for_sft(self):
|
||||
"""Teacher-backed SFT rolls out via the teacher's plain chat-completions
|
||||
endpoint; the renderer client doesn't apply. When no teacher is
|
||||
configured, SFT uses the student rollout path and keeps the renderer."""
|
||||
if self.training_mode == "sft" and self.teacher is not None:
|
||||
self.renderer = None
|
||||
def inherit_env_algorithms(self):
|
||||
"""Envs without their own algorithm inherit the top-level one.
|
||||
Declared before any validator that reads ``algo``."""
|
||||
for env_cfg in self.train.env:
|
||||
if env_cfg.algo is None:
|
||||
env_cfg.algo = self.algo.model_copy(deep=True)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_training_mode(self):
|
||||
"""Enforce training mode invariants that involve only orchestrator fields."""
|
||||
has_teacher = self.teacher is not None
|
||||
if self.training_mode == "rl" and has_teacher:
|
||||
raise ValueError("orchestrator.teacher must not be set when training_mode = 'rl'.")
|
||||
if self.training_mode == "opd" and not has_teacher:
|
||||
raise ValueError("orchestrator.teacher must be configured when training_mode = 'opd'.")
|
||||
return self
|
||||
@property
|
||||
def any_policy_sourced(self) -> bool:
|
||||
"""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.env)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_pool_size(self):
|
||||
"""``pool_size`` is only meaningful when the renderer is enabled
|
||||
(``renderer is not None``). Reject otherwise so callers don't
|
||||
silently pass it and wonder why it's ignored."""
|
||||
if self.renderer is None and self.pool_size is not None:
|
||||
"""``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 "
|
||||
"orchestrator.renderer is None (MITO mode). Either configure a renderer "
|
||||
"or remove pool_size."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def vlm_requires_renderer(self):
|
||||
"""VLMs (``[model.vlm]`` block set) must go through the renderer.
|
||||
|
||||
The renderer owns the processor per-slot, produces byte-identical
|
||||
tokens, and ships generic ``mm_kwargs`` keyed by whatever the
|
||||
model's forward signature expects.
|
||||
"""
|
||||
if self.student.model.vlm is not None and self.renderer is None:
|
||||
raise ValueError(
|
||||
"orchestrator.renderer must be set when model.vlm is set. "
|
||||
"VLMs must go through a renderer (e.g. Qwen3VLRenderer) that owns the processor."
|
||||
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
|
||||
|
||||
@@ -817,11 +669,11 @@ class OrchestratorConfig(BaseConfig):
|
||||
``DefaultRendererConfig.tool_parser`` is configured. Surface at
|
||||
config time so ``--dry-run`` reports the error.
|
||||
"""
|
||||
if self.renderer is None or self.renderer.name != "auto":
|
||||
if self.renderer.name != "auto":
|
||||
return self
|
||||
from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
model_id = self.tokenizer.name or self.student.model.name
|
||||
model_id = self.tokenizer.name or self.model.name
|
||||
if model_id in MODEL_RENDERER_MAP:
|
||||
return self
|
||||
raise ValueError(
|
||||
@@ -835,9 +687,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
f"(b) [orchestrator.renderer] name=<model-specific renderer> — "
|
||||
f"if {model_id!r} is template-identical to a mapped family "
|
||||
f"(and ideally also add it upstream to "
|
||||
f"renderers.base.MODEL_RENDERER_MAP). "
|
||||
f"(c) orchestrator.renderer='none' — opt out of the renderer "
|
||||
f"client entirely (MITO)."
|
||||
f"renderers.base.MODEL_RENDERER_MAP)."
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -880,17 +730,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
if "group_size" not in env_cfg.model_fields_set:
|
||||
env_cfg.group_size = self.group_size
|
||||
|
||||
# Propagate the top-level ``advantage`` into each train env that didn't set its own.
|
||||
for env_cfg in self.train.env:
|
||||
if "advantage" not in env_cfg.model_fields_set:
|
||||
env_cfg.advantage = self.advantage
|
||||
|
||||
# Resolve train env num_workers from max_inflight_rollouts
|
||||
for env_cfg in self.train.env:
|
||||
if env_cfg.num_workers == "auto":
|
||||
assert self.max_inflight_rollouts is not None
|
||||
env_cfg.num_workers = max(1, math.ceil(self.max_inflight_rollouts / 256))
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -909,12 +748,17 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_config(self):
|
||||
"""Populate extra_env_kwargs and vLLM sampling defaults from top-level fields."""
|
||||
is_vllm = self.training_mode != "sft"
|
||||
"""Set vLLM sampling defaults + legacy env kwargs on each train env from top-level fields."""
|
||||
for env in self.train.env:
|
||||
env.extra_env_kwargs.update(max_seq_len=self.seq_len)
|
||||
if is_vllm:
|
||||
# Policy-sourced rollouts hit our vLLM server; frozen-sourced
|
||||
# rollouts may hit external OAI endpoints that reject these knobs.
|
||||
assert env.algo is not None
|
||||
if env.algo.sampling.source == "policy":
|
||||
env.sampling.extra_body.setdefault("top_k", -1)
|
||||
env.sampling.extra_body.setdefault("min_p", 0.0)
|
||||
env.sampling.extra_body.setdefault("return_token_ids", True)
|
||||
if env.is_legacy:
|
||||
# v0 env: cap per-turn response tokens to the training budget (the legacy
|
||||
# bridge applies extra_env_kwargs via env.set_kwargs).
|
||||
env.extra_env_kwargs["max_seq_len"] = self.seq_len
|
||||
return self
|
||||
|
||||
@@ -16,6 +16,7 @@ from prime_rl.configs.orchestrator import (
|
||||
OrchestratorConfig,
|
||||
)
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
SlurmConfig,
|
||||
VLMConfig,
|
||||
)
|
||||
@@ -167,6 +168,9 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Training nodes per FSDP island. Auto-sets ``trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
|
||||
|
||||
orchestrator_on_inference: bool = False
|
||||
"""Run the orchestrator on the last inference node instead of trainer rank 0 (frees host RAM on the trainer node)."""
|
||||
|
||||
@property
|
||||
def total_infer_nodes(self) -> int:
|
||||
return self.num_infer_nodes * self.num_infer_replicas
|
||||
@@ -185,6 +189,9 @@ class RLConfig(BaseConfig):
|
||||
inference: InferenceConfig | None = None
|
||||
"""Inference server configuration. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."""
|
||||
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for every launched RL component. Component-specific env_vars override these."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Output directory. Should be unique per experiment."""
|
||||
|
||||
@@ -370,40 +377,40 @@ class RLConfig(BaseConfig):
|
||||
if self.trainer.weight_broadcast.type == "nccl":
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
|
||||
if self.orchestrator.student.model.lora is None:
|
||||
if self.orchestrator.model.lora is None:
|
||||
from prime_rl.configs.orchestrator import LoRAConfig
|
||||
|
||||
self.orchestrator.student.model.lora = LoRAConfig()
|
||||
self.orchestrator.model.lora = LoRAConfig()
|
||||
|
||||
if (
|
||||
self.orchestrator.student.model.lora.rank is not None
|
||||
and self.orchestrator.student.model.lora.rank != self.trainer.model.lora.rank
|
||||
self.orchestrator.model.lora.rank is not None
|
||||
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
|
||||
):
|
||||
raise ValueError(
|
||||
f"orchestrator.student.model.lora.rank ({self.orchestrator.student.model.lora.rank}) conflicts with "
|
||||
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
|
||||
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
|
||||
f"Remove orchestrator.student.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
|
||||
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
|
||||
)
|
||||
|
||||
if (
|
||||
self.orchestrator.student.model.lora.alpha is not None
|
||||
and self.orchestrator.student.model.lora.alpha != self.trainer.model.lora.alpha
|
||||
self.orchestrator.model.lora.alpha is not None
|
||||
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
|
||||
):
|
||||
raise ValueError(
|
||||
f"orchestrator.student.model.lora.alpha ({self.orchestrator.student.model.lora.alpha}) conflicts with "
|
||||
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
|
||||
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
|
||||
f"Remove orchestrator.student.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
|
||||
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
|
||||
)
|
||||
|
||||
if self.orchestrator.student.model.lora.rank is None:
|
||||
self.orchestrator.student.model.lora.rank = self.trainer.model.lora.rank
|
||||
if self.orchestrator.model.lora.rank is None:
|
||||
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
|
||||
|
||||
if self.orchestrator.student.model.lora.alpha is None:
|
||||
self.orchestrator.student.model.lora.alpha = self.trainer.model.lora.alpha
|
||||
if self.orchestrator.model.lora.alpha is None:
|
||||
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
|
||||
|
||||
if self.orchestrator.student.model.lora.name is None:
|
||||
self.orchestrator.student.model.lora.name = (
|
||||
f"r{self.orchestrator.student.model.lora.rank}-a{self.orchestrator.student.model.lora.alpha}"
|
||||
if self.orchestrator.model.lora.name is None:
|
||||
self.orchestrator.model.lora.name = (
|
||||
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
|
||||
)
|
||||
|
||||
if self.inference is not None:
|
||||
@@ -435,6 +442,25 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@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).
|
||||
|
||||
Runs after ``auto_setup_router_replay`` so it also catches the
|
||||
``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:
|
||||
router = getattr(self.inference.deployment, "router", None)
|
||||
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 "
|
||||
"breaks P/D and is unverified for multi-node. Use router type 'vllm-router' "
|
||||
"for router-replay runs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_router_replay_without_kv_offload(self):
|
||||
if (
|
||||
@@ -601,19 +627,26 @@ class RLConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_inference_client(self):
|
||||
"""Auto-configure orchestrator student client from the inference server config.
|
||||
"""Auto-configure the orchestrator policy client from the inference server config.
|
||||
|
||||
For all modes, sets dp_rank_count from inference DP size. For SFT mode,
|
||||
also sets base_url - rl/opd rely on the ClientConfig default
|
||||
(``["http://localhost:8000/v1"]``) which already matches the auto-launched
|
||||
student vLLM at inference.server.port = 8000.
|
||||
Direct single-node runs expose all local DP ranks behind one base URL,
|
||||
so pin logical clients with ``X-data-parallel-rank``. Multi-node SLURM
|
||||
runs expose a vllm-router URL instead; the router balances across
|
||||
per-rank backend URLs and forwards request headers, so the orchestrator
|
||||
must not inject a DP-rank header there. When no train env samples from
|
||||
the policy (e.g. sft_distill), also set base_url — policy-sourced
|
||||
algorithms rely on the ClientConfig default (``["http://localhost:8000/v1"]``)
|
||||
which already matches the auto-launched policy vLLM at inference.server.port = 8000.
|
||||
"""
|
||||
if self.inference is None:
|
||||
return self
|
||||
client = self.orchestrator.student.client
|
||||
client = self.orchestrator.model.client
|
||||
if "dp_rank_count" not in client.model_fields_set:
|
||||
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
|
||||
if self.orchestrator.training_mode == "sft" and "base_url" not in client.model_fields_set:
|
||||
if self.deployment.type == "multi_node":
|
||||
client.dp_rank_count = 1
|
||||
else:
|
||||
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
|
||||
if not self.orchestrator.any_policy_sourced and "base_url" not in client.model_fields_set:
|
||||
host = self.inference.server.host or "localhost"
|
||||
port = self.inference.server.port
|
||||
client.base_url = [f"http://{host}:{port}/v1"]
|
||||
|
||||
@@ -6,6 +6,7 @@ from pydantic import Field, model_validator
|
||||
from renderers import RendererConfig
|
||||
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
HeartbeatConfig,
|
||||
SlurmConfig,
|
||||
TrainerLogConfig,
|
||||
@@ -173,6 +174,9 @@ class SFTExperimentalConfig(BaseConfig):
|
||||
class SFTConfig(BaseConfig):
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for the SFT trainer process(es). Merged on top of the launcher defaults."""
|
||||
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
renderer: RendererConfig | None = None
|
||||
@@ -347,18 +351,12 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_and_disable_chunked_loss(self):
|
||||
if isinstance(self.model.fused_lm_head_token_chunk_size, int):
|
||||
raise ValueError(
|
||||
"Chunked loss is not supported for SFT training yet, please set "
|
||||
"`model.fused_lm_head_token_chunk_size` to 'disabled'"
|
||||
)
|
||||
|
||||
self.model.fused_lm_head_token_chunk_size = "disabled"
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def ep_only_with_custom_impl(self):
|
||||
if self.model.ep > 1 and self.model.impl not in ("custom", "auto"):
|
||||
if self.model.ep != 1 and self.model.ep != "auto" and self.model.impl not in ("custom", "auto"):
|
||||
raise ValueError("EP is only supported with the custom implementation or auto mode")
|
||||
|
||||
return self
|
||||
|
||||
@@ -2,10 +2,30 @@ import os
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic import AfterValidator, Field, model_validator
|
||||
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
# Launcher-managed env vars that a component's `env_vars` must not set: GPU partitioning
|
||||
# and the single shared W&B run. The launcher always sets these last, so allowing them in
|
||||
# `env_vars` would be a silent no-op (or, on multi-node, a footgun) — reject them instead.
|
||||
PROTECTED_ENV_VARS = frozenset(
|
||||
{"CUDA_VISIBLE_DEVICES", "WANDB_SHARED_MODE", "WANDB_SHARED_RUN_ID", "WANDB_SHARED_LABEL"}
|
||||
)
|
||||
|
||||
|
||||
def reject_protected_env_vars(env_vars: dict[str, str]) -> dict[str, str]:
|
||||
clobbered = sorted(PROTECTED_ENV_VARS & env_vars.keys())
|
||||
if clobbered:
|
||||
raise ValueError(
|
||||
f"env_vars cannot set launcher-managed vars {clobbered} — set by the launcher, not overridable"
|
||||
)
|
||||
return env_vars
|
||||
|
||||
|
||||
EnvVars: TypeAlias = Annotated[dict[str, str], AfterValidator(reject_protected_env_vars)]
|
||||
"""A per-component `env_vars` mapping, validated to not clobber `PROTECTED_ENV_VARS`."""
|
||||
|
||||
|
||||
class SlurmConfig(BaseConfig):
|
||||
job_name: str = "prime-rl"
|
||||
@@ -83,10 +103,6 @@ class BaseModelConfig(BaseConfig):
|
||||
vlm: "VLMConfig | None" = None
|
||||
"""VLM configuration. Setting this enables vision-language model support."""
|
||||
|
||||
@property
|
||||
def is_vlm(self) -> bool:
|
||||
return self.vlm is not None
|
||||
|
||||
|
||||
class ElasticConfig(BaseConfig):
|
||||
hostname: str
|
||||
@@ -100,12 +116,6 @@ class ElasticConfig(BaseConfig):
|
||||
|
||||
|
||||
class ClientConfig(BaseConfig):
|
||||
timeout: int = 1200
|
||||
"""Request timeout in seconds."""
|
||||
|
||||
connect_timeout: float = 30.0
|
||||
"""TCP connect timeout in seconds for inference API requests."""
|
||||
|
||||
wait_for_ready_timeout: int = 1800
|
||||
"""Seconds to wait at startup for the inference pool to become ready. Applies to both the static health check and elastic DNS-based discovery."""
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
EnvVars,
|
||||
FileSystemTransportConfig,
|
||||
HeartbeatConfig,
|
||||
MetricsServerConfig,
|
||||
@@ -122,19 +123,19 @@ class ModelConfig(BaseModelConfig):
|
||||
attn: AttnImplementation = "flash_attention_2"
|
||||
"""Attention implementation. With CP enabled, ring attention uses the matching kernel family (FA2/FA3/FA4)."""
|
||||
|
||||
compile: CompileConfig | None = None
|
||||
compile: CompileConfig | None = CompileConfig()
|
||||
"""Compile the model with ``torch.compile``."""
|
||||
|
||||
ac: ActivationCheckpointConfig | None = None
|
||||
ac: ActivationCheckpointConfig | None = ActivationCheckpointConfig()
|
||||
"""Activation checkpointing configuration. If None, activation checkpointing is disabled."""
|
||||
|
||||
ac_offloading: ActivationOffloadingConfig | None = None
|
||||
ac_offloading: ActivationOffloadingConfig | None = ActivationOffloadingConfig()
|
||||
"""Activation offloading configuration. If None, activation offloading is disabled."""
|
||||
|
||||
fsdp_cpu_offload: bool = False
|
||||
"""Enable FSDP CPU offloading for parameters, gradients, and optimizer states. Uses pinned memory for efficient CPU↔GPU transfers."""
|
||||
|
||||
optim_cpu_offload: bool = False
|
||||
optim_cpu_offload: bool = True
|
||||
"""Offload only optimizer states (momentum, variance) to CPU, keeping weights on GPU. Avoids the H2D all-gather overhead of FSDP CPU offload while still saving GPU memory."""
|
||||
|
||||
reshard_after_forward: bool = True
|
||||
@@ -143,8 +144,8 @@ class ModelConfig(BaseModelConfig):
|
||||
dp_replicate: int = 1
|
||||
"""Data parallel dim where model weights are replicated."""
|
||||
|
||||
ep: int = 1
|
||||
"""Expert parallelism degree for MoE layers. 1 disables EP."""
|
||||
ep: int | Literal["auto"] = "auto"
|
||||
"""Expert parallelism degree for MoE layers. 1 disables EP. ``auto`` resolves to ``min(fsdp_island_size, 8)`` for MoE models (where ``fsdp_island_size = world_size // dp_replicate``), and to 1 for non-MoE models. Set an explicit integer to override."""
|
||||
|
||||
ep_comm_backend: EPCommBackend = "torch"
|
||||
"""Communication backend for expert parallelism. ``torch`` uses TorchTitan all-to-all collectives; ``deepep`` uses DeepEP custom kernels."""
|
||||
@@ -188,8 +189,8 @@ class ModelConfig(BaseModelConfig):
|
||||
debug: DebugModelConfig = DebugModelConfig()
|
||||
"""Debugging knobs for the model and distributed training."""
|
||||
|
||||
fused_lm_head_token_chunk_size: int | Literal["auto", "disabled"] = "disabled"
|
||||
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``auto`` auto-enables (RL training picks 8192); ``disabled`` uses the vanilla LM head. Integer values aren't supported for SFT training."""
|
||||
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 1024
|
||||
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. SFT training silently disables this (not supported yet)."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
@@ -258,7 +259,7 @@ class ModelConfig(BaseModelConfig):
|
||||
if self.ep_comm_backend == "torch":
|
||||
return self
|
||||
|
||||
if self.ep <= 1:
|
||||
if isinstance(self.ep, int) and self.ep <= 1:
|
||||
raise ValueError(f"model.ep_comm_backend='{self.ep_comm_backend}' requires model.ep > 1.")
|
||||
|
||||
return self
|
||||
@@ -425,6 +426,18 @@ class DefaultLossConfig(BaseConfig):
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class IPOLossConfig(BaseConfig):
|
||||
type: Literal["ipo"] = "ipo"
|
||||
ipo_threshold: float = Field(0.1, ge=0)
|
||||
"""Upper DPPO masking threshold."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
kl_tau: float = Field(1e-3, ge=0)
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class CustomLossConfig(BaseConfig):
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
@@ -435,7 +448,7 @@ class CustomLossConfig(BaseConfig):
|
||||
"""Kwargs forwarded to the loss function."""
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
@@ -490,15 +503,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class TokenExportConfig(BaseConfig):
|
||||
"""Configures per-token rollout exports from the RL trainer."""
|
||||
|
||||
|
||||
class TrainerExperimentalConfig(BaseConfig):
|
||||
token_export: TokenExportConfig | None = None
|
||||
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
|
||||
|
||||
|
||||
class TrainerConfig(BaseConfig):
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
@@ -507,7 +511,7 @@ class TrainerConfig(BaseConfig):
|
||||
data: DataLoaderConfig = DataLoaderConfig()
|
||||
|
||||
loss: LossConfig = DefaultLossConfig()
|
||||
"""Loss config for rl-mode batches. opd and sft batches dispatch to their own loss fns unconditionally and do not read this."""
|
||||
"""Loss config for the rl loss component (see ``setup_rl_loss_fn``). The ce / ref_kl components are fixed and do not read this."""
|
||||
|
||||
optim: OptimizerConfig = AdamWConfig()
|
||||
|
||||
@@ -562,7 +566,11 @@ class TrainerConfig(BaseConfig):
|
||||
max_concurrent_runs: int = Field(1, ge=1)
|
||||
"""Maximum number of concurrent runs to allow. If 1, only one run may run at a time."""
|
||||
|
||||
experimental: TrainerExperimentalConfig = TrainerExperimentalConfig()
|
||||
enable_token_export: bool = False
|
||||
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
|
||||
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for the trainer process(es). Merged on top of the launcher defaults."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
@@ -653,16 +661,9 @@ class TrainerConfig(BaseConfig):
|
||||
self.tokenizer.trust_remote_code = self.model.trust_remote_code
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_fused_lm_head_token_chunk_size(self):
|
||||
if self.model.fused_lm_head_token_chunk_size == "auto":
|
||||
self.model.fused_lm_head_token_chunk_size = 8192
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def ep_only_with_custom_impl(self):
|
||||
if self.model.ep > 1 and self.model.impl not in ("custom", "auto"):
|
||||
if self.model.ep != 1 and self.model.ep != "auto" and self.model.impl not in ("custom", "auto"):
|
||||
raise ValueError("EP is only supported with the custom implementation or auto mode")
|
||||
|
||||
return self
|
||||
|
||||
@@ -22,6 +22,8 @@ REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
(re.compile(r"^zai-org/GLM-"), "glm45"),
|
||||
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
|
||||
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Super"), "nemotron_v3"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Nano"), "nano_v3"),
|
||||
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
|
||||
# Only Qwen3 Thinking models reason — Instruct/base models do not.
|
||||
(re.compile(r"^Qwen/Qwen3-.*Thinking"), "deepseek_r1"),
|
||||
|
||||
@@ -22,9 +22,6 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
The original footgun the mutex was designed to catch — a sub-config
|
||||
value silently winning over a later CLI shared override — is still
|
||||
caught because that scenario produces *different* values.
|
||||
- **Aliased sub-paths**: ``orchestrator.model.*`` is checked against its
|
||||
``orchestrator.student.model.*`` alias (and vice versa), so the
|
||||
conflict fires regardless of which spelling the user wrote.
|
||||
"""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
@@ -51,36 +48,34 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
|
||||
conflicts: list[tuple[str, str]] = []
|
||||
|
||||
def propagate(shared_path: str, *targets: str, aliases: tuple[str, ...] = ()) -> None:
|
||||
"""Verbatim shared → targets. Records *disagreeing* overlap (incl. alias
|
||||
spellings) into ``conflicts`` and fills each target if the shared value
|
||||
is set. Matching values are silently accepted so the materialized
|
||||
config round-trips through re-load.
|
||||
def propagate(shared_path: str, *targets: str) -> None:
|
||||
"""Verbatim shared → targets. Records *disagreeing* overlap into
|
||||
``conflicts`` and fills each target if the shared value is set. Matching
|
||||
values are silently accepted so the materialized config round-trips
|
||||
through re-load.
|
||||
"""
|
||||
value = get(shared_path)
|
||||
if value is None:
|
||||
return
|
||||
for sub in (*targets, *aliases):
|
||||
sub_value = get(sub)
|
||||
for target in targets:
|
||||
sub_value = get(target)
|
||||
if sub_value is not None and sub_value != value:
|
||||
conflicts.append((shared_path, sub))
|
||||
conflicts.append((shared_path, target))
|
||||
for target in targets:
|
||||
fill(target, value)
|
||||
|
||||
# [model] → trainer / orchestrator (student, via AliasChoices) / inference.
|
||||
# [model] → trainer / orchestrator / inference.
|
||||
propagate(
|
||||
"model.name",
|
||||
"trainer.model.name",
|
||||
"inference.model.name",
|
||||
"orchestrator.model.name",
|
||||
aliases=("orchestrator.student.model.name",),
|
||||
)
|
||||
propagate(
|
||||
"model.vlm",
|
||||
"trainer.model.vlm",
|
||||
"inference.model.vlm",
|
||||
"orchestrator.model.vlm",
|
||||
aliases=("orchestrator.student.model.vlm",),
|
||||
)
|
||||
|
||||
# [log]
|
||||
@@ -224,18 +219,18 @@ 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.student.model.name:
|
||||
if inference.model.name != orchestrator.model.name:
|
||||
raise ValueError(
|
||||
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.student.model.name}) are not the same. "
|
||||
f"Inference model name ({inference.model.name}) 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
|
||||
|
||||
if trainer.model.name.startswith("Jackmin108/"): # The TT MoE models will have a different name on the orchestrator
|
||||
return
|
||||
if trainer.model.name != orchestrator.student.model.name:
|
||||
if trainer.model.name != orchestrator.model.name:
|
||||
raise ValueError(
|
||||
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.student.model.name}) are not the same. Please specify the same model name for both."
|
||||
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. Please specify the same model name for both."
|
||||
)
|
||||
|
||||
|
||||
|
||||
+122
-53
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "prime-rl"
|
||||
version = "0.5.0"
|
||||
version = "0.6.0"
|
||||
description = "Async RL Training at Scale"
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
@@ -19,7 +19,7 @@ dependencies = [
|
||||
"torchaudio",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers==5.6.2",
|
||||
"vllm>=0.22.0",
|
||||
"vllm>=0.23.0",
|
||||
"mooncake-transfer-engine>=0.3.10.post2",
|
||||
"wandb>=0.26.1",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
@@ -33,13 +33,16 @@ dependencies = [
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"torchtitan",
|
||||
"verifiers",
|
||||
"verifiers>=0.1.15.dev405",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
"flash-linear-attention",
|
||||
"nvidia-ml-py>=12.575.51",
|
||||
"pybase64>=1.4.2",
|
||||
"orjson>=3.10",
|
||||
"pandas>=2.0",
|
||||
"msgspec>=0.18",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
@@ -63,35 +66,69 @@ flash-attn-cute = [
|
||||
"flash-attn-4",
|
||||
]
|
||||
envs = [
|
||||
"aime2024",
|
||||
"aime2025",
|
||||
"aime24-v1",
|
||||
"aime25-v1",
|
||||
"aime26-v1",
|
||||
"alphabet-sort",
|
||||
"code-env",
|
||||
"color-codeword",
|
||||
"deepdive",
|
||||
"alphabet-sort-v1",
|
||||
"apex-shortlist-v1",
|
||||
"browsecomp-v1",
|
||||
"code-golf-v1",
|
||||
"color-codeword-v1",
|
||||
"deepdive-v1",
|
||||
"deepwiki-v1",
|
||||
"forth-lang-v1",
|
||||
"general-agent",
|
||||
"gpqa",
|
||||
"hle",
|
||||
"ifeval",
|
||||
"livecodebench",
|
||||
"general-agent-v1",
|
||||
"glossary-v1",
|
||||
"gpqa-v1",
|
||||
"graphwalks-v1",
|
||||
"gsm8k-v1",
|
||||
"i3-code-v1",
|
||||
"i3-science-v1",
|
||||
"ifbench-v1",
|
||||
"ifeval-v1",
|
||||
"lean-v1",
|
||||
"livecodebench-v1",
|
||||
"logic-env",
|
||||
"longcot-mini-v1",
|
||||
"longcot-v1",
|
||||
"math-env",
|
||||
"math-env-v1",
|
||||
"math-python",
|
||||
"math500",
|
||||
"mini-swe-agent-plus",
|
||||
"mmlu-pro",
|
||||
"opencode-cp",
|
||||
"opencode-deepdive",
|
||||
"opencode-math",
|
||||
"opencode-science",
|
||||
"opencode-swe",
|
||||
"math500-v1",
|
||||
"mmlu-pro-v1",
|
||||
"mrcr-v2-v1",
|
||||
"oolong-pairs-v1",
|
||||
"oolong-real-v1",
|
||||
"oolong-synth-v1",
|
||||
"openseeker-v1",
|
||||
"openthoughts-tblite-v1",
|
||||
"papersearchqa-v1",
|
||||
"patterned-needle-in-haystack-v1",
|
||||
"prolog-v1",
|
||||
"r2e-gym-v1",
|
||||
"redsearcher-v1",
|
||||
"reverse-text",
|
||||
"rlm-swe",
|
||||
"science-env",
|
||||
"simpleqa-verified",
|
||||
"tau2-bench",
|
||||
"reverse-text-v1",
|
||||
"rlm-search",
|
||||
"scaleswe-v1",
|
||||
"simpleqa-v1",
|
||||
"simpleqa-verified-v1",
|
||||
"swebench-pro-v1",
|
||||
"swebench-verified-v1",
|
||||
"swelego-v1",
|
||||
"tau2-bench-v1",
|
||||
"terminal-bench-2-v1",
|
||||
"unscramble-v1",
|
||||
"uuid-ctf-v1",
|
||||
"verbatim-copy-v1",
|
||||
"wideseek-v1",
|
||||
"wiki-search",
|
||||
"wiki-search-v1",
|
||||
"wikispeedia-v1",
|
||||
"wordle",
|
||||
"wordle-v1",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
@@ -137,7 +174,6 @@ dev = [
|
||||
# *without* the cooldown — bypassing this security policy.
|
||||
required-version = ">=0.11.1"
|
||||
exclude-newer = "7 days"
|
||||
preview = true
|
||||
no-build-isolation-package = ["flash-attn"]
|
||||
environments = [
|
||||
"sys_platform == 'linux' and platform_machine == 'x86_64'",
|
||||
@@ -151,7 +187,6 @@ override-dependencies = [
|
||||
"transformers==5.6.2",
|
||||
"torch>=2.9.0",
|
||||
"openenv-core",
|
||||
"verifiers[packages]>=0.1.15.dev150",
|
||||
]
|
||||
|
||||
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
|
||||
@@ -186,8 +221,6 @@ prime-tunnel = false
|
||||
prime-evals = false
|
||||
verifiers = false
|
||||
renderers = false
|
||||
tasksets = false
|
||||
harnesses = false
|
||||
prime-pydantic-config = false
|
||||
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
|
||||
vllm-router = false
|
||||
@@ -198,40 +231,76 @@ nixl-cu12 = false
|
||||
|
||||
[tool.uv.sources]
|
||||
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
# prime-rl depends on the one `verifiers` package (v0 + v1 + the legacy bridge + the built-in v1
|
||||
# harnesses/tasksets, now bundled in verifiers.v1). v0 envs resolve from
|
||||
# deps/{verifiers,research-environments}/environments; v1 tasksets (`-v1`) and the `compact`
|
||||
# example live under deps/{verifiers,research-environments}/environments.
|
||||
verifiers = { path = "deps/verifiers", editable = true }
|
||||
renderers = { path = "deps/renderers", editable = true }
|
||||
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
|
||||
aime2024 = { path = "deps/research-environments/environments/aime2024", editable = true }
|
||||
aime2025 = { path = "deps/research-environments/environments/aime2025", editable = true }
|
||||
aime24-v1 = { path = "deps/research-environments/environments/aime24_v1", editable = true }
|
||||
aime25-v1 = { path = "deps/research-environments/environments/aime25_v1", editable = true }
|
||||
aime26-v1 = { path = "deps/research-environments/environments/aime26_v1", editable = true }
|
||||
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
|
||||
code-env = { path = "deps/research-environments/environments/code_env", editable = true }
|
||||
color-codeword = { path = "deps/research-environments/environments/color_codeword", editable = true }
|
||||
deepdive = { path = "deps/research-environments/environments/deepdive", editable = true }
|
||||
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
|
||||
apex-shortlist-v1 = { path = "deps/research-environments/environments/apex_shortlist_v1", editable = true }
|
||||
browsecomp-v1 = { path = "deps/research-environments/environments/browsecomp_v1", editable = true }
|
||||
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_v1", editable = true }
|
||||
color-codeword-v1 = { path = "deps/verifiers/environments/color_codeword_v1", editable = true }
|
||||
deepdive-v1 = { path = "deps/research-environments/environments/deepdive_v1", editable = true }
|
||||
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
|
||||
forth-lang-v1 = { path = "deps/research-environments/environments/forth_lang_v1", editable = true }
|
||||
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
|
||||
gpqa = { path = "deps/research-environments/environments/gpqa", editable = true }
|
||||
harnesses = { path = "deps/verifiers/packages/harnesses", editable = true }
|
||||
hle = { path = "deps/research-environments/environments/hle", editable = true }
|
||||
ifeval = { path = "deps/research-environments/environments/ifeval", editable = true }
|
||||
livecodebench = { path = "deps/research-environments/environments/livecodebench", editable = true }
|
||||
general-agent-v1 = { path = "deps/research-environments/environments/general_agent_v1", editable = true }
|
||||
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
|
||||
gpqa-v1 = { path = "deps/research-environments/environments/gpqa_v1", editable = true }
|
||||
graphwalks-v1 = { path = "deps/research-environments/environments/graphwalks_v1", editable = true }
|
||||
gsm8k-v1 = { path = "deps/verifiers/environments/gsm8k_v1", editable = true }
|
||||
i3-code-v1 = { path = "deps/research-environments/environments/i3_code_v1", editable = true }
|
||||
i3-science-v1 = { path = "deps/research-environments/environments/i3_science_v1", editable = true }
|
||||
ifbench-v1 = { path = "deps/research-environments/environments/ifbench_v1", editable = true }
|
||||
ifeval-v1 = { path = "deps/research-environments/environments/ifeval_v1", editable = true }
|
||||
lean-v1 = { path = "deps/research-environments/environments/lean_v1", editable = true }
|
||||
livecodebench-v1 = { path = "deps/research-environments/environments/livecodebench_v1", editable = true }
|
||||
logic-env = { path = "deps/research-environments/environments/logic_env", editable = true }
|
||||
longcot-mini-v1 = { path = "deps/research-environments/environments/longcot_mini_v1", editable = true }
|
||||
longcot-v1 = { path = "deps/research-environments/environments/longcot_v1", editable = true }
|
||||
math-env = { path = "deps/research-environments/environments/math_env", editable = true }
|
||||
math-env-v1 = { path = "deps/research-environments/environments/math_env_v1", editable = true }
|
||||
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
|
||||
math500 = { path = "deps/research-environments/environments/math500", editable = true }
|
||||
mini-swe-agent-plus = { path = "deps/research-environments/environments/mini_swe_agent_plus", editable = true }
|
||||
mmlu-pro = { path = "deps/research-environments/environments/mmlu_pro", editable = true }
|
||||
opencode-cp = { path = "deps/research-environments/environments/opencode_cp", editable = true }
|
||||
opencode-deepdive = { path = "deps/research-environments/environments/opencode_deepdive", editable = true }
|
||||
opencode-math = { path = "deps/research-environments/environments/opencode_math", editable = true }
|
||||
opencode-science = { path = "deps/research-environments/environments/opencode_science", editable = true }
|
||||
opencode-swe = { path = "deps/research-environments/environments/opencode_swe", editable = true }
|
||||
math500-v1 = { path = "deps/research-environments/environments/math500_v1", editable = true }
|
||||
mmlu-pro-v1 = { path = "deps/research-environments/environments/mmlu_pro_v1", editable = true }
|
||||
mrcr-v2-v1 = { path = "deps/research-environments/environments/mrcr_v2_v1", editable = true }
|
||||
oolong-pairs-v1 = { path = "deps/research-environments/environments/oolong_pairs_v1", editable = true }
|
||||
oolong-real-v1 = { path = "deps/research-environments/environments/oolong_real_v1", editable = true }
|
||||
oolong-synth-v1 = { path = "deps/research-environments/environments/oolong_synth_v1", editable = true }
|
||||
openseeker-v1 = { path = "deps/research-environments/environments/openseeker_v1", editable = true }
|
||||
openthoughts-tblite-v1 = { path = "deps/research-environments/environments/openthoughts_tblite_v1", editable = true }
|
||||
papersearchqa-v1 = { path = "deps/research-environments/environments/papersearchqa_v1", editable = true }
|
||||
patterned-needle-in-haystack-v1 = { path = "deps/research-environments/environments/patterned_needle_in_haystack_v1", editable = true }
|
||||
prolog-v1 = { path = "deps/research-environments/environments/prolog_v1", editable = true }
|
||||
r2e-gym-v1 = { path = "deps/research-environments/environments/r2e_gym_v1", editable = true }
|
||||
redsearcher-v1 = { path = "deps/research-environments/environments/redsearcher_v1", editable = true }
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
|
||||
science-env = { path = "deps/research-environments/environments/science_env", editable = true }
|
||||
simpleqa-verified = { path = "deps/research-environments/environments/simpleqa_verified", editable = true }
|
||||
tau2-bench = { path = "deps/research-environments/environments/tau2_bench", editable = true }
|
||||
tasksets = { path = "deps/verifiers/packages/tasksets", editable = true }
|
||||
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
|
||||
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
|
||||
scaleswe-v1 = { path = "deps/research-environments/environments/scaleswe_v1", editable = true }
|
||||
simpleqa-v1 = { path = "deps/research-environments/environments/simpleqa_v1", editable = true }
|
||||
simpleqa-verified-v1 = { path = "deps/research-environments/environments/simpleqa_verified_v1", editable = true }
|
||||
swebench-pro-v1 = { path = "deps/research-environments/environments/swebench_pro_v1", editable = true }
|
||||
swebench-verified-v1 = { path = "deps/research-environments/environments/swebench_verified_v1", editable = true }
|
||||
swelego-v1 = { path = "deps/research-environments/environments/swelego_v1", editable = true }
|
||||
tau2-bench-v1 = { path = "deps/research-environments/environments/tau2_bench_v1", editable = true }
|
||||
terminal-bench-2-v1 = { path = "deps/research-environments/environments/terminal_bench_2_v1", editable = true }
|
||||
unscramble-v1 = { path = "deps/research-environments/environments/unscramble_v1", editable = true }
|
||||
uuid-ctf-v1 = { path = "deps/research-environments/environments/uuid_ctf_v1", editable = true }
|
||||
verbatim-copy-v1 = { path = "deps/research-environments/environments/verbatim_copy_v1", editable = true }
|
||||
wideseek-v1 = { path = "deps/research-environments/environments/wideseek_v1", editable = true }
|
||||
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
|
||||
wiki-search-v1 = { path = "deps/verifiers/environments/wiki_search_v1", editable = true }
|
||||
wikispeedia-v1 = { path = "deps/research-environments/environments/wikispeedia_v1", editable = true }
|
||||
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
|
||||
wordle-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
@@ -240,8 +309,8 @@ dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.22.0/vllm-0.22.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.22.0/vllm-0.22.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.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.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
mode="env"
|
||||
if [ "${1:-}" = "--shell" ] || [ "${1:-}" = "--github-output" ]; then
|
||||
mode="${1#--}"
|
||||
shift
|
||||
fi
|
||||
|
||||
root="${1:-.}"
|
||||
root="$(cd "$root" && pwd)"
|
||||
|
||||
dependency_floor_version() {
|
||||
local package="$1"
|
||||
|
||||
find "$root" \
|
||||
\( -path "$root/.git" -o -path "$root/.venv" \) -prune -o \
|
||||
-type f -name pyproject.toml -print |
|
||||
while IFS= read -r pyproject; do
|
||||
sed -nE "s/.*[\"']${package}(\\[[^]]+\\])?>=([^\"',; ]+).*/\\2/p" "$pyproject"
|
||||
done |
|
||||
sort -V |
|
||||
tail -n 1
|
||||
}
|
||||
|
||||
next_patch_dev_version() {
|
||||
local tag="$1"
|
||||
local distance="$2"
|
||||
local version="${tag#v}"
|
||||
local major minor patch
|
||||
|
||||
if [ "$distance" = "0" ]; then
|
||||
printf '%s\n' "$version"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [[ "$version" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
|
||||
major="${BASH_REMATCH[1]}"
|
||||
minor="${BASH_REMATCH[2]}"
|
||||
patch="${BASH_REMATCH[3]}"
|
||||
printf '%s.%s.%s.dev%s\n' "$major" "$minor" "$((patch + 1))" "$distance"
|
||||
return 0
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
describe_distance() {
|
||||
sed -E 's/.*-([0-9]+)-g[0-9a-f]+$/\1/' <<< "$1"
|
||||
}
|
||||
|
||||
describe_tag() {
|
||||
sed -E 's/-[0-9]+-g[0-9a-f]+$//' <<< "$1"
|
||||
}
|
||||
|
||||
verifiers_git_version() {
|
||||
local dir="$root/deps/verifiers"
|
||||
local desc tag distance
|
||||
|
||||
[ -d "$dir" ] || return 1
|
||||
desc="$(git -C "$dir" describe --tags --long --match 'v[0-9]*.[0-9]*.[0-9]*' --exclude '*dev*' 2>/dev/null)" || return 1
|
||||
tag="$(describe_tag "$desc")"
|
||||
distance="$(describe_distance "$desc")"
|
||||
next_patch_dev_version "$tag" "$distance"
|
||||
}
|
||||
|
||||
renderers_git_version() {
|
||||
local dir="$root/deps/renderers"
|
||||
local desc tag distance version
|
||||
|
||||
[ -d "$dir" ] || return 1
|
||||
desc="$(git -C "$dir" describe --tags --long --match 'renderers-v*' 2>/dev/null)" || return 1
|
||||
tag="$(describe_tag "$desc")"
|
||||
distance="$(describe_distance "$desc")"
|
||||
version="${tag#renderers-v}"
|
||||
|
||||
if [ "$distance" = "0" ]; then
|
||||
printf '%s\n' "$version"
|
||||
return 0
|
||||
fi
|
||||
|
||||
next_patch_dev_version "v$version" "$distance"
|
||||
}
|
||||
|
||||
resolve_version() {
|
||||
local package="$1"
|
||||
local env_name="$2"
|
||||
local git_func="$3"
|
||||
local version
|
||||
|
||||
version="${!env_name:-}"
|
||||
if [ -n "$version" ]; then
|
||||
printf '%s\n' "$version"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if version="$("$git_func")" && [ -n "$version" ]; then
|
||||
printf '%s\n' "$version"
|
||||
return 0
|
||||
fi
|
||||
|
||||
version="$(dependency_floor_version "$package")"
|
||||
if [ -n "$version" ]; then
|
||||
printf '%s\n' "$version"
|
||||
return 0
|
||||
fi
|
||||
|
||||
printf 'Could not infer a pretend version for %s under %s\n' "$package" "$root" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
verifiers_version="$(resolve_version verifiers VERIFIERS_PRETEND_VERSION verifiers_git_version)"
|
||||
renderers_version="$(resolve_version renderers RENDERERS_PRETEND_VERSION renderers_git_version)"
|
||||
|
||||
printf 'Resolved verifiers pretend version: %s\n' "$verifiers_version" >&2
|
||||
printf 'Resolved renderers pretend version: %s\n' "$renderers_version" >&2
|
||||
|
||||
case "$mode" in
|
||||
shell)
|
||||
printf "export VERIFIERS_PRETEND_VERSION='%s'\n" "$verifiers_version"
|
||||
printf "export RENDERERS_PRETEND_VERSION='%s'\n" "$renderers_version"
|
||||
;;
|
||||
github-output)
|
||||
printf 'verifiers=%s\n' "$verifiers_version"
|
||||
printf 'renderers=%s\n' "$renderers_version"
|
||||
;;
|
||||
env)
|
||||
printf 'VERIFIERS_PRETEND_VERSION=%s\n' "$verifiers_version"
|
||||
printf 'RENDERERS_PRETEND_VERSION=%s\n' "$renderers_version"
|
||||
;;
|
||||
*)
|
||||
printf 'Unknown output mode: %s\n' "$mode" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -4,8 +4,74 @@ set -e
|
||||
# Set higher ulimit for file descriptors to prevent API timeout issues
|
||||
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
|
||||
|
||||
# Allow runtime override of the prime-rl source itself.
|
||||
# PRIME_RL_REF can be a git tag, branch, or commit hash. PRIME_RL_REPO
|
||||
# optionally points at a fork; defaults to the upstream repo.
|
||||
#
|
||||
# We clone into a per-ref dir under /tmp, seed the venv from the baked
|
||||
# /app/.venv so heavy wheels (flash-attn, mamba-ssm, …) survive, then
|
||||
# `uv sync --inexact` re-installs prime_rl from the override source.
|
||||
# Workdir + PATH swap so the chart's `uv run trainer/inference/orchestrator`
|
||||
# resolves the entrypoints from the override venv.
|
||||
if [ -n "$PRIME_RL_REF" ]; then
|
||||
PRIME_RL_REPO="${PRIME_RL_REPO:-https://github.com/PrimeIntellect-ai/prime-rl.git}"
|
||||
# Slug + content hash for the cache dir name. Slug keeps the path
|
||||
# human-readable; the hash (over repo + ref) prevents collisions
|
||||
# between distinct refs that slugify the same way (e.g. `feat/foo`
|
||||
# vs `feat-foo`) and between the same ref on different forks.
|
||||
REF_SLUG="${PRIME_RL_REF//\//-}"
|
||||
REF_HASH=$(echo -n "${PRIME_RL_REPO}|${PRIME_RL_REF}" | md5sum | cut -c1-12)
|
||||
DEST="/tmp/prime-rl-${REF_SLUG}-${REF_HASH}"
|
||||
# Rewrite ssh://git@github.com URLs to https so submodules listed
|
||||
# with SSH URLs (deps/verifiers, deps/renderers, deps/research-envs)
|
||||
# can be cloned from the pod without ssh keys.
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
if [ ! -d "$DEST/.git" ]; then
|
||||
echo "[prime-rl] cloning ${PRIME_RL_REPO} for ${PRIME_RL_REF}"
|
||||
rm -rf "$DEST"
|
||||
git clone --recurse-submodules "$PRIME_RL_REPO" "$DEST"
|
||||
fi
|
||||
# Always fetch + checkout so mutable refs (branches/tags) pick up new
|
||||
# commits between pod restarts. No-op for immutable SHAs.
|
||||
echo "[prime-rl] refreshing ${PRIME_RL_REF}"
|
||||
git -C "$DEST" fetch --quiet --tags --force origin
|
||||
git -C "$DEST" checkout --quiet --force "$PRIME_RL_REF"
|
||||
# Fast-forward to upstream tip when PRIME_RL_REF is a branch name.
|
||||
# Silently no-ops for SHAs/tags (no `origin/<sha>` exists).
|
||||
git -C "$DEST" reset --hard --quiet "origin/${PRIME_RL_REF}" 2>/dev/null || true
|
||||
# Refresh submodules to whatever the parent commit pins. `sync`
|
||||
# picks up URL changes in .gitmodules between checkouts on cache
|
||||
# hit; `update --init --recursive` applies the pinned SHAs.
|
||||
git -C "$DEST" submodule sync --recursive
|
||||
git -C "$DEST" submodule update --init --recursive
|
||||
if [ ! -d "$DEST/.venv" ]; then
|
||||
# Seed from the baked venv so the heavy wheels (flash-attn,
|
||||
# mamba-ssm, …) don't have to be rebuilt. Plain `cp -a` (no
|
||||
# hardlinks): a subsequent `uv sync` writes into this tree, and
|
||||
# hardlinks would leak those writes back into /app/.venv when
|
||||
# /tmp and /app share a filesystem.
|
||||
cp -a /app/.venv "$DEST/.venv"
|
||||
fi
|
||||
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
|
||||
# Mirror the image's uv sync extras — explicit instead
|
||||
# of --all-extras so we don't pull in `disagg` / `quack` and trigger
|
||||
# heavy source builds (deep-ep, deep-gemm, quack-kernels) at pod
|
||||
# startup. --inexact keeps the seeded venv's pre-built wheels
|
||||
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
|
||||
# override's lockfile pins different versions.
|
||||
( cd "$DEST" && uv sync --inexact --no-dev \
|
||||
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
|
||||
--extra envs --extra gpt-oss --extra modelexpress \
|
||||
--group mamba-ssm )
|
||||
export VIRTUAL_ENV="$DEST/.venv"
|
||||
export PATH="$DEST/.venv/bin:$PATH"
|
||||
cd "$DEST"
|
||||
fi
|
||||
|
||||
# Allow runtime override of the verifiers package version.
|
||||
# VERIFIERS_VERSION can be a git tag, branch, or commit hash.
|
||||
# VERIFIERS_VERSION can be a git tag, branch, or commit hash. Runs after the
|
||||
# PRIME_RL_REF swap so when both are set the install lands in the override
|
||||
# venv (uv pip install targets $VIRTUAL_ENV when exported).
|
||||
if [ -n "$VERIFIERS_VERSION" ]; then
|
||||
echo "Installing verifiers version: $VERIFIERS_VERSION"
|
||||
uv pip install --reinstall-package verifiers \
|
||||
|
||||
Executable
+86
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install the llm-d standalone (no-Kubernetes) routing binaries into
|
||||
# third_party/llmd/bin:
|
||||
# - epp : llm-d-router Endpoint Picker (the routing brain)
|
||||
# - pd-sidecar : decode-side proxy for P/D disaggregation
|
||||
# - envoy : the data-plane proxy that calls the EPP via ext_proc
|
||||
#
|
||||
# epp/pd-sidecar are built from a pinned llm-d-router commit. We currently build
|
||||
# from a small fork that adds P/D disaggregation for vLLM's token-in
|
||||
# /inference/v1/generate endpoint (prime-rl's renderer / TITO rollout path) —
|
||||
# upstream's pd-sidecar only disaggregates the OpenAI endpoints, so token-in P/D
|
||||
# silently runs decode-only. The fork is pending upstream PR
|
||||
# llm-d/llm-d-router#1458; switch LLMD_ROUTER_REPO back to the upstream repo and
|
||||
# bump LLMD_ROUTER_REF once it merges. The fork is branched off the upstream
|
||||
# commit that added the EPP vllmhttp parser (PR #1248), which the renderer path
|
||||
# also needs.
|
||||
#
|
||||
# System Go is not required: a Go toolchain is vendored under third_party/llmd/go
|
||||
# and used to bootstrap; GOTOOLCHAIN=auto fetches the exact version the module
|
||||
# pins. Envoy is extracted as a static binary from its release container image
|
||||
# WITHOUT docker: we build `crane` (pure-Go, talks straight to the OCI registry)
|
||||
# with the same vendored toolchain and use it to export the image filesystem.
|
||||
# This is the only step that previously required a docker daemon, which cluster
|
||||
# compute nodes don't have.
|
||||
set -euo pipefail
|
||||
|
||||
LLMD_ROUTER_REPO="${LLMD_ROUTER_REPO:-https://github.com/S1ro1/llm-d-router.git}"
|
||||
LLMD_ROUTER_REF="${LLMD_ROUTER_REF:-1ca4243ec84c657b4a5f507a1776d6c15a618d5b}"
|
||||
GO_BOOTSTRAP_VERSION="${GO_BOOTSTRAP_VERSION:-1.23.4}"
|
||||
ENVOY_VERSION="${ENVOY_VERSION:-1.36.0}"
|
||||
ENVOY_IMAGE="${ENVOY_IMAGE:-envoyproxy/envoy:v${ENVOY_VERSION}}"
|
||||
|
||||
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
PROJECT_DIR=$(cd "$SCRIPT_DIR/.." && pwd)
|
||||
LLMD_DIR="$PROJECT_DIR/third_party/llmd"
|
||||
BIN_DIR="$LLMD_DIR/bin"
|
||||
GO_ROOT="$LLMD_DIR/go"
|
||||
SRC_DIR="$LLMD_DIR/src"
|
||||
GO_TOOLS_BIN="$LLMD_DIR/gotools/bin"
|
||||
mkdir -p "$BIN_DIR" "$GO_TOOLS_BIN"
|
||||
|
||||
# --- Go toolchain (vendored bootstrap; auto-upgrades to the module's version) ---
|
||||
if [ ! -x "$GO_ROOT/bin/go" ]; then
|
||||
echo "[install_llmd] downloading bootstrap Go $GO_BOOTSTRAP_VERSION"
|
||||
rm -rf "$GO_ROOT"
|
||||
curl -fsSL "https://go.dev/dl/go${GO_BOOTSTRAP_VERSION}.linux-amd64.tar.gz" | tar -xz -C "$LLMD_DIR"
|
||||
fi
|
||||
export GOROOT="$GO_ROOT"
|
||||
export PATH="$GO_ROOT/bin:$PATH"
|
||||
export GOTOOLCHAIN=auto
|
||||
echo "[install_llmd] bootstrap $(go version)"
|
||||
|
||||
# --- Fetch llm-d-router source at the pinned ref ---
|
||||
echo "[install_llmd] fetching ${LLMD_ROUTER_REPO}@${LLMD_ROUTER_REF}"
|
||||
if [ ! -d "$SRC_DIR/.git" ]; then
|
||||
rm -rf "$SRC_DIR"
|
||||
git clone --quiet "$LLMD_ROUTER_REPO" "$SRC_DIR"
|
||||
fi
|
||||
git -C "$SRC_DIR" remote set-url origin "$LLMD_ROUTER_REPO"
|
||||
git -C "$SRC_DIR" fetch --quiet origin
|
||||
git -C "$SRC_DIR" checkout --quiet "$LLMD_ROUTER_REF"
|
||||
|
||||
# --- Build epp + pd-sidecar ---
|
||||
echo "[install_llmd] building epp + pd-sidecar"
|
||||
( cd "$SRC_DIR" && go build -o "$BIN_DIR/epp" ./cmd/epp && go build -o "$BIN_DIR/pd-sidecar" ./cmd/pd-sidecar )
|
||||
|
||||
# --- Envoy static binary (extract from the release image; keep if present) ---
|
||||
# No docker: build crane with the vendored toolchain and export the image's
|
||||
# filesystem straight from the registry, then pull out the static envoy binary.
|
||||
if [ ! -x "$BIN_DIR/envoy" ]; then
|
||||
if [ ! -x "$GO_TOOLS_BIN/crane" ]; then
|
||||
echo "[install_llmd] building crane (OCI registry client, no docker needed)"
|
||||
GOBIN="$GO_TOOLS_BIN" GOFLAGS=-mod=mod \
|
||||
go install github.com/google/go-containerregistry/cmd/crane@latest
|
||||
fi
|
||||
echo "[install_llmd] extracting Envoy ${ENVOY_VERSION} from ${ENVOY_IMAGE}"
|
||||
"$GO_TOOLS_BIN/crane" export "$ENVOY_IMAGE" - \
|
||||
| tar -xf - -O usr/local/bin/envoy > "$BIN_DIR/envoy"
|
||||
chmod +x "$BIN_DIR/envoy"
|
||||
fi
|
||||
|
||||
echo "[install_llmd] installed binaries in $BIN_DIR:"
|
||||
"$BIN_DIR/epp" --version 2>&1 | head -1 || true
|
||||
"$BIN_DIR/envoy" --version 2>&1 | head -1 || true
|
||||
"$BIN_DIR/pd-sidecar" --help >/dev/null 2>&1 && echo " pd-sidecar OK" || true
|
||||
echo "[install_llmd] done"
|
||||
@@ -10,6 +10,19 @@ PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
VENV_BIN="$PROJECT_DIR/.venv/bin"
|
||||
PYTHON="$VENV_BIN/python"
|
||||
|
||||
# UCX's --with-verbs silently disables IB/RoCE support when the rdma-core *dev*
|
||||
# headers (verbs.h / rdma_cma.h) are missing, yielding a TCP-only build. On hosts
|
||||
# with RDMA devices, require the headers up front instead of failing at runtime.
|
||||
HAVE_RDMA=0
|
||||
if compgen -G "/sys/class/infiniband/*" > /dev/null; then
|
||||
HAVE_RDMA=1
|
||||
if [ ! -f /usr/include/infiniband/verbs.h ] || [ ! -f /usr/include/rdma/rdma_cma.h ]; then
|
||||
echo "ERROR: host has RDMA devices but the rdma-core dev headers are missing." >&2
|
||||
echo "Install them first, e.g.: apt-get install -y libibverbs-dev librdmacm-dev" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
WORKSPACE="$PROJECT_DIR/nixl_workspace"
|
||||
mkdir -p "$WORKSPACE"
|
||||
UCX_SRC="$WORKSPACE/ucx_source"
|
||||
@@ -40,11 +53,23 @@ if [ ! -f "$UCX_INSTALL/lib/libucs.so" ]; then
|
||||
--enable-devel-headers \
|
||||
--enable-mt \
|
||||
--with-verbs \
|
||||
--with-rdmacm \
|
||||
--with-cuda="$CUDA_PATH" \
|
||||
--with-ze=no
|
||||
make -j"$NPROC"
|
||||
make install
|
||||
echo "=== UCX installed to $UCX_INSTALL ==="
|
||||
|
||||
# Fail loudly if the IB transports didn't make it into the build.
|
||||
if [ "$HAVE_RDMA" = 1 ]; then
|
||||
ucx_transports=$(LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:-}" \
|
||||
"$UCX_INSTALL/bin/ucx_info" -d)
|
||||
if ! grep -q "Transport: rc_verbs" <<< "$ucx_transports"; then
|
||||
echo "ERROR: UCX built without IB (rc_verbs) transport despite RDMA devices being present." >&2
|
||||
echo "Check that libibverbs-dev / librdmacm-dev were present at configure time." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
echo "=== UCX already built, skipping ==="
|
||||
fi
|
||||
|
||||
+3
-3
@@ -81,7 +81,7 @@ tmux send-keys -t "$SESSION_NAME:Logs.1" \
|
||||
"tail -F ${LOG_DIR}/orchestrator.log 2>/dev/null" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.2" \
|
||||
"tail -F ${LOG_DIR}/envs/*/*/*.log 2>/dev/null" C-m
|
||||
"tail -F ${LOG_DIR}/envs/*/*.log 2>/dev/null" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.3" \
|
||||
"tail -F ${LOG_DIR}/inference.log 2>/dev/null" C-m
|
||||
@@ -95,8 +95,8 @@ tmux send-keys -t "$SESSION_NAME:Claude" \
|
||||
All ranks: ${LOG_DIR}/trainer/torchrun/*/*/*/*.log
|
||||
Orchestrator: ${LOG_DIR}/orchestrator.log
|
||||
Inference: ${LOG_DIR}/inference.log
|
||||
Envs: ${LOG_DIR}/envs/*/*/*.log
|
||||
Train envs: ${LOG_DIR}/envs/train/*/*.log
|
||||
Envs: ${LOG_DIR}/envs/*/*.log
|
||||
Train envs: ${LOG_DIR}/envs/train/*.log
|
||||
You are running inside tmux session \"${SESSION_NAME}\". The Launcher window (window 0) is where the user runs launch commands. You can read its contents with: tmux capture-pane -t ${SESSION_NAME}:Launcher -p
|
||||
Help the user monitor and debug this run.'" C-m
|
||||
|
||||
|
||||
@@ -47,9 +47,11 @@ id = "reverse-text"
|
||||
|
||||
CLI: `--env.0.id reverse-text --env.1.id math-env`.
|
||||
|
||||
**Dicts** — TOML uses a section; CLI takes a JSON string: `--vllm-extra '{"key1": "value1"}'`.
|
||||
**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.
|
||||
|
||||
**Discriminated unions** — set the `type` field to pick the variant (`[trainer.loss] type = "sft"`). Omit `type` to keep the default variant.
|
||||
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
|
||||
|
||||
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-env override: `[orchestrator.train.env.algo] type = "opd"` (the env assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
|
||||
|
||||
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
|
||||
|
||||
@@ -62,10 +64,10 @@ In TOML, an empty section header (`[ckpt]`) does the same.
|
||||
|
||||
## RL trainer token exports
|
||||
|
||||
For rollout debugging, enable trainer-side token export under `trainer.experimental.token_export` (or `experimental.token_export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Single-run/fallback exports go under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`; multi-run trainer exports with packer metadata go under the owning run directory, `output_dir/<run_id>/token_exports/step_<run_step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
|
||||
```toml
|
||||
[trainer.experimental.token_export]
|
||||
enable_token_export = true
|
||||
```
|
||||
|
||||
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
|
||||
|
||||
+11
-1
@@ -27,7 +27,7 @@ uv sync --group dev # + pytest, ruff, pre-commit
|
||||
uv sync --all-extras # recommended: envs, flash-attn, flash-attn-cute, etc.
|
||||
```
|
||||
|
||||
The `envs` extra installs every env workspace listed in `[tool.uv.workspace]`. Adding a new env means adding it to `members`, the `envs` extra, and `[tool.uv.sources]`.
|
||||
The `envs` extra installs environments listed under `[project.optional-dependencies].envs`, resolved through `[tool.uv.sources]`. Adding a new env means adding its package name to `envs` and its editable source path to `[tool.uv.sources]`.
|
||||
|
||||
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
|
||||
|
||||
@@ -59,6 +59,16 @@ Flags: `--workspace DIR`, `--deepep-ref REF` (default `73b6ea4`), `--nvshmem-ver
|
||||
|
||||
Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`.
|
||||
|
||||
### llm-d router backend
|
||||
|
||||
Multi-node / disaggregated deployments can route through the upstream llm-d Endpoint Picker instead of `vllm-router` (set `[...deployment.router] type = "llm-d"`). It needs three native binaries — install once:
|
||||
|
||||
```bash
|
||||
bash scripts/install_llmd.sh # builds epp + pd-sidecar from a pinned llm-d-router commit (vendored Go), fetches envoy
|
||||
```
|
||||
|
||||
Binaries land in `third_party/llmd/bin/{epp,envoy,pd-sidecar}` (a shared path, so SLURM nodes see them). `epp` is pinned to the commit that includes the `vllmhttp-parser` (PR #1248) so prime-rl's renderer/TITO `/inference/v1/generate` path routes correctly. Override the pin with `LLMD_ROUTER_REF=<sha>`. The EPP + Envoy + endpoints configs are rendered from `templates/llmd/*.yaml.j2` (included into the SLURM script); only the per-node IPv4 addresses are filled in inline at launch time.
|
||||
|
||||
## Key files
|
||||
|
||||
- `pyproject.toml` — dependencies, extras, dependency groups
|
||||
|
||||
@@ -71,9 +71,7 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
├── inference/
|
||||
│ ├── node_*.log # per-node (multi-node only)
|
||||
│ └── router_0.log # vllm-router per replica (multi-node only)
|
||||
└── envs/{train,eval}/{env_name}/
|
||||
├── env_server.log
|
||||
└── env_worker_*.log
|
||||
└── envs/{train,eval}/{env_name}.log # one log file per env
|
||||
```
|
||||
|
||||
Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough. Drop into per-node or per-rank logs only when debugging. All logs are loguru with `HH:mm:ss LEVEL message`; levels: `DEBUG`, `INFO`, `SUCCESS`, `WARNING`, `ERROR`.
|
||||
@@ -82,7 +80,7 @@ Scan for problems:
|
||||
|
||||
```bash
|
||||
grep -E "WARNING|ERROR" {output_dir}/logs/{trainer,orchestrator,inference}.log
|
||||
grep -E "WARNING|ERROR" {output_dir}/logs/envs/train/*/env_{server,worker_*}.log
|
||||
grep -E "WARNING|ERROR" {output_dir}/logs/envs/{train,eval}/*.log
|
||||
```
|
||||
|
||||
### Metrics
|
||||
|
||||
@@ -36,7 +36,7 @@ uv run rl @ examples/reverse_text/rl.toml --dry-run
|
||||
- SLURM: single- and multi-node
|
||||
- Environment packages: before launching a config with a non-core verifier env id,
|
||||
verify the package imports under `uv run` (for example
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('rlm_swe'))"`).
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym_v1'))"`).
|
||||
If a local env exists under `deps/research-environments/environments/` but does not
|
||||
import, add it to the root `pyproject.toml` env extra, workspace members, and
|
||||
`[tool.uv.sources]`, then run `uv sync --all-extras`.
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import tomli_w
|
||||
|
||||
@@ -8,12 +11,23 @@ from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, DEFAULT_INFERENCE_ENV_VARS, set_proc_title
|
||||
|
||||
INFERENCE_TOML = "inference.toml"
|
||||
INFERENCE_SBATCH = "inference.sbatch"
|
||||
|
||||
|
||||
def vllm_overrides_fragment(overrides: dict[str, Any]) -> str:
|
||||
"""Render per-role vLLM overrides as a JSON fragment for the ROLE_EXTRA bash string.
|
||||
|
||||
Returns a leading-comma fragment with quotes escaped for the double-quoted assignment
|
||||
(e.g. `, \\"max_num_seqs\\": 256`), or an empty string when there are no overrides.
|
||||
"""
|
||||
if not overrides:
|
||||
return ""
|
||||
return ", " + json.dumps(overrides)[1:-1].replace('"', '\\"')
|
||||
|
||||
|
||||
def write_config(config: InferenceConfig, output_dir: Path, exclude: set[str] | None = None) -> Path:
|
||||
"""Write resolved config to disk."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -47,12 +61,13 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
dp_per_node=dp_per_node,
|
||||
num_nodes=getattr(config.deployment, "num_nodes", 1),
|
||||
port=config.server.port,
|
||||
disaggregated=is_disaggregated,
|
||||
is_disaggregated=is_disaggregated,
|
||||
kv_offload=offload is not None,
|
||||
kv_offload_mooncake=is_mooncake,
|
||||
kv_offload_cpu_bytes=int(offload.cpu.num_bytes) if is_mooncake else 0,
|
||||
kv_offload_disk_path=str(offload.disk.path) if (is_mooncake and offload.disk is not None) else "",
|
||||
kv_offload_device_name=offload.device_name if is_mooncake else "",
|
||||
inference_env_vars={**DEFAULT_COMMON_ENV_VARS, **DEFAULT_INFERENCE_ENV_VARS, **config.env_vars},
|
||||
)
|
||||
|
||||
is_multi_node = config.deployment.type == "multi_node"
|
||||
@@ -65,20 +80,21 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
num_decode_replicas=config.deployment.num_decode_replicas,
|
||||
prefill_port=config.deployment.prefill_port,
|
||||
decode_port=config.deployment.decode_port,
|
||||
router_port=config.deployment.router.port,
|
||||
router_policy=config.deployment.router.policy,
|
||||
router=config.deployment.router,
|
||||
data_parallel_rpc_port=config.data_parallel_rpc_port,
|
||||
use_deep_gemm=config.use_deep_gemm,
|
||||
prefill_env_overrides=config.deployment.prefill_env_overrides,
|
||||
decode_env_overrides=config.deployment.decode_env_overrides,
|
||||
prefill_env_vars=config.deployment.prefill_env_vars,
|
||||
decode_env_vars=config.deployment.decode_env_vars,
|
||||
prefill_vllm_extra_json=vllm_overrides_fragment(config.deployment.prefill_vllm_overrides),
|
||||
decode_vllm_extra_json=vllm_overrides_fragment(config.deployment.decode_vllm_overrides),
|
||||
)
|
||||
elif is_multi_node:
|
||||
template_vars.update(
|
||||
router_port=config.deployment.router.port,
|
||||
router=config.deployment.router,
|
||||
backend_port=config.deployment.backend_port,
|
||||
router_policy=config.deployment.router.policy,
|
||||
data_parallel_rpc_port=config.data_parallel_rpc_port,
|
||||
enable_expert_parallel=config.enable_expert_parallel,
|
||||
infer_nodes_per_replica=config.deployment.num_nodes,
|
||||
)
|
||||
|
||||
script = template.render(**template_vars)
|
||||
@@ -137,6 +153,11 @@ def inference_local(config: InferenceConfig):
|
||||
port = config.server.port
|
||||
logger.info(f"Starting inference on http://{host}:{port}/v1\n")
|
||||
|
||||
# Apply the inference env (defaults + [inference.env_vars]) in-process so a standalone
|
||||
# `uv run inference` gets the same environment the rl/SLURM launchers inject into the
|
||||
# server subprocess. config.env_vars wins over the defaults; existing os.environ loses.
|
||||
os.environ.update({**DEFAULT_COMMON_ENV_VARS, **DEFAULT_INFERENCE_ENV_VARS, **config.env_vars})
|
||||
|
||||
setup_vllm_env(config)
|
||||
|
||||
from prime_rl.inference.vllm.server import server # pyright: ignore
|
||||
|
||||
@@ -12,7 +12,10 @@ from threading import Event, Thread
|
||||
import pynvml
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
from prime_rl.configs.inference import VllmRouterConfig
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.entrypoints.inference import vllm_overrides_fragment
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
@@ -23,7 +26,15 @@ from prime_rl.utils.pathing import (
|
||||
resolve_latest_ckpt_step,
|
||||
validate_output_dir,
|
||||
)
|
||||
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process, set_proc_title
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
DEFAULT_TRAINER_ENV_VARS,
|
||||
cleanup_processes,
|
||||
cleanup_threads,
|
||||
monitor_process,
|
||||
set_proc_title,
|
||||
)
|
||||
|
||||
RL_TOML = "rl.toml"
|
||||
RL_SBATCH = "rl.sbatch"
|
||||
@@ -116,16 +127,16 @@ def rl_local(config: RLConfig):
|
||||
}
|
||||
|
||||
# Validate client port matches inference server port
|
||||
if config.inference is not None and not config.orchestrator.student.client.is_elastic:
|
||||
if config.inference is not None and not config.orchestrator.model.client.is_elastic:
|
||||
from urllib.parse import urlparse
|
||||
|
||||
base_url = config.orchestrator.student.client.base_url[0]
|
||||
base_url = config.orchestrator.model.client.base_url[0]
|
||||
parsed = urlparse(base_url)
|
||||
client_port = parsed.port
|
||||
expected_port = config.inference.server.port
|
||||
if client_port != expected_port:
|
||||
raise ValueError(
|
||||
f"orchestrator.student.client.base_url port ({client_port}) does not match "
|
||||
f"orchestrator.model.client.base_url port ({client_port}) does not match "
|
||||
f"inference.server.port ({expected_port}). "
|
||||
f"Update the base_url to use port {expected_port} to match the inference server."
|
||||
)
|
||||
@@ -160,6 +171,10 @@ def rl_local(config: RLConfig):
|
||||
inference_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
|
||||
},
|
||||
stdout=log_file,
|
||||
@@ -179,19 +194,26 @@ def rl_local(config: RLConfig):
|
||||
monitor_threads.append(monitor_thread)
|
||||
else:
|
||||
logger.warning(
|
||||
"No [inference] block configured - the student inference server will not be started here. "
|
||||
"All training modes (rl/opd/sft) require a student inference pool for evals + weight sync; "
|
||||
"make sure one is running at orchestrator.student.client.base_url "
|
||||
f"({', '.join(config.orchestrator.student.client.base_url)}), otherwise the orchestrator "
|
||||
"No [inference] block configured - the policy inference server will not be started here. "
|
||||
"Every algorithm requires a policy inference pool for evals + weight sync; "
|
||||
"make sure one is running at orchestrator.model.client.base_url "
|
||||
f"({', '.join(config.orchestrator.model.client.base_url)}), otherwise the orchestrator "
|
||||
"will hang waiting for it."
|
||||
)
|
||||
|
||||
if config.orchestrator.teacher:
|
||||
frozen_endpoints: list[str] = []
|
||||
for env in config.orchestrator.train.env:
|
||||
algo = env.algo
|
||||
assert algo is not None, "TrainEnvConfig.algo must be resolved before launch (inherit_env_algorithms)"
|
||||
for ref in (algo.sampling.source, getattr(algo, "teacher", None)):
|
||||
if isinstance(ref, FrozenModelConfig):
|
||||
frozen_endpoints.append(f"{ref.name} ({', '.join(ref.base_url)})")
|
||||
if frozen_endpoints:
|
||||
endpoints = ", ".join(dict.fromkeys(frozen_endpoints))
|
||||
logger.info(
|
||||
"orchestrator.teacher is configured - the rl entrypoint does not start teacher inference "
|
||||
"servers. Make sure your teacher endpoint at "
|
||||
f"{', '.join(config.orchestrator.teacher.client.base_url)} is running before the "
|
||||
"orchestrator starts, otherwise rollouts will hang."
|
||||
"Frozen model references are configured - the rl entrypoint does not start them. "
|
||||
f"Make sure these endpoints are serving before the orchestrator starts: {endpoints}; "
|
||||
"otherwise rollouts will hang."
|
||||
)
|
||||
|
||||
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_TOML).as_posix()]
|
||||
@@ -204,11 +226,14 @@ def rl_local(config: RLConfig):
|
||||
stderr=log_file,
|
||||
env={
|
||||
**os.environ,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "orchestrator",
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
**config.env_vars,
|
||||
**config.orchestrator.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "orchestrator",
|
||||
},
|
||||
)
|
||||
processes.append(orchestrator_process)
|
||||
@@ -250,14 +275,16 @@ def rl_local(config: RLConfig):
|
||||
trainer_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "trainer",
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
|
||||
"PYTHONUNBUFFERED": "1",
|
||||
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
**config.env_vars,
|
||||
**config.trainer.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "trainer",
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
@@ -346,6 +373,21 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
kv_offload_device_name=offload.device_name if is_mooncake else "",
|
||||
)
|
||||
|
||||
# Per-component env vars: launcher defaults (shared + multi-node-specific) with the
|
||||
# user's config merged on top. Runtime wiring stays in the template.
|
||||
trainer_env_vars = {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.trainer.env_vars,
|
||||
}
|
||||
orchestrator_env_vars = {**DEFAULT_COMMON_ENV_VARS, **config.env_vars, **config.orchestrator.env_vars}
|
||||
inference_env_vars = (
|
||||
{**DEFAULT_COMMON_ENV_VARS, **DEFAULT_INFERENCE_ENV_VARS, **config.env_vars, **config.inference.env_vars}
|
||||
if config.inference
|
||||
else {}
|
||||
)
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
@@ -371,18 +413,24 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
num_prefill_replicas=infer_deploy.num_prefill_replicas,
|
||||
num_decode_replicas=infer_deploy.num_decode_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router_port=infer_deploy.router.port,
|
||||
router=infer_deploy.router,
|
||||
prefill_port=infer_deploy.prefill_port,
|
||||
decode_port=infer_deploy.decode_port,
|
||||
inference_tp=config.inference.parallel.tp,
|
||||
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port,
|
||||
use_deep_gemm=config.inference.use_deep_gemm,
|
||||
prefill_env_overrides=infer_deploy.prefill_env_overrides,
|
||||
decode_env_overrides=infer_deploy.decode_env_overrides,
|
||||
prefill_env_vars=infer_deploy.prefill_env_vars,
|
||||
decode_env_vars=infer_deploy.decode_env_vars,
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
orchestrator_env_vars=orchestrator_env_vars,
|
||||
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,
|
||||
**mooncake_vars,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
)
|
||||
else:
|
||||
script = template.render(
|
||||
@@ -396,7 +444,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
nodes_per_infer_replica=config.deployment.num_infer_nodes,
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router_port=config.inference.deployment.router.port if config.inference else 8000,
|
||||
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
|
||||
infer_nodes_per_replica=config.deployment.num_infer_nodes,
|
||||
backend_port=config.inference.deployment.backend_port if config.inference else 8100,
|
||||
inference_tp=config.inference.parallel.tp if config.inference else 1,
|
||||
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
|
||||
@@ -405,6 +454,10 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
**mooncake_vars,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
orchestrator_env_vars=orchestrator_env_vars,
|
||||
inference_env_vars=inference_env_vars,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -12,7 +12,14 @@ from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir, validate_output_dir
|
||||
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process, set_proc_title
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_TRAINER_ENV_VARS,
|
||||
cleanup_processes,
|
||||
cleanup_threads,
|
||||
monitor_process,
|
||||
set_proc_title,
|
||||
)
|
||||
|
||||
SFT_TOML = "sft.toml"
|
||||
SFT_SBATCH = "sft.sbatch"
|
||||
@@ -36,6 +43,12 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path)
|
||||
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
|
||||
template = env.get_template(config.slurm.template_path.name)
|
||||
|
||||
trainer_env_vars = {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
**config.env_vars,
|
||||
}
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
@@ -48,6 +61,7 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path)
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.output_dir,
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
num_nodes=config.deployment.num_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
ranks_filter=",".join(map(str, config.log.ranks_filter)),
|
||||
@@ -143,8 +157,9 @@ def sft_local(config: SFTConfig):
|
||||
trainer_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
"PYTHONUNBUFFERED": "1",
|
||||
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
**config.env_vars,
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
|
||||
+170
-188
@@ -1,5 +1,4 @@
|
||||
import torch
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
|
||||
|
||||
@@ -15,11 +14,90 @@ def transformers_v5_compat():
|
||||
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
|
||||
Qwen3VLMoeTextConfig.tie_word_embeddings = False
|
||||
|
||||
_patch_qwen35_lora()
|
||||
_patch_lora_key_prefix()
|
||||
monkey_patch_deep_gemm_silu_mul_quant_int64()
|
||||
_patch_qwen35_moe_lora_format()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
|
||||
|
||||
def monkey_patch_kv_xfer_finished_tolerate_freed():
|
||||
"""Tolerate KV-transfer finish notifications for already-freed requests.
|
||||
|
||||
In disaggregated P/D (NIXL, optionally + a KV store connector) a request can
|
||||
be finished — most often ``FINISHED_ABORTED`` from an off-policy cancel, a
|
||||
client disconnect, or a request timeout — while it still has in-flight KV
|
||||
transfers. When such a request's ``finished_recving`` and ``finished_sending``
|
||||
both land in the same ``Scheduler.update_from_output`` step, the stock
|
||||
``_update_from_kv_xfer_finished`` frees it in the recving branch
|
||||
(``_free_blocks`` -> ``del self.requests[req_id]``) and then the sending
|
||||
branch hits ``assert req_id in self.requests`` and kills the EngineCore. On a
|
||||
DP deployment that one death cascades to every rank via the gloo finish-state
|
||||
all-reduce, taking down the whole inference pool.
|
||||
|
||||
The trigger is the abort itself, not weight-update pause/resume: it reproduces
|
||||
during normal stepping whenever an aborted request's recv and send complete in
|
||||
the same step (observed with zero off-policy cancellations, driven only by
|
||||
incidental client-side aborts). Skip already-freed request ids instead of
|
||||
asserting — their blocks are freed either way, so dropping the stale
|
||||
notification is safe.
|
||||
|
||||
Upstream issue: https://github.com/vllm-project/vllm/issues/46240
|
||||
"""
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.core.sched.scheduler import Scheduler
|
||||
from vllm.v1.request import RequestStatus
|
||||
|
||||
logger = init_logger("vllm.v1.core.sched.scheduler")
|
||||
|
||||
if getattr(Scheduler._update_from_kv_xfer_finished, "_prime_rl_tolerates_freed", False):
|
||||
return
|
||||
|
||||
def _update_from_kv_xfer_finished(self, kv_connector_output):
|
||||
if self.connector is not None:
|
||||
self.connector.update_connector_output(kv_connector_output)
|
||||
|
||||
for req_id in kv_connector_output.finished_recving or ():
|
||||
logger.debug("Finished recving KV transfer for request %s", req_id)
|
||||
# Stale notification for a request freed earlier this step (e.g. an
|
||||
# aborted request whose send completion freed it). Nothing to do.
|
||||
if req_id not in self.requests:
|
||||
continue
|
||||
req = self.requests[req_id]
|
||||
if req.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
|
||||
self.finished_recving_kv_req_ids.add(req_id)
|
||||
else:
|
||||
assert RequestStatus.is_finished(req.status)
|
||||
self._free_blocks(self.requests[req_id])
|
||||
for req_id in kv_connector_output.finished_sending or ():
|
||||
logger.debug("Finished sending KV transfer for request %s", req_id)
|
||||
# See above: the recving branch may have already freed an aborted
|
||||
# request whose send also completed this step.
|
||||
if req_id not in self.requests:
|
||||
continue
|
||||
self._free_blocks(self.requests[req_id])
|
||||
|
||||
_update_from_kv_xfer_finished._prime_rl_tolerates_freed = True
|
||||
Scheduler._update_from_kv_xfer_finished = _update_from_kv_xfer_finished
|
||||
logger.warning("Patched Scheduler._update_from_kv_xfer_finished to tolerate freed (aborted) KV-transfer reqs.")
|
||||
|
||||
|
||||
def monkey_patch_nano_v3_reasoning_parser():
|
||||
from vllm.reasoning.abs_reasoning_parsers import ReasoningParserManager
|
||||
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
|
||||
|
||||
class NanoV3ReasoningParser(DeepSeekR1ReasoningParser):
|
||||
def extract_reasoning(self, model_output, request):
|
||||
reasoning_content, final_content = super().extract_reasoning(model_output, request)
|
||||
chat_template_kwargs = getattr(request, "chat_template_kwargs", None)
|
||||
|
||||
if chat_template_kwargs and chat_template_kwargs.get("enable_thinking") is False and final_content is None:
|
||||
reasoning_content, final_content = final_content, reasoning_content
|
||||
|
||||
return reasoning_content, final_content
|
||||
|
||||
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
@@ -66,200 +144,66 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel(
|
||||
y_ptr,
|
||||
y_q_ptr,
|
||||
y_s_ptr,
|
||||
M: tl.int64,
|
||||
N: tl.int64,
|
||||
y_s_col_stride: tl.int64,
|
||||
eps,
|
||||
clamp_limit,
|
||||
fp8_min: tl.constexpr,
|
||||
fp8_max: tl.constexpr,
|
||||
use_ue8m0: tl.constexpr,
|
||||
HAS_CLAMP: tl.constexpr,
|
||||
GROUP_SIZE: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
):
|
||||
pid_m = tl.program_id(0)
|
||||
pid_n = tl.program_id(1)
|
||||
N_2 = N // 2
|
||||
|
||||
m_offset = (pid_m * BLOCK_M).to(tl.int64)
|
||||
n_offset = (pid_n * BLOCK_N).to(tl.int64)
|
||||
if m_offset >= M:
|
||||
return
|
||||
|
||||
offs_n = tl.arange(0, BLOCK_N).to(tl.int64)
|
||||
offs_m = tl.arange(0, BLOCK_M).to(tl.int64)
|
||||
|
||||
base_y_ptr = y_ptr + m_offset * N + n_offset
|
||||
act_in_ptrs = base_y_ptr + offs_m[:, None] * N + offs_n[None, :]
|
||||
|
||||
act_in = tl.load(act_in_ptrs)
|
||||
mul_in = tl.load(act_in_ptrs + N_2)
|
||||
|
||||
if HAS_CLAMP:
|
||||
act_in = tl.minimum(act_in.to(tl.float32), clamp_limit).to(y_ptr.dtype.element_ty)
|
||||
mul_in = tl.clamp(mul_in.to(tl.float32), -clamp_limit, clamp_limit).to(y_ptr.dtype.element_ty)
|
||||
act_in = act_in.to(tl.float32)
|
||||
one_f32 = tl.cast(1, tl.float32)
|
||||
silu_out = (act_in / (one_f32 + tl.exp(-act_in))).to(y_ptr.dtype.element_ty)
|
||||
y = (silu_out * mul_in).to(tl.float32)
|
||||
|
||||
absmax = tl.maximum(tl.max(tl.abs(y), axis=1), eps)
|
||||
scale_raw = absmax * (1.0 / fp8_max)
|
||||
y_s = tl.math.exp2(tl.ceil(tl.log2(scale_raw))) if use_ue8m0 else scale_raw
|
||||
y_s = tl.reshape(y_s, (BLOCK_M, 1))
|
||||
y_q = tl.clamp(y / y_s, fp8_min, fp8_max).to(y_q_ptr.dtype.element_ty)
|
||||
|
||||
base_y_q_ptr = y_q_ptr + m_offset * N_2 + n_offset
|
||||
y_q_ptrs = base_y_q_ptr + offs_m[:, None] * N_2 + offs_n[None, :]
|
||||
tl.store(y_q_ptrs, y_q)
|
||||
|
||||
group_id = n_offset // GROUP_SIZE
|
||||
base_y_s_ptr = y_s_ptr + group_id * y_s_col_stride + m_offset
|
||||
y_s_ptrs = base_y_s_ptr + offs_m
|
||||
y_s = tl.reshape(y_s, (BLOCK_M,))
|
||||
tl.store(y_s_ptrs, y_s)
|
||||
|
||||
|
||||
def _silu_mul_per_token_group_quant_fp8_colmajor_int64(
|
||||
input: torch.Tensor,
|
||||
output: torch.Tensor | None = None,
|
||||
use_ue8m0: bool | None = None,
|
||||
eps: float = 1e-10,
|
||||
clamp_limit: float | None = None,
|
||||
):
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.deep_gemm import is_deep_gemm_e8m0_used
|
||||
|
||||
group_size = 128
|
||||
assert input.ndim == 2
|
||||
if output is not None:
|
||||
assert output.ndim == 2
|
||||
assert input.size(0) % group_size == 0
|
||||
assert input.size(1) % (group_size * 2) == 0
|
||||
|
||||
if use_ue8m0 is None:
|
||||
use_ue8m0 = is_deep_gemm_e8m0_used()
|
||||
|
||||
M, N = input.size()
|
||||
N_2 = N // 2
|
||||
|
||||
fp8_dtype = current_platform.fp8_dtype()
|
||||
if output is None:
|
||||
output = torch.empty((M, N_2), dtype=fp8_dtype, device=input.device)
|
||||
|
||||
output_scales = torch.empty(((N_2 // group_size), M), dtype=torch.float32, device=input.device).transpose(0, 1)
|
||||
|
||||
block_m = 8
|
||||
block_n = group_size
|
||||
assert M % block_m == 0
|
||||
assert N_2 % block_n == 0
|
||||
|
||||
finfo = torch.finfo(fp8_dtype)
|
||||
fp8_min = -224.0 if current_platform.is_fp8_fnuz() else finfo.min
|
||||
fp8_max = 224.0 if current_platform.is_fp8_fnuz() else finfo.max
|
||||
|
||||
has_clamp = clamp_limit is not None
|
||||
grid = (M // block_m, N_2 // block_n)
|
||||
_silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel[grid](
|
||||
input,
|
||||
output,
|
||||
output_scales,
|
||||
M,
|
||||
N,
|
||||
output_scales.stride(-1),
|
||||
eps,
|
||||
clamp_limit if has_clamp else 0.0,
|
||||
fp8_min,
|
||||
fp8_max,
|
||||
use_ue8m0,
|
||||
has_clamp,
|
||||
group_size,
|
||||
block_m,
|
||||
block_n,
|
||||
)
|
||||
|
||||
return output, output_scales
|
||||
|
||||
|
||||
def monkey_patch_deep_gemm_silu_mul_quant_int64():
|
||||
import sys
|
||||
def monkey_patch_strip_routed_experts_from_chat():
|
||||
"""Drop routed_experts from chat-completions responses.
|
||||
|
||||
routed_experts are only consumed via the serialized ``/generate``
|
||||
(serving_tokens) path used for router-replay training, which encodes them as a
|
||||
``{data, shape, start}`` object the PD router can merge. The stock
|
||||
chat-completions path instead encodes them as a base64 ``np.save`` *string*,
|
||||
which the PD router rejects ("prefill routed_experts must be an object with
|
||||
base64 data and shape") and fails every eval rollout (evals go through chat
|
||||
completions). ``enable_return_routed_experts`` is a server-wide model-config
|
||||
flag with no per-request toggle, so strip the field on the chat path here.
|
||||
"""
|
||||
from vllm.entrypoints.openai.chat_completion.serving import OpenAIServingChat
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization.utils import fp8_utils
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
fp8_utils.silu_mul_per_token_group_quant_fp8_colmajor = _silu_mul_per_token_group_quant_fp8_colmajor_int64
|
||||
if getattr(OpenAIServingChat.chat_completion_full_generator, "_prime_rl_strips_routed_experts", False):
|
||||
return
|
||||
|
||||
deep_gemm_moe_module = sys.modules.get("vllm.model_executor.layers.fused_moe.experts.deep_gemm_moe")
|
||||
if deep_gemm_moe_module is not None:
|
||||
deep_gemm_moe_module.silu_mul_per_token_group_quant_fp8_colmajor = (
|
||||
_silu_mul_per_token_group_quant_fp8_colmajor_int64
|
||||
)
|
||||
_original = OpenAIServingChat.chat_completion_full_generator
|
||||
|
||||
logger.warning("Enabled int64-addressing Triton patch for vLLM DeepGEMM SiLU/mul FP8 quant.")
|
||||
async def _strip(result_generator):
|
||||
async for res in result_generator:
|
||||
for output in res.outputs:
|
||||
output.routed_experts = None
|
||||
yield res
|
||||
|
||||
async def _patched(self, request, result_generator, *args, **kwargs):
|
||||
return await _original(self, request, _strip(result_generator), *args, **kwargs)
|
||||
|
||||
_patched._prime_rl_strips_routed_experts = True
|
||||
OpenAIServingChat.chat_completion_full_generator = _patched
|
||||
logger.info(
|
||||
"Stripped routed_experts from chat-completions responses (PD router merges only the /generate object form)."
|
||||
)
|
||||
|
||||
|
||||
def _patch_qwen35_lora():
|
||||
"""Fix Qwen3.5 LoRA: align packed_modules_mapping with output_sizes.
|
||||
def _patch_qwen35_moe_lora_format():
|
||||
"""Force Qwen3.5-MoE onto vLLM's 2D per-expert LoRA format.
|
||||
|
||||
Qwen3.5's GDN layers use create_qkvz_proj with 4 output_sizes (q, k, v, z)
|
||||
but packed_modules_mapping only lists 2 entries, causing an IndexError
|
||||
during LoRA initialization.
|
||||
vLLM 0.23.0 defaults ``Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = True``,
|
||||
which makes the LoRA loader expect 3D stacked-expert adapters
|
||||
(``base_layer.lora_{A,B}.weight`` / ``lora_{A,B}.weight``, experts folded into the
|
||||
rank dim; see ``_stack_moe_lora_weights``). Our trainer instead emits the 2D
|
||||
per-expert layout (``{expert_id}.gate_proj.lora_A.weight`` ...) from
|
||||
``MultiLoRAGroupedExperts.state_dict_for_adapter`` -- vLLM only consults that layout
|
||||
when ``is_3d_moe_weight`` is False (or ``enable_mixed_moe_lora_format=True``).
|
||||
Without this override the adapters fail to load with key/shape mismatches.
|
||||
|
||||
Also generalizes MergedColumnParallelLinearWithLoRA.can_replace_layer
|
||||
to accept any number of packed modules (not just 2), and generalizes
|
||||
MergedColumnParallelLinearWithShardedLoRA.slice_lora_a to handle N
|
||||
subloras instead of the hardcoded 2 (needed for fully_sharded_loras=True).
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/issues/36372
|
||||
The rest of the old Qwen3.5 LoRA shim (the in_proj_qkvz packed-mapping fix and the
|
||||
N-slice ``can_replace_layer`` / ``slice_lora_a`` generalizations for vllm#36372) is
|
||||
handled natively by 0.23.0 and was dropped. Remove this too once we either adopt the
|
||||
3D stacked save format (like gpt-oss) or start the engine with
|
||||
``enable_mixed_moe_lora_format=True``.
|
||||
"""
|
||||
from vllm.lora.layers.column_parallel_linear import (
|
||||
MergedColumnParallelLinearWithLoRA,
|
||||
MergedColumnParallelLinearWithShardedLoRA,
|
||||
)
|
||||
from vllm.model_executor.models.qwen3_5 import (
|
||||
Qwen3_5ForCausalLMBase,
|
||||
Qwen3_5ForConditionalGeneration,
|
||||
Qwen3_5MoeForConditionalGeneration,
|
||||
)
|
||||
|
||||
qkvz_fix = ["in_proj_q", "in_proj_k", "in_proj_v", "in_proj_z"]
|
||||
|
||||
Qwen3_5ForCausalLMBase.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
|
||||
Qwen3_5ForConditionalGeneration.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
|
||||
from vllm.model_executor.models.qwen3_5 import Qwen3_5MoeForConditionalGeneration
|
||||
|
||||
Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = False
|
||||
|
||||
from vllm.lora.layers.utils import _not_fully_sharded_can_replace
|
||||
|
||||
@classmethod
|
||||
@_not_fully_sharded_can_replace
|
||||
def can_replace_layer(cls, source_layer, lora_config, packed_modules_list, model_config=None):
|
||||
from vllm.model_executor.layers.linear import MergedColumnParallelLinear
|
||||
|
||||
return type(source_layer) is MergedColumnParallelLinear and len(packed_modules_list) == len(
|
||||
source_layer.output_sizes
|
||||
)
|
||||
|
||||
MergedColumnParallelLinearWithLoRA.can_replace_layer = can_replace_layer
|
||||
|
||||
def slice_lora_a(self, lora_a):
|
||||
output_shard_size = self.lora_a_stacked[0].shape[2]
|
||||
output_start_idx = self.tp_rank * output_shard_size
|
||||
return [
|
||||
a[output_start_idx : output_start_idx + output_shard_size, :] if a is not None else None for a in lora_a
|
||||
]
|
||||
|
||||
MergedColumnParallelLinearWithShardedLoRA.slice_lora_a = slice_lora_a
|
||||
|
||||
|
||||
def _patch_lora_key_prefix():
|
||||
"""Patch vLLM's LoRA loading to handle keys without base_model.model. prefix.
|
||||
@@ -663,9 +607,10 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
still runs for all wrapped layers when any adapter is active — and it
|
||||
asserts inputs are float16/bfloat16. Qwen3 MoE doesn't have this
|
||||
problem because its gate uses the model dtype.
|
||||
Fix: recreate the gate in model dtype and remove the float32 cast.
|
||||
FusedMoE already has router_logits_dtype=float32, so routing precision
|
||||
is preserved inside the expert dispatch.
|
||||
Fix: rebuild the gate as GateLinear with a bf16 weight (out_dtype=float32
|
||||
keeps fp32 router logits). vLLM 0.23.0's own forward already drops the
|
||||
float32 input cast. FusedMoE also has router_logits_dtype=float32, so
|
||||
routing precision is preserved inside the expert dispatch.
|
||||
|
||||
Problem 2 — Adapter key naming mismatch:
|
||||
PrimeRL saves adapter keys using its internal naming convention
|
||||
@@ -687,13 +632,17 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
|
||||
def _patched_init(self, config, quant_config=None, prefix=""):
|
||||
_original_init(self, config, quant_config, prefix)
|
||||
from vllm.model_executor.layers.linear import ReplicatedLinear
|
||||
from vllm.model_executor.layers.fused_moe.router.gate_linear import GateLinear
|
||||
|
||||
self.gate = ReplicatedLinear(
|
||||
# vLLM 0.23.0 builds the gate as GateLinear with a float32 weight; rebuild it
|
||||
# with a bf16 weight (model dtype) so the LoRA Triton kernel's float16/bfloat16
|
||||
# assertion passes, keeping out_dtype=float32 so router logits stay fp32 (the
|
||||
# GateLinear bf16xbf16->fp32 path).
|
||||
self.gate = GateLinear(
|
||||
config.hidden_size,
|
||||
config.num_local_experts,
|
||||
bias=False,
|
||||
quant_config=None,
|
||||
out_dtype=torch.float32,
|
||||
prefix=f"{prefix}.gate",
|
||||
)
|
||||
|
||||
@@ -836,3 +785,36 @@ def monkey_patch_fp32_lm_head():
|
||||
LogitsProcessor.__init__ = _patched_init
|
||||
LogitsProcessor._get_logits = _patched_get_logits
|
||||
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
|
||||
|
||||
|
||||
def monkey_patch_dp_coordinator_startup_timeout():
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 30s.
|
||||
|
||||
The coordinator child process is spawned on the DP-rank-0 API server while
|
||||
every engine-core rank on the node is importing and loading weights, so its
|
||||
own spawn-time re-import can take well over 30s under that CPU/IO
|
||||
contention (seen on multi-node disaggregated GLM-5.1 launches). Configurable
|
||||
via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT (seconds, default 300).
|
||||
"""
|
||||
import multiprocessing.connection
|
||||
import os
|
||||
|
||||
from vllm.v1.engine.coordinator import DPCoordinator
|
||||
|
||||
timeout = float(os.environ.get("PRIME_DP_COORDINATOR_STARTUP_TIMEOUT", "300"))
|
||||
|
||||
def _patched_wait_for_zmq_addrs(self, zmq_addr_pipe):
|
||||
try:
|
||||
ready = multiprocessing.connection.wait([zmq_addr_pipe, self.proc.sentinel], timeout=timeout)
|
||||
if not ready:
|
||||
raise RuntimeError(
|
||||
f"DP Coordinator process failed to report ZMQ addresses within {timeout}s during startup."
|
||||
)
|
||||
try:
|
||||
return zmq_addr_pipe.recv()
|
||||
except EOFError:
|
||||
raise RuntimeError("DP Coordinator process failed during startup.") from None
|
||||
finally:
|
||||
zmq_addr_pipe.close()
|
||||
|
||||
DPCoordinator._wait_for_zmq_addrs = _patched_wait_for_zmq_addrs
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user