Compare commits
32
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
@@ -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}")
|
||||
|
||||
@@ -2,6 +2,15 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **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.
|
||||
|
||||
+86
-3
@@ -77,26 +77,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 +176,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
|
||||
|
||||
@@ -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"
|
||||
@@ -6,6 +6,7 @@ enable_token_export = true
|
||||
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
|
||||
|
||||
@@ -19,6 +19,10 @@ training_mode = "sft"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text-v1"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
args = { v1 = true }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference]
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
@@ -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"
|
||||
|
||||
@@ -9,9 +9,8 @@ Minimal end-to-end configs for the three training modes (`rl` / `opd` / `sft`) a
|
||||
| `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.
|
||||
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`) is **not** auto-launched — start it manually on GPU 1.
|
||||
|
||||
## Start the local teacher
|
||||
|
||||
@@ -38,10 +37,6 @@ 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.
|
||||
|
||||
@@ -20,6 +20,10 @@ training_mode = "sft"
|
||||
batch_size = 128
|
||||
group_size = 4
|
||||
|
||||
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -20,6 +20,10 @@ training_mode = "sft"
|
||||
batch_size = 128
|
||||
group_size = 4
|
||||
|
||||
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
|
||||
@@ -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,55 @@
|
||||
# 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]
|
||||
training_mode = "rl"
|
||||
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,42 @@
|
||||
# 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]
|
||||
training_mode = "rl"
|
||||
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"
|
||||
@@ -0,0 +1,86 @@
|
||||
# v1 port of configs/rlm_swe/qwen35_4b.toml — identical except the env blocks, which load
|
||||
# the v1 `r2e-gym-v1` taskset through the rlm harness on the prime runtime instead of the
|
||||
# v0 `rlm_swe` composable env. Same model / trainer / inference / orchestrator knobs.
|
||||
|
||||
output_dir = "/beegfs/mika/rlm-swe-qwen35-4b"
|
||||
max_steps = 400
|
||||
seq_len = 65536
|
||||
|
||||
[slurm]
|
||||
job_name = "rlm-swe-qwen35-4b"
|
||||
project_dir = "."
|
||||
pre_run_command = "prime sandbox delete --label rlm-swe-qwen35-4b -y --plain || true"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 2
|
||||
|
||||
[wandb]
|
||||
project = "rlm-swe-debug"
|
||||
name = "qwen35-4b"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3.5-4B"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 8
|
||||
max_inflight_rollouts = 512
|
||||
max_off_policy_steps = 16
|
||||
|
||||
# Thinking enabled for the Qwen3.5 renderer.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3.5"
|
||||
enable_thinking = true
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 1.0
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "rlm-swe-r2e"
|
||||
taskset = { id = "r2e-gym-v1" }
|
||||
harness = { id = "rlm", runtime = { type = "prime", labels = ["rlm-swe-qwen35-4b"] } }
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
enable_prefix_caching = true
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 65536
|
||||
|
||||
[inference.parallel]
|
||||
dp = 8
|
||||
|
||||
# Qwen3.5-4B is a VL model; skip the vision tower for text-only SWE.
|
||||
# `language_model_only` is a vLLM MultiModalConfig arg (no prime-rl field) → pass via vllm_extra.
|
||||
[inference.vllm_extra]
|
||||
language_model_only = true
|
||||
@@ -0,0 +1,42 @@
|
||||
# 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]
|
||||
training_mode = "rl"
|
||||
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"
|
||||
@@ -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_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
decode_env_overrides = {"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"
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -60,7 +60,6 @@ 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"]
|
||||
@@ -73,8 +72,7 @@ interval = 20
|
||||
[[orchestrator.eval.env]]
|
||||
id = "rlm_swe"
|
||||
name = "rlm-swe-swebench-verified-quick"
|
||||
num_workers = 4
|
||||
timeout = 3600
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.args]
|
||||
task_type = "swebench"
|
||||
|
||||
@@ -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 the qwen3 renderer's preserve_all_thinking.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
preserve_all_thinking = true
|
||||
Vendored
+1
-1
Submodule deps/pydantic-config updated: 896ade4e69...99f47c6cc0
Vendored
+1
-1
Submodule deps/renderers updated: e6dba5ad6c...1933293372
Vendored
+1
-1
Submodule deps/research-environments updated: 841f9a54df...99ebd2e133
Vendored
+1
-1
Submodule deps/verifiers updated: 78c1b3c545...aa95826d4e
+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.
|
||||
+13
-3
@@ -136,10 +136,20 @@ The default advantage is per-group reward minus per-group baseline (DR-GRPO with
|
||||
|
||||
This is intentionally simple — it does the right thing for most envs. Switch to a [custom advantage](#custom-advantage) when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …).
|
||||
|
||||
Two built-in **length penalties** can be layered on top of any advantage to discourage rambling:
|
||||
A **length penalty** can be layered on top of the default advantage to discourage rambling. Configured under `[orchestrator.advantage.length_penalty]`, it subtracts a `coef * pass_rate * (completion tokens / orchestrator.seq_len)` term from every reward before the baseline subtraction, where `pass_rate` is the problem's mean reward across the group. The pass-rate factor means problems the model already solves reliably get the strongest push toward concise outputs, while rarely-solved problems are barely penalized (a never-solved group, mean reward 0, gets none). Set `gate_by_correctness = true` to apply the penalty only to correct rollouts (`reward == 1`), leaving incorrect ones untouched:
|
||||
|
||||
- `[orchestrator.length_penalty] type = "tokens"` — penalizes long completions in tokens, with configurable target and slope.
|
||||
- `[orchestrator.length_penalty] type = "turns"` — penalizes long multi-turn rollouts by turn count.
|
||||
```toml
|
||||
[orchestrator.advantage.length_penalty]
|
||||
coef = 0.25 # effective penalty is coef * pass_rate * (completion_tokens / seq_len)
|
||||
gate_by_correctness = false # when true, only penalize rollouts with reward == 1
|
||||
```
|
||||
|
||||
By default the baseline is the plain group mean reward. Set `length_weighted_baseline = true` to instead use the token-length-weighted mean — `sum(len_i * reward_i) / sum(len_i)` — which centers advantages by per-token expected reward when rollouts vary a lot in length:
|
||||
|
||||
```toml
|
||||
[orchestrator.advantage]
|
||||
length_weighted_baseline = true
|
||||
```
|
||||
|
||||
|
||||
### Custom Advantage
|
||||
|
||||
+19
-4
@@ -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,9 +167,22 @@ 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
|
||||
|
||||
@@ -232,6 +245,8 @@ 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
|
||||
|
||||
+15
-27
@@ -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,41 @@ 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 = "auto" # picks 8192 for RL
|
||||
# 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,7 +174,7 @@ 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
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
# 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
|
||||
```
|
||||
|
||||
Output of the command:
|
||||
```
|
||||
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/glm5-llmd/configs [rl.py::515]
|
||||
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/glm5-llmd/rl.sbatch [rl.py::534]
|
||||
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/glm5-llmd/rl.sbatch [rl.py::540]
|
||||
XXX:XX:XX SUCCESS Submitted batch job YYYY
|
||||
|
||||
Logs:
|
||||
Trainer: tail -F /shared/outputs/glm5-llmd/logs/trainer.log
|
||||
Orchestrator: tail -F /shared/outputs/glm5-llmd/logs/orchestrator.log
|
||||
Inference: tail -F /shared/outputs/glm5-llmd/logs/inference.log
|
||||
Envs: tail -F /shared/outputs/glm5-llmd/logs/envs/*/*/*.log
|
||||
```
|
||||
@@ -0,0 +1,140 @@
|
||||
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_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
decode_env_overrides = {"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"
|
||||
preserve_all_thinking = true
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 1.0
|
||||
extra_body = {chat_template_kwargs = {clear_thinking = false}}
|
||||
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "rlm_swe"
|
||||
name = "r2e"
|
||||
num_workers = 16
|
||||
|
||||
[orchestrator.train.env.args]
|
||||
max_turns = 300
|
||||
timeout_seconds = 21600
|
||||
summarize_at_tokens = [35000, 80000]
|
||||
poll_interval = 5
|
||||
rlm_ref = "907115a79b2a50d193863e7ea1f3550acb4386f0"
|
||||
labels = ["glm5-llmd"]
|
||||
|
||||
[orchestrator.advantage]
|
||||
type = "default"
|
||||
|
||||
[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
|
||||
@@ -10,6 +10,7 @@ dependencies = [
|
||||
"renderers>=0.1.8.dev28",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.1.15.dev388",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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):
|
||||
@@ -240,6 +306,12 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
decode_env_overrides: dict[str, str] = {}
|
||||
"""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
|
||||
@@ -369,6 +441,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,10 +1,9 @@
|
||||
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.shared import (
|
||||
@@ -143,31 +142,85 @@ class EvalSamplingConfig(BaseConfig):
|
||||
return data
|
||||
|
||||
|
||||
class TokensLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["tokens"] = "tokens"
|
||||
class EnvConfig(vf.EnvServerConfig):
|
||||
name: str | None = None
|
||||
"""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."""
|
||||
|
||||
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on model completion tokens. Finite and non-negative."""
|
||||
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. The ``pool`` sizes the spawned server."""
|
||||
|
||||
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."""
|
||||
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)."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Times the env server retries a failed rollout before returning an error."""
|
||||
|
||||
@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 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.env_id
|
||||
|
||||
@model_validator(mode="after")
|
||||
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 == "all":
|
||||
raise ValueError(
|
||||
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
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
|
||||
|
||||
|
||||
class TurnsLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["turns"] = "turns"
|
||||
class LinearLengthPenaltyConfig(BaseConfig):
|
||||
coef: float = Field(0.25, ge=0, allow_inf_nan=False)
|
||||
"""Scale on the linear length penalty. Each reward is reduced by ``coef * pass_rate * (model completion tokens / orchestrator.seq_len)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative."""
|
||||
|
||||
|
||||
LengthPenaltyConfig: TypeAlias = Annotated[
|
||||
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
gate_by_correctness: bool = False
|
||||
"""When True, scale each rollout's penalty by its reward (``penalty * reward``), so correct rollouts (``reward == 1``) are penalized and incorrect ones (``reward == 0``) are not. When False, every rollout is penalized equally."""
|
||||
|
||||
|
||||
class DefaultAdvantageConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
length_penalty: 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."""
|
||||
length_penalty: LinearLengthPenaltyConfig | None = None
|
||||
"""Length penalty applied during advantage computation. Subtracts a ``coef * pass_rate * (completion tokens / orchestrator.seq_len)`` term from each reward (``pass_rate`` = group mean reward) before the baseline subtraction, so solved-often problems get the strongest concision pressure and never-solved groups get none. None disables the penalty."""
|
||||
|
||||
length_weighted_baseline: bool = False
|
||||
"""When True, the GRPO baseline is the token-length-weighted mean reward (``sum(len_i * reward_i) / sum(len_i)``) instead of the plain group mean, centering advantages by per-token expected reward."""
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseConfig):
|
||||
@@ -186,69 +239,6 @@ AdvantageConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
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."""
|
||||
|
||||
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."""
|
||||
|
||||
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."""
|
||||
|
||||
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)."""
|
||||
|
||||
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."""
|
||||
|
||||
@property
|
||||
def stripped_id(self) -> str:
|
||||
"""Environment ID without the @version suffix."""
|
||||
return self.id.split("@")[0]
|
||||
|
||||
@property
|
||||
def resolved_name(self) -> str:
|
||||
return self.name or self.stripped_id
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env_name(self):
|
||||
if self.resolved_name == "all":
|
||||
raise ValueError(
|
||||
'Environment name "all" is reserved for global 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
|
||||
return self
|
||||
|
||||
|
||||
class TrainEnvConfig(EnvConfig):
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
|
||||
@@ -278,21 +268,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 +288,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 +313,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 +325,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 +337,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 +352,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")
|
||||
@@ -518,30 +493,16 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
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."""
|
||||
@@ -630,9 +591,6 @@ 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")
|
||||
@@ -757,51 +715,14 @@ 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
|
||||
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
|
||||
|
||||
@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:
|
||||
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."
|
||||
)
|
||||
if self.training_mode in ("opd", "sft") and not has_teacher:
|
||||
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -817,7 +738,7 @@ 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
|
||||
|
||||
@@ -835,9 +756,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")
|
||||
@@ -885,12 +804,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
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 +822,15 @@ 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 on each train env from top-level fields."""
|
||||
if self.training_mode == "sft":
|
||||
return self
|
||||
for env in self.train.env:
|
||||
env.extra_env_kwargs.update(max_seq_len=self.seq_len)
|
||||
if is_vllm:
|
||||
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)
|
||||
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
|
||||
|
||||
@@ -438,6 +438,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 (
|
||||
|
||||
@@ -347,18 +347,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
|
||||
|
||||
@@ -83,10 +83,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 +96,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."""
|
||||
|
||||
|
||||
@@ -122,19 +122,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 +143,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 +188,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["auto", "disabled"] = 1024
|
||||
"""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. SFT training silently disables this (not supported yet)."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
@@ -258,7 +258,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
|
||||
@@ -666,7 +666,7 @@ class TrainerConfig(BaseConfig):
|
||||
|
||||
@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
|
||||
|
||||
+75
-50
@@ -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.dev400",
|
||||
"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,36 +66,47 @@ flash-attn-cute = [
|
||||
"flash-attn-4",
|
||||
]
|
||||
envs = [
|
||||
"aime2024",
|
||||
"aime2025",
|
||||
"alphabet-sort",
|
||||
"code-env",
|
||||
"color-codeword",
|
||||
"deepdive",
|
||||
"general-agent",
|
||||
"gpqa",
|
||||
"hle",
|
||||
"ifeval",
|
||||
"livecodebench",
|
||||
"logic-env",
|
||||
"math-env",
|
||||
"math-python",
|
||||
"math500",
|
||||
"mini-swe-agent-plus",
|
||||
"mmlu-pro",
|
||||
"opencode-cp",
|
||||
"opencode-deepdive",
|
||||
"opencode-math",
|
||||
"opencode-science",
|
||||
"opencode-swe",
|
||||
"reverse-text",
|
||||
"rlm-swe",
|
||||
"rlm-search",
|
||||
"science-env",
|
||||
"simpleqa-verified",
|
||||
"tau2-bench",
|
||||
"uuid-ctf-v1",
|
||||
"wiki-search",
|
||||
"wordle",
|
||||
"reverse-text-v1",
|
||||
"gsm8k-v1",
|
||||
"math-env-v1",
|
||||
"aime24-v1",
|
||||
"aime25-v1",
|
||||
"aime26-v1",
|
||||
"alphabet-sort-v1",
|
||||
"scaleswe-v1",
|
||||
"color-codeword-v1",
|
||||
"deepdive-v1",
|
||||
"gpqa-v1",
|
||||
"livecodebench-v1",
|
||||
"r2e-gym-v1",
|
||||
"terminal-bench-2-v1",
|
||||
"code-golf-v1",
|
||||
"deepwiki-v1",
|
||||
"glossary-v1",
|
||||
"swelego-v1",
|
||||
"wiki-search-v1",
|
||||
"wikispeedia-v1",
|
||||
"wordle-v1",
|
||||
"general-agent-v1",
|
||||
"swebench-verified-v1",
|
||||
"tau2-bench-v1",
|
||||
"math500-v1",
|
||||
"mmlu-pro-v1",
|
||||
"ifeval-v1",
|
||||
"simpleqa-verified-v1",
|
||||
"i3-code-v1",
|
||||
"i3-science-v1",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
@@ -152,7 +166,7 @@ override-dependencies = [
|
||||
"transformers==5.6.2",
|
||||
"torch>=2.9.0",
|
||||
"openenv-core",
|
||||
"verifiers[packages]>=0.1.15.dev150",
|
||||
"verifiers>=0.1.15.dev400",
|
||||
]
|
||||
|
||||
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
|
||||
@@ -187,8 +201,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
|
||||
@@ -199,41 +211,54 @@ 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 }
|
||||
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
|
||||
code-env = { path = "deps/research-environments/environments/code_env", editable = true }
|
||||
color-codeword = { path = "deps/research-environments/environments/color_codeword", editable = true }
|
||||
deepdive = { path = "deps/research-environments/environments/deepdive", editable = true }
|
||||
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
|
||||
gpqa = { path = "deps/research-environments/environments/gpqa", editable = true }
|
||||
harnesses = { path = "deps/verifiers/packages/harnesses", editable = true }
|
||||
hle = { path = "deps/research-environments/environments/hle", editable = true }
|
||||
ifeval = { path = "deps/research-environments/environments/ifeval", editable = true }
|
||||
livecodebench = { path = "deps/research-environments/environments/livecodebench", editable = true }
|
||||
logic-env = { path = "deps/research-environments/environments/logic_env", editable = true }
|
||||
math-env = { path = "deps/research-environments/environments/math_env", editable = true }
|
||||
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
|
||||
math500 = { path = "deps/research-environments/environments/math500", editable = true }
|
||||
mini-swe-agent-plus = { path = "deps/research-environments/environments/mini_swe_agent_plus", editable = true }
|
||||
mmlu-pro = { path = "deps/research-environments/environments/mmlu_pro", editable = true }
|
||||
opencode-cp = { path = "deps/research-environments/environments/opencode_cp", editable = true }
|
||||
opencode-deepdive = { path = "deps/research-environments/environments/opencode_deepdive", editable = true }
|
||||
opencode-math = { path = "deps/research-environments/environments/opencode_math", editable = true }
|
||||
opencode-science = { path = "deps/research-environments/environments/opencode_science", editable = true }
|
||||
opencode-swe = { path = "deps/research-environments/environments/opencode_swe", editable = true }
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
|
||||
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
|
||||
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 }
|
||||
uuid-ctf-v1 = { path = "deps/research-environments/environments/uuid_ctf_v1", editable = true }
|
||||
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
|
||||
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
|
||||
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
|
||||
gsm8k-v1 = { path = "deps/verifiers/environments/gsm8k_v1", editable = true }
|
||||
math-env-v1 = { path = "deps/research-environments/environments/math_env_v1", 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-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
|
||||
scaleswe-v1 = { path = "deps/research-environments/environments/scaleswe_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 }
|
||||
gpqa-v1 = { path = "deps/research-environments/environments/gpqa_v1", editable = true }
|
||||
livecodebench-v1 = { path = "deps/research-environments/environments/livecodebench_v1", editable = true }
|
||||
r2e-gym-v1 = { path = "deps/research-environments/environments/r2e_gym_v1", editable = true }
|
||||
terminal-bench-2-v1 = { path = "deps/research-environments/environments/terminal_bench_2_v1", editable = true }
|
||||
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_v1", editable = true }
|
||||
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
|
||||
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
|
||||
swelego-v1 = { path = "deps/research-environments/environments/swelego_v1", 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-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
|
||||
general-agent-v1 = { path = "deps/research-environments/environments/general_agent_v1", editable = true }
|
||||
swebench-verified-v1 = { path = "deps/research-environments/environments/swebench_verified_v1", editable = true }
|
||||
tau2-bench-v1 = { path = "deps/research-environments/environments/tau2_bench_v1", 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 }
|
||||
ifeval-v1 = { path = "deps/research-environments/environments/ifeval_v1", editable = true }
|
||||
simpleqa-verified-v1 = { path = "deps/research-environments/environments/simpleqa_verified_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 }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
@@ -242,8 +267,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"
|
||||
+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
|
||||
|
||||
|
||||
+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
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import tomli_w
|
||||
|
||||
@@ -14,6 +16,17 @@ 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,7 +60,7 @@ 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,
|
||||
@@ -65,20 +78,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_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)
|
||||
|
||||
@@ -12,7 +12,9 @@ from threading import Event, Thread
|
||||
import pynvml
|
||||
import tomli_w
|
||||
|
||||
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 (
|
||||
@@ -371,7 +373,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
num_prefill_replicas=infer_deploy.num_prefill_replicas,
|
||||
num_decode_replicas=infer_deploy.num_decode_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router_port=infer_deploy.router.port,
|
||||
router=infer_deploy.router,
|
||||
prefill_port=infer_deploy.prefill_port,
|
||||
decode_port=infer_deploy.decode_port,
|
||||
inference_tp=config.inference.parallel.tp,
|
||||
@@ -379,6 +381,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
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_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",
|
||||
@@ -397,7 +401,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,
|
||||
|
||||
@@ -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,12 +14,73 @@ def transformers_v5_compat():
|
||||
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
|
||||
Qwen3VLMoeTextConfig.tie_word_embeddings = False
|
||||
|
||||
_patch_qwen35_lora()
|
||||
_patch_lora_key_prefix()
|
||||
_patch_qwen35_moe_lora_format()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_deep_gemm_silu_mul_quant_int64()
|
||||
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():
|
||||
@@ -122,200 +182,28 @@ def monkey_patch_strip_routed_experts_from_chat():
|
||||
)
|
||||
|
||||
|
||||
@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
|
||||
def _patch_qwen35_moe_lora_format():
|
||||
"""Force Qwen3.5-MoE onto vLLM's 2D per-expert LoRA format.
|
||||
|
||||
m_offset = (pid_m * BLOCK_M).to(tl.int64)
|
||||
n_offset = (pid_n * BLOCK_N).to(tl.int64)
|
||||
if m_offset >= M:
|
||||
return
|
||||
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.
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
)
|
||||
|
||||
logger.warning("Enabled int64-addressing Triton patch for vLLM DeepGEMM SiLU/mul FP8 quant.")
|
||||
|
||||
|
||||
def _patch_qwen35_lora():
|
||||
"""Fix Qwen3.5 LoRA: align packed_modules_mapping with output_sizes.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
@@ -719,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
|
||||
@@ -743,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",
|
||||
)
|
||||
|
||||
|
||||
@@ -11,6 +11,15 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
# Force the V1 GPU model runner. vLLM 0.23.0 routes dense Llama/Mistral/Qwen3 to the
|
||||
# V2 runner, which has no `_preprocess` hook for our padded-input scrub (see
|
||||
# inference/vllm/padded_input_scrub.py) and doesn't zero the padded decode tail
|
||||
# itself; that stale tail poisons CUDA-graph replay as NaN logits (reproduced on
|
||||
# Nemotron-Nano SWE, PR #2506; upstream fix vllm#42779 is still unmerged). V1 keeps
|
||||
# the scrub effective for every model and is also required for routed-experts capture
|
||||
# (the NIXL PD path rejects V2). setdefault so it stays overridable.
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
|
||||
|
||||
deep_gemm_enabled = "1" if config.use_deep_gemm else "0"
|
||||
os.environ["VLLM_USE_DEEP_GEMM"] = deep_gemm_enabled
|
||||
os.environ["VLLM_MOE_USE_DEEP_GEMM"] = deep_gemm_enabled
|
||||
|
||||
@@ -1,28 +1,24 @@
|
||||
"""Prime-RL extensions to vLLM's `/inference/v1/generate` handler.
|
||||
|
||||
vLLM 0.20 ships a generic tokens-in / tokens-out handler at
|
||||
vLLM 0.22 ships a generic tokens-in / tokens-out handler at
|
||||
``vllm.entrypoints.serve.disagg.serving.ServingTokens`` that already covers
|
||||
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs and
|
||||
priority. Three prime-RL features are not in the upstream protocol though, so
|
||||
we subclass it to add them back:
|
||||
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
|
||||
priority, ``data_parallel_rank`` header routing and server-side ``max_tokens``
|
||||
defaulting. We subclass it for the bits still missing from the upstream handler:
|
||||
|
||||
1. ``data_parallel_rank`` routing — read from the ``X-data-parallel-rank``
|
||||
header and forwarded to ``engine_client.generate``. The DP-replicated
|
||||
inference servers prime-RL runs need this to target a specific replica.
|
||||
header and forwarded to ``engine_client.generate``. Upstream ``ServingTokens``
|
||||
now does this too; we keep the equivalent path for the DP-replicated
|
||||
inference servers prime-RL runs.
|
||||
|
||||
2. Compact ``routed_experts`` export — when the engine emits routing
|
||||
decisions, surface them as base64 raw-byte payloads without requiring a vLLM
|
||||
source fork.
|
||||
|
||||
3. Server-side ``max_tokens`` defaulting — ``ServingTokens`` hands the
|
||||
client-supplied ``SamplingParams`` to the engine verbatim, and
|
||||
``SamplingParams.max_tokens`` defaults to ``16`` (a dataclass-level
|
||||
default that predates the OpenAI-compat layer). Every other vLLM
|
||||
endpoint masks this server-side via
|
||||
``vllm.entrypoints.utils.get_max_tokens`` (see e.g.
|
||||
``OpenAIServingChat`` at ``serving.py:284``); the disagg endpoint
|
||||
skips that path. Mirror it here so callers that omit ``max_tokens``
|
||||
don't silently truncate at 16. Drop once vLLM patches upstream.
|
||||
3. Server-side ``max_tokens`` defaulting — upstream ``ServingTokens`` now applies
|
||||
this itself (via ``GenerateRequest.is_sampling_param_provided`` +
|
||||
``get_max_tokens``); we keep an equivalent guard so callers that omit
|
||||
``max_tokens`` don't truncate at vLLM's 16-token ``SamplingParams`` default.
|
||||
|
||||
Everything else (request/response schema, sampling params, error handling)
|
||||
delegates to upstream so we track future vLLM changes for free.
|
||||
@@ -47,7 +43,7 @@ from vllm.entrypoints.serve.disagg.protocol import (
|
||||
GenerateResponseChoice,
|
||||
)
|
||||
from vllm.entrypoints.serve.disagg.serving import ServingTokens
|
||||
from vllm.entrypoints.utils import get_max_tokens
|
||||
from vllm.entrypoints.serve.utils.api_utils import get_max_tokens
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
|
||||
@@ -156,7 +152,7 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
|
||||
@cached_property
|
||||
def _max_tokens_defaults(self) -> tuple[dict, int | None]:
|
||||
"""Server-side ``max_tokens`` defaulting inputs, mirroring ``OpenAIServingChat``.
|
||||
"""Server-side ``max_tokens`` defaulting inputs, mirroring upstream ``ServingTokens``.
|
||||
|
||||
Computed lazily because ``custom_init_app_state`` swaps in this
|
||||
subclass via ``object.__new__`` + ``__dict__.update`` (so our
|
||||
@@ -180,7 +176,7 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
request: GenerateRequest,
|
||||
raw_request: Request | None = None,
|
||||
) -> PrimeRlGenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
|
||||
# Mirrors upstream ``ServingTokens.serve_tokens`` (vllm 0.20). Diffs:
|
||||
# Mirrors upstream ``ServingTokens.serve_tokens`` (vllm 0.22). Diffs:
|
||||
# (a) inject ``data_parallel_rank`` from the inbound header into
|
||||
# ``engine_client.generate``; (b) default ``sampling_params.max_tokens``
|
||||
# to ``max_model_len - prompt_len`` when the caller didn't set it; and
|
||||
@@ -253,10 +249,10 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
extra["kv_transfer_params"] = request.kv_transfer_params
|
||||
sampling_params.extra_args = extra
|
||||
|
||||
# Server-side ``max_tokens`` defaulting — see module docstring.
|
||||
# Mirrors ``OpenAIServingChat`` (vllm/entrypoints/openai/chat_completion/
|
||||
# serving.py:284) so callers that omit ``max_tokens`` don't get capped
|
||||
# at vLLM's 16-token ``SamplingParams`` default.
|
||||
# Server-side ``max_tokens`` defaulting — see module docstring. Upstream
|
||||
# ``ServingTokens`` now does this too; kept here so callers that omit
|
||||
# ``max_tokens`` don't get capped at vLLM's 16-token ``SamplingParams``
|
||||
# default.
|
||||
if not await _client_set_max_tokens(raw_request):
|
||||
diff_sp, override = self._max_tokens_defaults
|
||||
sampling_params.max_tokens = get_max_tokens(
|
||||
|
||||
@@ -24,17 +24,22 @@ else:
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_nccl")
|
||||
|
||||
# NemotronH mixer.D is dropped by vLLM 0.22's layerwise online-reload path (left uninitialized).
|
||||
# NemotronH mixer.D is dropped by vLLM's layerwise online-reload path (left uninitialized).
|
||||
_RELOAD_CORRUPTED_SUFFIXES = (".mixer.D",)
|
||||
|
||||
|
||||
def _restore_reload_corrupted_params(model: Module, received: dict[str, torch.Tensor]) -> None:
|
||||
"""Work around a vLLM 0.22 layerwise-reload bug for NemotronH.
|
||||
"""Work around a vLLM layerwise-reload bug for NemotronH (present through vLLM 0.23.0).
|
||||
|
||||
The online reload drops the weight load for every Mamba layer's ``mixer.D`` (the SSD skip
|
||||
connection), leaving it as uninitialized ``empty_strided`` memory -- it reads back as garbage
|
||||
(NaN/inf) and the logits go NaN after a weight update. The received broadcast value is correct,
|
||||
so restore D from it via the param's own ``weight_loader``. Remove once the upstream bug is fixed.
|
||||
(NaN/inf) and the logits go NaN after a weight update. Root cause: ``mixer.A`` is loaded with
|
||||
``composed_weight_loader`` (an extra in-place transform copy), so the reload element counter
|
||||
double-counts ``A`` and finalizes the layer before ``D`` (loaded last) is loaded. The received
|
||||
broadcast value is correct, so restore D from it via the param's own ``weight_loader``.
|
||||
|
||||
Fixed upstream by vllm-project/vllm#44814 (merged 2026-06-10) but NOT in the pinned 0.23.0
|
||||
release; remove this shim once we bump to a vLLM release that includes it.
|
||||
"""
|
||||
|
||||
def _layer_key(name: str) -> str:
|
||||
@@ -179,7 +184,7 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
update_mla_absorbed_weights(model)
|
||||
return
|
||||
|
||||
# vLLM 0.22's layerwise reload drops NemotronH mixer.D's weight load (see
|
||||
# vLLM's layerwise reload drops NemotronH mixer.D's weight load (see
|
||||
# _restore_reload_corrupted_params). Capture the correct received value to restore after.
|
||||
received_reload_fix: dict[str, torch.Tensor] = {}
|
||||
|
||||
|
||||
@@ -4,21 +4,17 @@ from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Callable
|
||||
|
||||
import torch
|
||||
import verifiers as vf
|
||||
from jaxtyping import Float
|
||||
from torch import Tensor
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import TrainRollout
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
from prime_rl.configs.orchestrator import (
|
||||
AdvantageConfig,
|
||||
CustomAdvantageConfig,
|
||||
LengthPenaltyConfig,
|
||||
TokensLengthPenaltyConfig,
|
||||
TurnsLengthPenaltyConfig,
|
||||
LinearLengthPenaltyConfig,
|
||||
)
|
||||
from prime_rl.orchestrator.utils import get_model_completion_len, get_tool_response_len
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -26,7 +22,7 @@ from prime_rl.utils.utils import import_object
|
||||
class AdvantageInputs:
|
||||
"""Inputs for advantage computation of a single group (one example × N rollouts)."""
|
||||
|
||||
rollouts: list[vf.RolloutOutput]
|
||||
rollouts: list[vf.Trace]
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -50,68 +46,36 @@ entry per rollout. `assign_advantages` calls it on one already-grouped cohort.
|
||||
|
||||
def default_advantage_fn(
|
||||
inputs: AdvantageInputs,
|
||||
length_penalty: LengthPenaltyConfig | None = None,
|
||||
length_penalty: LinearLengthPenaltyConfig | None = None,
|
||||
max_seq_len: int | None = None,
|
||||
length_weighted_baseline: bool = False,
|
||||
) -> AdvantageOutputs:
|
||||
"""Default GRPO advantage for a single group: reward minus per-group baseline.
|
||||
|
||||
`length_penalty` enables correctness-gated efficiency shaping over a per-rollout
|
||||
cost: tokens (weighted completion + tool-response) or trajectory turn count.
|
||||
``length_penalty`` subtracts ``coef * pass_rate * (completion tokens / max_seq_len)``
|
||||
from each reward (``pass_rate`` = group mean reward), optionally gated to correct
|
||||
(``reward == 1``) rollouts. ``length_weighted_baseline`` uses the token-length-weighted
|
||||
mean reward as the baseline instead of the plain mean.
|
||||
"""
|
||||
rewards = torch.tensor([r["reward"] for r in inputs.rollouts], dtype=torch.float32)
|
||||
rewards = torch.tensor([r.reward for r in inputs.rollouts], dtype=torch.float32)
|
||||
lengths = torch.tensor([r.completion_len for r in inputs.rollouts], dtype=rewards.dtype)
|
||||
|
||||
if isinstance(length_penalty, TokensLengthPenaltyConfig):
|
||||
w_c = length_penalty.completion_weight
|
||||
w_t = length_penalty.tool_response_weight
|
||||
costs = torch.tensor(
|
||||
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in inputs.rollouts],
|
||||
dtype=rewards.dtype,
|
||||
)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
|
||||
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
|
||||
costs = torch.tensor([len(r["trajectory"]) for r in inputs.rollouts], dtype=rewards.dtype)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
|
||||
if length_penalty is not None:
|
||||
if max_seq_len is None:
|
||||
raise ValueError("max_seq_len is required when length_penalty is enabled")
|
||||
penalty = length_penalty.coef * rewards.mean() * (lengths / max_seq_len)
|
||||
if length_penalty.gate_by_correctness:
|
||||
penalty = penalty * rewards
|
||||
rewards = rewards - penalty
|
||||
|
||||
return AdvantageOutputs(advantages=(rewards - rewards.mean()).tolist())
|
||||
if length_weighted_baseline:
|
||||
baseline = (lengths * rewards).sum() / lengths.sum()
|
||||
else:
|
||||
baseline = rewards.mean()
|
||||
return AdvantageOutputs(advantages=(rewards - baseline).tolist())
|
||||
|
||||
|
||||
def _efficiency_shaping(
|
||||
rewards: Float[Tensor, "group_size"],
|
||||
costs: Float[Tensor, "group_size"],
|
||||
) -> Float[Tensor, "group_size"]:
|
||||
"""Correctness-gated efficiency shaping with bounded advantages.
|
||||
|
||||
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
|
||||
preserving zero-mean advantages within the group. `costs` is a per-rollout cost
|
||||
(e.g., completion length in tokens or number of turns).
|
||||
|
||||
Correct rollouts get reward amplified by up to 2x based on relative efficiency.
|
||||
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
|
||||
"""
|
||||
max_reward = rewards.max()
|
||||
correct_mask = rewards >= max_reward
|
||||
num_correct = correct_mask.sum()
|
||||
|
||||
# No shaping when max reward is 0 — no correct rollouts to differentiate
|
||||
if max_reward <= 0:
|
||||
return rewards - rewards.mean()
|
||||
|
||||
# Mean cost of correct rollouts
|
||||
mean_correct_cost = (costs * correct_mask).sum() / num_correct.clamp(min=1)
|
||||
|
||||
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
|
||||
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
|
||||
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
|
||||
if mean_correct_cost <= 0:
|
||||
return rewards - rewards.mean()
|
||||
|
||||
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
|
||||
|
||||
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
|
||||
shaped_rewards = rewards * (1 + bonus * correct_mask)
|
||||
return shaped_rewards - shaped_rewards.mean()
|
||||
|
||||
|
||||
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
def setup_advantage_fn(config: AdvantageConfig, max_seq_len: int | None = None) -> AdvantageFn:
|
||||
"""Setup advantage function from config."""
|
||||
if isinstance(config, CustomAdvantageConfig):
|
||||
custom_fn = import_object(config.import_path)
|
||||
@@ -123,25 +87,29 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
return advantage_fn
|
||||
|
||||
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
|
||||
return default_advantage_fn(inputs, length_penalty=config.length_penalty)
|
||||
return default_advantage_fn(
|
||||
inputs,
|
||||
length_penalty=config.length_penalty,
|
||||
max_seq_len=max_seq_len,
|
||||
length_weighted_baseline=config.length_weighted_baseline,
|
||||
)
|
||||
|
||||
return advantage_fn
|
||||
|
||||
|
||||
def assign_advantages(
|
||||
rollouts: list["TrainRollout"], # noqa: F821 (forward ref)
|
||||
rollouts: list[Rollout],
|
||||
advantage_fn: AdvantageFn | None,
|
||||
) -> None:
|
||||
"""Compute and assign advantages for one finished group of rollouts
|
||||
(``TrainSink.process_group`` hands in a single group's surviving rollouts).
|
||||
``advantage_fn=None`` is the trivial case (advantage = reward); a custom
|
||||
``advantage_fn`` receives the raw ``vf.RolloutOutput``\\ s via
|
||||
``AdvantageInputs.rollouts``.
|
||||
``advantage_fn`` receives the ``vf.Trace``\\ s via ``AdvantageInputs.rollouts``.
|
||||
"""
|
||||
if advantage_fn is None:
|
||||
for rollout in rollouts:
|
||||
rollout.advantage = rollout.reward
|
||||
return
|
||||
result = advantage_fn(AdvantageInputs(rollouts=[r.raw for r in rollouts]))
|
||||
result = advantage_fn(AdvantageInputs(rollouts=[r for r in rollouts]))
|
||||
for rollout, advantage in zip(rollouts, result.advantages):
|
||||
rollout.advantage = advantage
|
||||
|
||||
@@ -6,13 +6,14 @@
|
||||
- Emit-everything invariant: every dispatched rollout eventually reaches
|
||||
``out_q`` exactly once as a ``TrainRollout`` / ``EvalRollout``. Failures
|
||||
(env error, empty trajectory, task exception, off-policy cancel) carry
|
||||
``raw["error"]`` set; sinks decide drop / partial-train policy.
|
||||
``trace.error`` set; sinks decide drop / partial-train policy.
|
||||
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
|
||||
schedule next. Transitions are level-triggered (driven by the eval
|
||||
source's emptiness), so in-flight rollouts of the opposite kind drain
|
||||
naturally on either side of an eval boundary.
|
||||
- ``on_new_version`` (called by the watcher) bumps ``off_policy_steps`` on
|
||||
in-flight train rollouts and drops groups past ``max_off_policy_steps``.
|
||||
- ``on_version_pending`` (called by the watcher before the engines pause for
|
||||
the weight update) bumps ``off_policy_steps`` on in-flight train rollouts and
|
||||
drops groups past ``max_off_policy_steps``.
|
||||
Eval rollouts are measurements for the policy version they started with,
|
||||
so they are allowed to finish even if training advances.
|
||||
Cancellations surface as synthetic ``Cancelled`` markers so the sink's
|
||||
@@ -28,20 +29,18 @@ from dataclasses import dataclass, field
|
||||
from enum import Enum, auto
|
||||
from typing import Literal
|
||||
|
||||
import verifiers as vf
|
||||
import verifiers.v1 as vf
|
||||
from aiolimiter import AsyncLimiter
|
||||
|
||||
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
from prime_rl.orchestrator.types import (
|
||||
EvalRollout,
|
||||
FinishedRollout,
|
||||
GroupState,
|
||||
InflightRollout,
|
||||
Policy,
|
||||
Rollout,
|
||||
RolloutKind,
|
||||
TrainRollout,
|
||||
)
|
||||
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
|
||||
from prime_rl.utils.client import InferencePool, client_identity
|
||||
@@ -116,7 +115,7 @@ class RolloutDispatcher:
|
||||
"""``await dispatcher.start()`` runs the dispatch loop until ``stop()``.
|
||||
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules
|
||||
rollouts under shared capacity, and emits ``FinishedRollout``\\ s to
|
||||
``out_q``. The watcher drives ``on_new_version`` for off-policy
|
||||
``out_q``. The watcher drives ``on_version_pending`` for off-policy
|
||||
cancellation; the orchestrator triggers eval epochs."""
|
||||
|
||||
def __init__(
|
||||
@@ -158,7 +157,7 @@ class RolloutDispatcher:
|
||||
self.groups: dict[uuid.UUID, GroupState] = {}
|
||||
|
||||
# Bounded so the dispatcher backpressures on a slow sink
|
||||
self.out_q: asyncio.Queue[FinishedRollout] = asyncio.Queue(maxsize=max(8, self.max_inflight))
|
||||
self.out_q: asyncio.Queue[Rollout] = asyncio.Queue(maxsize=max(8, self.max_inflight))
|
||||
|
||||
self.mode: DispatcherMode = DispatcherMode.PREFER_TRAIN
|
||||
# Set by the orchestrator after the final train step; pipeline then
|
||||
@@ -263,11 +262,16 @@ class RolloutDispatcher:
|
||||
await safe_cancel(self.task)
|
||||
self.task = None
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""Bump off-policy counters and drop groups past
|
||||
``max_off_policy_steps`` (drop_group emits ``Cancelled`` markers so
|
||||
the sink still finalizes the partial group). Eval rollouts are not
|
||||
aged because they are tied to their start-time policy version."""
|
||||
aged because they are tied to their start-time policy version.
|
||||
|
||||
Runs *before* the inference engines are paused for the weight update so
|
||||
the resulting aborts are processed while the engine is still stepping —
|
||||
otherwise the orphaned KV transfers crash the decode engine on resume
|
||||
(see ``WeightWatcher.apply_policy_update``)."""
|
||||
stale_groups: set[uuid.UUID] = set()
|
||||
cancelled = 0
|
||||
for meta in self.inflight.values():
|
||||
@@ -287,6 +291,9 @@ class RolloutDispatcher:
|
||||
"Consider increasing it to avoid this."
|
||||
)
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""No-op: the dispatcher drains in ``on_version_pending`` (pre-pause)."""
|
||||
|
||||
async def fill_inflight(self) -> None:
|
||||
"""Schedule new rollouts up to ``max_inflight``, honoring
|
||||
``self.mode``. Eval scheduling ignores the orchestrator's dispatch
|
||||
@@ -373,7 +380,7 @@ class RolloutDispatcher:
|
||||
return GroupState(
|
||||
kind=kind,
|
||||
env_name=env_name,
|
||||
example=example,
|
||||
task_idx=example["task_idx"],
|
||||
rollouts_to_schedule=group_size,
|
||||
target_rollouts=group_size,
|
||||
eval_step=eval_step,
|
||||
@@ -427,7 +434,7 @@ class RolloutDispatcher:
|
||||
task: asyncio.Task = asyncio.create_task(
|
||||
env.run_group(
|
||||
client=client,
|
||||
example=group.example,
|
||||
task_idx=group.task_idx,
|
||||
model_name=model_name,
|
||||
group_size=permits,
|
||||
cache_salt=cache_salt,
|
||||
@@ -440,7 +447,7 @@ class RolloutDispatcher:
|
||||
task = asyncio.create_task(
|
||||
env.run_rollout(
|
||||
client=client,
|
||||
example=group.example,
|
||||
task_idx=group.task_idx,
|
||||
model_name=model_name,
|
||||
cache_salt=cache_salt,
|
||||
)
|
||||
@@ -484,97 +491,60 @@ class RolloutDispatcher:
|
||||
is_synth_exception = False
|
||||
try:
|
||||
result = task.result()
|
||||
rollouts: list[vf.RolloutOutput] = result if isinstance(result, list) else [result]
|
||||
rollouts: list[Rollout] = result if isinstance(result, list) else [result]
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
except Exception as exc:
|
||||
get_logger().warning(f"Rollout task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
|
||||
rollouts = [
|
||||
self.error_rollout_output(error_type=type(exc).__name__, error_repr=repr(exc))
|
||||
for _ in range(meta.rollout_count)
|
||||
]
|
||||
task_idx = group.task_idx if group is not None else -1
|
||||
rollouts = [Rollout(task=vf.Task(idx=task_idx, prompt=None)) for _ in range(meta.rollout_count)]
|
||||
for r in rollouts:
|
||||
r.capture_error(exc)
|
||||
is_synth_exception = True
|
||||
|
||||
for r in rollouts:
|
||||
if r.get("error") is None and len(r.get("trajectory") or []) == 0:
|
||||
if not r.has_error and r.num_turns == 0:
|
||||
# Empty trajectory: promote to an explicit error so the sink
|
||||
# treats it like any other failure
|
||||
r["error"] = {
|
||||
"error": "EmptyTrajectory",
|
||||
"error_chain_repr": "Rollout returned with no trajectory steps",
|
||||
"error_chain_str": "",
|
||||
}
|
||||
r.errors.append(vf.Error(type="EmptyTrajectory", message="Rollout returned with no trajectory steps"))
|
||||
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
|
||||
if r.get("error") is not None:
|
||||
err_type = r["error"].get("error", "Unknown")
|
||||
if r.has_error:
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
if not is_synth_exception:
|
||||
get_logger().warning(
|
||||
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — "
|
||||
f"{r['error'].get('error_chain_repr', err_type)}"
|
||||
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — {r.error.type}: {r.error.message}"
|
||||
)
|
||||
await self.emit_rollout(meta, group, r)
|
||||
|
||||
async def emit_rollout(self, meta: InflightRollout, group: GroupState | None, raw: vf.RolloutOutput) -> None:
|
||||
"""Build a ``TrainRollout`` / ``EvalRollout`` and put it on ``out_q``.
|
||||
async def emit_rollout(self, meta: InflightRollout, group: GroupState | None, rollout: Rollout) -> None:
|
||||
"""Stamp prime-rl metadata onto the completed rollout and put it on ``out_q``.
|
||||
Pops the group from ``self.groups`` once every member has been emitted."""
|
||||
eval_step = meta.eval_step
|
||||
policy_version = meta.policy_version
|
||||
example_id = raw.get("example_id")
|
||||
if group is not None:
|
||||
eval_step = group.eval_step
|
||||
policy_version = group.policy_version_at_start
|
||||
example_id = group.example["example_id"]
|
||||
group.emitted += 1
|
||||
if group.emitted >= group.target_rollouts:
|
||||
self.groups.pop(meta.group_id, None)
|
||||
|
||||
common = dict(
|
||||
raw=raw,
|
||||
env_name=meta.env_name,
|
||||
example_id=example_id if example_id is not None else -1,
|
||||
group_id=meta.group_id,
|
||||
policy_version=policy_version,
|
||||
off_policy_steps=meta.off_policy_steps,
|
||||
)
|
||||
rollout: FinishedRollout
|
||||
if meta.kind == "train":
|
||||
rollout = TrainRollout(**common)
|
||||
else:
|
||||
rollout.kind = meta.kind
|
||||
rollout.env_name = meta.env_name
|
||||
rollout.group_id = meta.group_id
|
||||
rollout.policy_version = policy_version
|
||||
rollout.off_policy_steps = meta.off_policy_steps
|
||||
if meta.kind == "eval":
|
||||
assert eval_step is not None, "eval rollout missing eval_step"
|
||||
rollout = EvalRollout(**common, eval_step=eval_step)
|
||||
rollout.eval_step = eval_step
|
||||
await self.out_q.put(rollout)
|
||||
|
||||
@staticmethod
|
||||
def error_rollout_output(*, error_type: str, error_repr: str) -> vf.RolloutOutput:
|
||||
"""Minimal ``vf.RolloutOutput`` for rollouts that never produced
|
||||
real output (task exception, off-policy cancel)."""
|
||||
out: vf.RolloutOutput = vf.RolloutOutput()
|
||||
out["error"] = {
|
||||
"error": error_type,
|
||||
"error_chain_repr": error_repr,
|
||||
"error_chain_str": error_repr,
|
||||
}
|
||||
out["trajectory"] = []
|
||||
out["completion"] = None
|
||||
out["reward"] = 0.0
|
||||
out["is_truncated"] = False
|
||||
out["metrics"] = {}
|
||||
out["stop_condition"] = None
|
||||
out["token_usage"] = {
|
||||
"input_tokens": 0.0,
|
||||
"output_tokens": 0.0,
|
||||
"final_input_tokens": 0.0,
|
||||
"final_output_tokens": 0.0,
|
||||
}
|
||||
return out
|
||||
|
||||
async def drop_group(self, group_id: uuid.UUID) -> int:
|
||||
"""Cancel remaining in-flight tasks for this group and emit a
|
||||
``Cancelled`` marker for every rollout it still owes the sink
|
||||
(both in-flight and not-yet-scheduled). Returns the count for
|
||||
off-policy metrics."""
|
||||
group = self.groups.pop(group_id, None)
|
||||
task_idx = group.task_idx if group is not None else -1
|
||||
|
||||
# Sync claim phase: pop matching tasks from ``self.inflight`` and
|
||||
# release their permits in one non-yielding sweep. After this loop
|
||||
@@ -594,15 +564,19 @@ class RolloutDispatcher:
|
||||
last_meta: InflightRollout | None = claimed[-1][1] if claimed else None
|
||||
for _, meta in claimed:
|
||||
for _ in range(meta.rollout_count):
|
||||
raw = self.error_rollout_output(error_type="Cancelled", error_repr="Off-policy cancel")
|
||||
await self.emit_rollout(meta, group, raw)
|
||||
trace = Rollout(
|
||||
task=vf.Task(idx=task_idx, prompt=None),
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
stop_condition="error",
|
||||
)
|
||||
await self.emit_rollout(meta, group, trace)
|
||||
|
||||
# For non-group-scoring envs, the group may have rollouts that
|
||||
# were never dispatched (``rollouts_to_schedule > 0``). Emit
|
||||
# markers for those too so the sink hits ``target_rollouts``
|
||||
#
|
||||
# ``last_meta`` can be ``None`` if the only inflight task for this
|
||||
# group completed naturally between ``on_new_version``'s snapshot
|
||||
# group completed naturally between ``on_version_pending``'s snapshot
|
||||
# and us reaching it — synthesize a stand-in from the group state
|
||||
unscheduled_cancelled = 0
|
||||
if group is not None and group.rollouts_to_schedule > 0:
|
||||
@@ -616,8 +590,12 @@ class RolloutDispatcher:
|
||||
)
|
||||
unscheduled_cancelled = group.rollouts_to_schedule
|
||||
for _ in range(unscheduled_cancelled):
|
||||
raw = self.error_rollout_output(error_type="Cancelled", error_repr="Off-policy cancel")
|
||||
await self.emit_rollout(fallback_meta, group, raw)
|
||||
trace = Rollout(
|
||||
task=vf.Task(idx=task_idx, prompt=None),
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
stop_condition="error",
|
||||
)
|
||||
await self.emit_rollout(fallback_meta, group, trace)
|
||||
|
||||
cancelled = inflight_cancelled + unscheduled_cancelled
|
||||
if cancelled > 0:
|
||||
|
||||
@@ -1,38 +1,35 @@
|
||||
import asyncio
|
||||
from functools import partial
|
||||
|
||||
from verifiers.serve import ZMQEnvServer
|
||||
from verifiers.v1 import pool_serve_kwargs
|
||||
from verifiers.v1.serve import serve_env
|
||||
|
||||
from prime_rl.configs.env_server import EnvServerConfig
|
||||
from prime_rl.orchestrator.utils import setup_env_server_logging
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import get_log_dir
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.utils import clean_exit, get_env_ids_to_install, install_env
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
|
||||
@clean_exit
|
||||
def run_server(config: EnvServerConfig):
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
|
||||
# install environment if not already installed
|
||||
env_ids_to_install = set()
|
||||
env_ids_to_install.update(get_env_ids_to_install([config.env]))
|
||||
for env_id in env_ids_to_install:
|
||||
install_env(env_id, prerelease=config.env_install_prerelease)
|
||||
|
||||
log_dir = (get_log_dir(config.output_dir) / config.env.resolved_name).as_posix()
|
||||
|
||||
server = ZMQEnvServer(
|
||||
env_id=config.env.stripped_id,
|
||||
env_args=config.env.args,
|
||||
extra_env_kwargs=config.env.extra_env_kwargs,
|
||||
log_level=config.log.level,
|
||||
log_dir=log_dir,
|
||||
json_logging=config.log.json_logging,
|
||||
num_workers=config.env.num_workers,
|
||||
**{"address": config.env.address} if config.env.address is not None else {},
|
||||
env = config.env
|
||||
address = env.address or "tcp://127.0.0.1:5000"
|
||||
# The env's ``pool`` (static or elastic) sizes the server; a v0/legacy env runs through
|
||||
# the bridge, a v1 env is a native taskset — both serve vf.Trace over the same protocol,
|
||||
# so the orchestrator is agnostic. serve_env applies the logging setup in this process
|
||||
# and in every spawned worker.
|
||||
server_kwargs = (
|
||||
{"env_id": env.env_id, "env_args": env.args, "extra_env_kwargs": env.extra_env_kwargs}
|
||||
if env.is_legacy
|
||||
else {"config": env}
|
||||
)
|
||||
serve_env(
|
||||
**pool_serve_kwargs(env.pool),
|
||||
legacy=env.is_legacy,
|
||||
address=address,
|
||||
log_setup=partial(setup_env_server_logging, config.log.level, config.log.json_logging),
|
||||
**server_kwargs,
|
||||
)
|
||||
asyncio.run(server.run())
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
+157
-124
@@ -1,33 +1,90 @@
|
||||
"""Env wrappers over a v1 env server.
|
||||
|
||||
Each ``Env`` owns a v1 ``EnvServer`` (spawned as a child process, or an
|
||||
external one given by ``config.address``) and an ``EnvClient`` to drive it. The
|
||||
orchestrator never *runs* an environment: it asks the server for ``info``
|
||||
(``num_tasks`` + whether group scoring is needed), then runs rollouts purely by
|
||||
**task index**. The server returns a ``Trace`` (a plain ``model_dump`` — derived values are
|
||||
properties, not serialized) which we validate into a ``Trace[WireTask]`` — a real ``vf.Trace``
|
||||
(never a loose dict) whose task keeps the env's
|
||||
task-specific fields as extras (``WireTask`` allows them). The orchestrator never imports the
|
||||
env package: the env's *type* and *runtime* both live only in the server, and the orchestrator
|
||||
drives it purely by task index. (Nothing here reads typed env task fields — only ``task.idx``
|
||||
and a full ``task.model_dump``, both of which ``WireTask`` preserves.)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import atexit
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import queue
|
||||
import sys
|
||||
from collections.abc import Iterator, Sequence
|
||||
from multiprocessing.process import BaseProcess
|
||||
from pathlib import Path
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
import verifiers as vf
|
||||
from verifiers.serve import ZMQEnvClient, ZMQEnvServer
|
||||
from verifiers.utils.serve_utils import get_free_port
|
||||
import verifiers.v1 as vf
|
||||
from verifiers.v1.serve import EnvClient
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalEnvConfig, TrainEnvConfig
|
||||
from prime_rl.orchestrator.advantage import AdvantageFn, setup_advantage_fn
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
REQUIRED_STATE_COLUMNS = ["trajectory"]
|
||||
# Every wire trace validates into this type. WireTask (extra="allow") keeps the env's task
|
||||
# fields without importing the env package — the orchestrator never reads them typed (only
|
||||
# task.idx + task.model_dump).
|
||||
ROLLOUT_TYPE = Rollout[vf.WireTask]
|
||||
|
||||
# Max wait for a spawned env server to bind and report its address. The child
|
||||
# loads the taskset (possibly downloading a dataset) before reporting, so this
|
||||
# is generous.
|
||||
ENV_SERVER_SPAWN_TIMEOUT = 600.0
|
||||
|
||||
|
||||
def _run_env_server(
|
||||
*,
|
||||
log_file: str,
|
||||
log_level: str,
|
||||
json_logging: bool,
|
||||
legacy: bool = False,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
"""Spawned-process entry point: redirect this process's output to ``log_file`` (the
|
||||
server's logging + any subprocess-runtime output), then serve via ``serve_env``. The
|
||||
worker-pool sizing arrives in ``kwargs`` (``max_workers`` / ``multiplex`` / ``elastic``
|
||||
from the env's ``pool``). ``serve_env`` applies ``log_setup`` here and in every spawned
|
||||
worker; a worker inherits this process's redirected stdout/stderr, so its per-rollout
|
||||
logs reach ``log_file`` too. Top-level so it stays picklable for the ``spawn`` start
|
||||
method. ``legacy`` picks the v0 bridge."""
|
||||
from functools import partial
|
||||
|
||||
from verifiers.v1.serve import serve_env
|
||||
|
||||
from prime_rl.orchestrator.utils import setup_env_server_logging
|
||||
|
||||
fh = open(log_file, "w", buffering=1)
|
||||
os.dup2(fh.fileno(), sys.stdout.fileno())
|
||||
os.dup2(fh.fileno(), sys.stderr.fileno())
|
||||
serve_env(
|
||||
legacy=legacy,
|
||||
log_setup=partial(setup_env_server_logging, log_level, json_logging),
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
class Env:
|
||||
"""Wraps a vf.Environment - only exposes features used in PRIME-RL."""
|
||||
"""Wraps a v1 env server + client. The orchestrator never loads the env."""
|
||||
|
||||
def __init__(self, config: EnvConfig):
|
||||
self.config = config
|
||||
self.sampling_args: dict = {}
|
||||
|
||||
get_logger().debug(f"Initializing {config.resolved_name} ({config})")
|
||||
self._env: vf.Environment = vf.load_environment(config.stripped_id, **config.args)
|
||||
self._env_client: ZMQEnvClient | None = None
|
||||
self.num_tasks: int = 0
|
||||
self.requires_group_scoring: bool = False
|
||||
self._env_client: EnvClient | None = None
|
||||
self._env_server_process: BaseProcess | None = None
|
||||
|
||||
@property
|
||||
@@ -35,122 +92,105 @@ class Env:
|
||||
return self.config.resolved_name
|
||||
|
||||
@property
|
||||
def env(self) -> vf.Environment:
|
||||
return self._env
|
||||
|
||||
@property
|
||||
def env_client(self) -> ZMQEnvClient:
|
||||
if not self._env_client:
|
||||
raise RuntimeError(
|
||||
f"Env {self.name} has no env client connected. Call connect() first to connect to an env server."
|
||||
)
|
||||
def env_client(self) -> EnvClient:
|
||||
if self._env_client is None:
|
||||
raise RuntimeError(f"Env {self.name} not started — call start() first.")
|
||||
return self._env_client
|
||||
|
||||
@property
|
||||
def requires_group_scoring(self) -> bool:
|
||||
return any(self.env.rubric._is_group_func(func) for func in self.env.rubric._get_reward_funcs())
|
||||
|
||||
async def start(
|
||||
self,
|
||||
log_dir: Path,
|
||||
log_level: str | None = None,
|
||||
json_logging: bool = False,
|
||||
) -> None:
|
||||
"""Spawn an env server (if needed) and connect to it."""
|
||||
if self.config.address is None:
|
||||
address = self._spawn(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
|
||||
else:
|
||||
address = self.config.address
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
"""Spawn the env server (if needed), connect, and cache its ``info``."""
|
||||
external = self.config.address is not None
|
||||
address = self.config.address or await self._spawn(log_dir, log_level or "INFO", json_logging)
|
||||
get_logger().debug(f"Connecting {self.name} to env server {address}")
|
||||
self._env_client = ZMQEnvClient(address=address, name=self.name)
|
||||
await self.env_client.wait_for_server_startup()
|
||||
|
||||
def _spawn(
|
||||
self,
|
||||
log_dir: Path,
|
||||
log_level: str | None = None,
|
||||
json_logging: bool = False,
|
||||
) -> str:
|
||||
assert isinstance(self.config.num_workers, int), (
|
||||
f"num_workers must be resolved before spawn, got {self.config.num_workers!r}"
|
||||
self._env_client = EnvClient(address=address)
|
||||
# A spawned server already reported its address *after* binding + loading,
|
||||
# so it's up — the untimed ``info`` below is enough. An external server has
|
||||
# no such handshake, so poll until it answers before we block on ``info``.
|
||||
if external:
|
||||
await self.env_client.wait_for_server_startup()
|
||||
info = await self.env_client.info()
|
||||
self.num_tasks = info.num_tasks
|
||||
self.requires_group_scoring = info.requires_group_scoring
|
||||
get_logger().info(
|
||||
f"Env {self.name} ready: num_tasks={self.num_tasks} group_scoring={self.requires_group_scoring}"
|
||||
)
|
||||
num_workers = self.config.num_workers
|
||||
address = f"tcp://127.0.0.1:{get_free_port()}"
|
||||
get_logger().debug(f"Spawning env server {self.name} ({address=}, {num_workers=})")
|
||||
process = mp.get_context("spawn").Process(
|
||||
target=ZMQEnvServer.run_server,
|
||||
args=(
|
||||
self.config.stripped_id,
|
||||
self.config.args,
|
||||
self.config.extra_env_kwargs,
|
||||
log_level,
|
||||
(log_dir / self.name).as_posix(),
|
||||
),
|
||||
|
||||
async def _spawn(self, log_dir: Path, log_level: str, json_logging: bool) -> str:
|
||||
"""Spawn a v1 EnvServer child process (it loads the env; we never do).
|
||||
The server binds an OS-assigned port (``:0``) and reports the concrete
|
||||
address back over a queue — no free-port guess, no TOCTOU race. Its output
|
||||
goes to ``<log_dir>/<name>.log`` (``log_dir`` is already the train/eval-split
|
||||
``.../logs/envs/{train,eval}`` the orchestrator passes in)."""
|
||||
ctx = mp.get_context("spawn")
|
||||
address_queue: mp.Queue = ctx.Queue()
|
||||
log_file = log_dir / f"{self.name}.log"
|
||||
log_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_logger().debug(f"Spawning env server {self.name} (id={self.config.env_id}, log={log_file})")
|
||||
server_kwargs = (
|
||||
dict(
|
||||
legacy=True,
|
||||
env_id=self.config.env_id,
|
||||
env_args=self.config.args,
|
||||
extra_env_kwargs=self.config.extra_env_kwargs,
|
||||
)
|
||||
if self.config.is_legacy
|
||||
else dict(legacy=False, config=self.config)
|
||||
)
|
||||
process = ctx.Process(
|
||||
target=_run_env_server,
|
||||
kwargs=dict(
|
||||
address=address,
|
||||
log_file=str(log_file),
|
||||
log_level=log_level,
|
||||
json_logging=json_logging,
|
||||
console_logging=False,
|
||||
num_workers=num_workers,
|
||||
**vf.pool_serve_kwargs(self.config.pool),
|
||||
address="tcp://127.0.0.1:0",
|
||||
address_queue=address_queue,
|
||||
**server_kwargs,
|
||||
),
|
||||
daemon=False,
|
||||
)
|
||||
process.start()
|
||||
self._env_server_process = process
|
||||
try:
|
||||
address = await asyncio.to_thread(address_queue.get, timeout=ENV_SERVER_SPAWN_TIMEOUT)
|
||||
except queue.Empty:
|
||||
raise RuntimeError(f"Env server {self.name} did not report its address within {ENV_SERVER_SPAWN_TIMEOUT}s")
|
||||
finally:
|
||||
address_queue.close()
|
||||
address_queue.join_thread()
|
||||
get_logger().debug(f"Env server {self.name} bound at {address}")
|
||||
return address
|
||||
|
||||
def _sampling_args_with_salt(self, cache_salt: str | None) -> dict:
|
||||
sampling_args = {**self.sampling_args}
|
||||
if cache_salt is None:
|
||||
return sampling_args
|
||||
extra_body = {**sampling_args.get("extra_body", {}), "cache_salt": cache_salt}
|
||||
sampling_args["extra_body"] = extra_body
|
||||
return sampling_args
|
||||
|
||||
@property
|
||||
def state_columns(self) -> list[str]:
|
||||
"""Required columns plus any extras configured on the env, deduped (required first)."""
|
||||
merged: list[str] = []
|
||||
for col in (*REQUIRED_STATE_COLUMNS, *self.config.state_columns):
|
||||
if col not in merged:
|
||||
merged.append(col)
|
||||
return merged
|
||||
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
|
||||
sampling = {**self.sampling_args}
|
||||
if cache_salt is not None:
|
||||
sampling["extra_body"] = {**sampling.get("extra_body", {}), "cache_salt": cache_salt}
|
||||
return vf.SamplingConfig(**sampling)
|
||||
|
||||
async def run_rollout(
|
||||
self,
|
||||
client: vf.ClientConfig,
|
||||
example: dict,
|
||||
model_name: str,
|
||||
cache_salt: str | None,
|
||||
) -> vf.RolloutOutput:
|
||||
"""Run a single rollout for an example."""
|
||||
return await self.env.run_rollout(
|
||||
vf.RolloutInput(**example),
|
||||
self, client: vf.ClientConfig, task_idx: int, model_name: str, cache_salt: str | None
|
||||
) -> Rollout:
|
||||
"""Run a single rollout for ``task_idx``; return a typed Trace."""
|
||||
wire = await self.env_client.run_rollout(
|
||||
task_idx=task_idx,
|
||||
client=client,
|
||||
model=model_name,
|
||||
sampling_args=self._sampling_args_with_salt(cache_salt),
|
||||
max_retries=self.config.max_retries,
|
||||
state_columns=self.state_columns,
|
||||
env_client=self.env_client,
|
||||
sampling=self._sampling(cache_salt),
|
||||
)
|
||||
return ROLLOUT_TYPE.model_construct(**dict(wire))
|
||||
|
||||
async def run_group(
|
||||
self,
|
||||
client: vf.ClientConfig,
|
||||
example: dict,
|
||||
model_name: str,
|
||||
group_size: int,
|
||||
cache_salt: str | None,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
"""Run a group of rollouts for an example. Required for group-scoring envs."""
|
||||
return await self.env.run_group(
|
||||
[vf.RolloutInput(**example) for _ in range(group_size)],
|
||||
self, client: vf.ClientConfig, task_idx: int, model_name: str, group_size: int, cache_salt: str | None
|
||||
) -> list[Rollout]:
|
||||
"""Run a group of rollouts for ``task_idx`` (group-scoring envs); return typed Traces."""
|
||||
wires = await self.env_client.run_group(
|
||||
task_idx=task_idx,
|
||||
n=group_size,
|
||||
client=client,
|
||||
model=model_name,
|
||||
sampling_args=self._sampling_args_with_salt(cache_salt),
|
||||
max_retries=self.config.max_retries,
|
||||
state_columns=self.state_columns,
|
||||
env_client=self.env_client,
|
||||
sampling=self._sampling(cache_salt),
|
||||
)
|
||||
return [ROLLOUT_TYPE.model_construct(**dict(wire)) for wire in wires]
|
||||
|
||||
def shutdown(self) -> None:
|
||||
if self._env_server_process is None:
|
||||
@@ -162,18 +202,14 @@ class Env:
|
||||
class TrainEnv(Env):
|
||||
config: TrainEnvConfig
|
||||
|
||||
def __init__(self, config: TrainEnvConfig):
|
||||
def __init__(self, config: TrainEnvConfig, max_seq_len: int):
|
||||
super().__init__(config)
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
# Built once — custom advantage funcs do an ``import_object`` we don't
|
||||
# want to pay per group. ``None`` = reward-only path.
|
||||
# Built once — custom advantage funcs do an ``import_object`` we don't want to pay per group.
|
||||
self.advantage_fn: AdvantageFn | None = (
|
||||
setup_advantage_fn(config.advantage) if config.advantage is not None else None
|
||||
setup_advantage_fn(config.advantage, max_seq_len=max_seq_len) if config.advantage is not None else None
|
||||
)
|
||||
|
||||
def get_dataset(self, seed: int | None = None):
|
||||
return self.env.get_dataset(seed=seed)
|
||||
|
||||
|
||||
class EvalEnv(Env):
|
||||
config: EvalEnvConfig
|
||||
@@ -181,7 +217,12 @@ class EvalEnv(Env):
|
||||
def __init__(self, config: EvalEnvConfig):
|
||||
super().__init__(config)
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
self.examples = self.env.get_eval_dataset(n=config.num_examples).to_list()
|
||||
self.examples: list[dict] = []
|
||||
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
await super().start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
|
||||
n = self.num_tasks if self.config.num_examples < 0 else min(self.config.num_examples, self.num_tasks)
|
||||
self.examples = [{"task_idx": i} for i in range(n)]
|
||||
|
||||
|
||||
EnvT = TypeVar("EnvT", bound=Env)
|
||||
@@ -209,23 +250,15 @@ class Envs(Generic[EnvT]):
|
||||
def __len__(self) -> int:
|
||||
return len(self._envs)
|
||||
|
||||
async def start(
|
||||
self,
|
||||
log_dir: Path,
|
||||
log_level: str | None = None,
|
||||
json_logging: bool = False,
|
||||
) -> None:
|
||||
"""Spawn env servers (where needed) and connect env clients one at a time.
|
||||
|
||||
Serialized to avoid a TOCTOU port race: get_free_port() only holds the port
|
||||
until it returns, so parallel spawns can hand the same port to two children.
|
||||
"""
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
"""Spawn env servers (where needed) and connect, one at a time. Each server
|
||||
binds an OS-assigned port and reports it back, so there's no port race."""
|
||||
for env in self:
|
||||
await env.start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
|
||||
atexit.register(self.shutdown)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Terminate all spawned env server processes in parallel."""
|
||||
"""Terminate all spawned env server processes."""
|
||||
processes = [env._env_server_process for env in self if env._env_server_process is not None]
|
||||
if not processes:
|
||||
return
|
||||
@@ -246,10 +279,10 @@ class Envs(Generic[EnvT]):
|
||||
class TrainEnvs(Envs[TrainEnv]):
|
||||
"""Collection of training environments."""
|
||||
|
||||
def __init__(self, configs: Sequence[TrainEnvConfig]):
|
||||
def __init__(self, configs: Sequence[TrainEnvConfig], max_seq_len: int):
|
||||
self._envs: dict[str, TrainEnv] = {}
|
||||
for config in configs:
|
||||
env = TrainEnv(config)
|
||||
env = TrainEnv(config, max_seq_len=max_seq_len)
|
||||
self._envs[env.name] = env
|
||||
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ from collections import defaultdict
|
||||
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.eval_utils import compute_pass_at_k
|
||||
from prime_rl.orchestrator.types import EvalBatch, EvalBatchMetrics, EvalRollout
|
||||
from prime_rl.orchestrator.types import EvalBatch, EvalBatchMetrics, Rollout
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -27,12 +27,12 @@ class EvalSink:
|
||||
|
||||
def __init__(self, *, eval_envs: EvalEnvs) -> None:
|
||||
self.eval_envs = eval_envs
|
||||
self.pending_groups: dict[uuid.UUID, list[EvalRollout]] = defaultdict(list)
|
||||
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
|
||||
# Bucket size IS the arrival count — ``process_group`` flushes
|
||||
# everything in without filtering
|
||||
self.pending_batches: dict[tuple[str, int], list[EvalRollout]] = defaultdict(list)
|
||||
self.pending_batches: dict[tuple[str, int], list[Rollout]] = defaultdict(list)
|
||||
|
||||
def add(self, rollout: EvalRollout) -> EvalBatch | None:
|
||||
def add(self, rollout: Rollout) -> EvalBatch | None:
|
||||
"""Process one arrival; finalize the group on the ``group_size``-th
|
||||
arrival and the per-env epoch on the ``num_examples × group_size``-th."""
|
||||
env_name = rollout.env_name
|
||||
@@ -82,7 +82,7 @@ class EvalSink:
|
||||
|
||||
# ── level 1: per-rollout (no-op for eval) ─────────────────────────────
|
||||
|
||||
def process_rollout(self, rollout: EvalRollout) -> None:
|
||||
def process_rollout(self, rollout: Rollout) -> None:
|
||||
"""No-op. Eval rollouts don't need trainer-bound tokenization; the
|
||||
method exists to keep the three-level structure uniform with
|
||||
``TrainSink``.
|
||||
@@ -96,17 +96,17 @@ class EvalSink:
|
||||
if not group:
|
||||
return
|
||||
env_name = group[0].env_name
|
||||
example_id = group[0].example_id
|
||||
task_idx = group[0].task.idx
|
||||
eval_step = group[0].eval_step
|
||||
bucket = self.pending_batches[(env_name, eval_step)]
|
||||
bucket.extend(group)
|
||||
|
||||
survivors = [r for r in group if r.error is None]
|
||||
survivors = [r for r in group if not r.has_error]
|
||||
num_errored = len(group) - len(survivors)
|
||||
rewards = [r.reward for r in survivors]
|
||||
avg_reward = sum(rewards) / len(rewards) if rewards else 0.0
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} example_id={example_id} eval_step={eval_step} | "
|
||||
f"Finished group | env={env_name} task_idx={task_idx} eval_step={eval_step} | "
|
||||
f"rollouts={len(group)} (errored={num_errored}) | reward={avg_reward:.4f}"
|
||||
)
|
||||
|
||||
@@ -120,9 +120,9 @@ class EvalSink:
|
||||
rollouts = self.pending_batches.pop(key, [])
|
||||
|
||||
n_total = len(rollouts)
|
||||
n_cancelled = sum(1 for r in rollouts if (r.error or {}).get("error") == "Cancelled")
|
||||
n_errored = sum(1 for r in rollouts if r.error is not None) - n_cancelled
|
||||
valid = [r for r in rollouts if r.error is None]
|
||||
n_cancelled = sum(1 for r in rollouts if r.has_error and r.error.type == "Cancelled")
|
||||
n_errored = sum(1 for r in rollouts if r.has_error) - n_cancelled
|
||||
valid = [r for r in rollouts if not r.has_error]
|
||||
metrics = EvalBatchMetrics(
|
||||
n_rollouts=n_total,
|
||||
n_cancelled=n_cancelled,
|
||||
@@ -131,23 +131,23 @@ class EvalSink:
|
||||
|
||||
if valid:
|
||||
rewards = [r.reward for r in valid]
|
||||
lens = [r.raw["token_usage"]["final_output_tokens"] for r in valid]
|
||||
lens = [sum(b.output_len for b in r.branches) for r in valid]
|
||||
metrics.group_size = self.group_size_for(env_name)
|
||||
metrics.reward_mean = float(sum(rewards) / len(rewards))
|
||||
metrics.completion_len_mean = float(sum(lens) / len(lens))
|
||||
metrics.completion_len_max = float(max(lens))
|
||||
metrics.completion_len_min = float(min(lens))
|
||||
metrics.truncation_rate = float(sum(1 for r in valid if r.is_truncated) / len(valid))
|
||||
metrics.no_response_rate = float(sum(1 for r in valid if not r.raw.get("completion")) / len(valid))
|
||||
num_turns = [len(r.raw.get("trajectory") or []) for r in valid]
|
||||
metrics.no_response_rate = float(sum(1 for r in valid if not r.has_response) / len(valid))
|
||||
num_turns = [r.num_turns for r in valid]
|
||||
metrics.num_turns_mean = float(sum(num_turns) / len(num_turns))
|
||||
metrics.num_turns_min = float(min(num_turns))
|
||||
metrics.num_turns_max = float(max(num_turns))
|
||||
|
||||
# pass@k: errored attempts don't count toward k tries
|
||||
by_example: dict[int | str, list[float]] = {}
|
||||
by_example: dict[int, list[float]] = {}
|
||||
for r in valid:
|
||||
by_example.setdefault(r.example_id, []).append(r.reward)
|
||||
by_example.setdefault(r.task.idx, []).append(r.reward)
|
||||
metrics.n_examples = len(by_example)
|
||||
unique_rewards = {float(r) for r in rewards}
|
||||
if unique_rewards.issubset({0.0, 1.0}) and by_example:
|
||||
|
||||
@@ -16,20 +16,19 @@ from prime_rl.configs.orchestrator import FilterConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import TrainRollout
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
@dataclass
|
||||
class FilterResult:
|
||||
detected: bool
|
||||
detection_index: int | None = None
|
||||
|
||||
|
||||
class RolloutFilter(Protocol):
|
||||
name: str
|
||||
enforce: bool
|
||||
|
||||
def check(self, rollout: "TrainRollout") -> FilterResult: ...
|
||||
def check(self, rollout: Rollout) -> FilterResult: ...
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -49,16 +48,16 @@ class GibberishFilter:
|
||||
logprob_threshold: float
|
||||
enforce: bool = False
|
||||
|
||||
def check(self, rollout: "TrainRollout") -> FilterResult:
|
||||
global_idx = 0
|
||||
for step in rollout.raw["trajectory"]:
|
||||
tokens = step["tokens"]
|
||||
if tokens is None:
|
||||
continue
|
||||
for token_id, logprob in zip(tokens["completion_ids"], tokens["completion_logprobs"]):
|
||||
def check(self, rollout: Rollout) -> FilterResult:
|
||||
for branch in rollout.branches:
|
||||
# branch.{token_ids,logprobs,sampled_mask} are flat and mutually aligned; the raw
|
||||
# node arrays are not (node.logprobs covers only the sampled suffix, not the
|
||||
# generation-prompt scaffold that token_ids/mask also span).
|
||||
for token_id, logprob, sampled in zip(branch.token_ids, branch.logprobs, branch.sampled_mask):
|
||||
if not sampled:
|
||||
continue
|
||||
if token_id > self.token_id_threshold and logprob < self.logprob_threshold:
|
||||
return FilterResult(detected=True, detection_index=global_idx)
|
||||
global_idx += 1
|
||||
return FilterResult(detected=True)
|
||||
return FilterResult(detected=False)
|
||||
|
||||
|
||||
@@ -79,21 +78,21 @@ class RepetitionFilter:
|
||||
logprob_threshold: float
|
||||
enforce: bool = False
|
||||
|
||||
def check(self, rollout: "TrainRollout") -> FilterResult:
|
||||
consecutive = 0
|
||||
global_idx = 0
|
||||
for step in rollout.raw["trajectory"]:
|
||||
tokens = step["tokens"]
|
||||
if tokens is None:
|
||||
continue
|
||||
for logprob in tokens["completion_logprobs"]:
|
||||
def check(self, rollout: Rollout) -> FilterResult:
|
||||
for branch in rollout.branches:
|
||||
# Aligned branch streams (see GibberishFilter), and reset the streak per branch:
|
||||
# flat rollout.nodes interleaves distinct root->leaf paths (compaction/subagents),
|
||||
# so a per-node walk would run a streak across a branch boundary.
|
||||
consecutive = 0
|
||||
for logprob, sampled in zip(branch.logprobs, branch.sampled_mask):
|
||||
if not sampled:
|
||||
continue
|
||||
if logprob > self.logprob_threshold:
|
||||
consecutive += 1
|
||||
else:
|
||||
consecutive = 0
|
||||
if consecutive >= self.window:
|
||||
return FilterResult(detected=True, detection_index=global_idx)
|
||||
global_idx += 1
|
||||
return FilterResult(detected=True)
|
||||
return FilterResult(detected=False)
|
||||
|
||||
|
||||
@@ -105,7 +104,7 @@ class ZeroAdvantageFilter:
|
||||
name: str
|
||||
enforce: bool = True
|
||||
|
||||
def check(self, rollout: "TrainRollout") -> FilterResult:
|
||||
def check(self, rollout: Rollout) -> FilterResult:
|
||||
if rollout.advantage is not None and rollout.advantage == 0.0:
|
||||
return FilterResult(detected=True)
|
||||
return FilterResult(detected=False)
|
||||
@@ -147,8 +146,8 @@ def setup_filters(configs: list[FilterConfig], vocab_size: int, *, kind: str) ->
|
||||
return filters
|
||||
|
||||
|
||||
def apply_filters(filters: list[RolloutFilter], rollouts: list["TrainRollout"]) -> None: # noqa: F821 (forward ref)
|
||||
"""Flag ``TrainRollout``\\ s in place with per-filter detection + drop decision.
|
||||
def apply_filters(filters: list[RolloutFilter], rollouts: list[Rollout]) -> None:
|
||||
"""Flag ``Rollout``\\ s in place with per-filter detection + drop decision.
|
||||
|
||||
Each rollout's ``filter_results`` dict records per-filter detection bools;
|
||||
``is_filtered`` is True iff an enforcing filter detected it. First matching
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
"""MetricsBuilder: assembles the per-step W&B dict.
|
||||
|
||||
The only I/O / state is the trainer's token-export metrics, which lag the
|
||||
orchestrator: ``build`` folds in the oldest unlogged stable step it finds on
|
||||
disk and tracks the last step logged so it never re-logs one.
|
||||
"""
|
||||
"""MetricsBuilder: assembles the per-step W&B dict. No I/O, no side effects."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -12,22 +7,18 @@ from typing import Any
|
||||
import pandas as pd
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.token_export_metrics import collect_next_token_export_metrics
|
||||
from prime_rl.orchestrator.types import Progress, TrainBatchMetrics, TrainRollout
|
||||
from prime_rl.orchestrator.types import Progress, Rollout, TrainBatchMetrics
|
||||
|
||||
|
||||
class MetricsBuilder:
|
||||
def __init__(self, config: OrchestratorConfig, start_step: int = 0) -> None:
|
||||
def __init__(self, config: OrchestratorConfig) -> None:
|
||||
self.config = config
|
||||
# Token exports are read back one step behind the orchestrator; track the
|
||||
# last run step whose metrics we've folded in so we never re-log a step.
|
||||
self._last_token_export_step_logged = start_step - 1
|
||||
|
||||
def build(
|
||||
self,
|
||||
*,
|
||||
step: int,
|
||||
rollouts: list[TrainRollout],
|
||||
rollouts: list[Rollout],
|
||||
metrics: TrainBatchMetrics,
|
||||
progress: Progress,
|
||||
step_time: float,
|
||||
@@ -41,30 +32,25 @@ class MetricsBuilder:
|
||||
existing dashboards / alerts keep working."""
|
||||
num_rollouts = len(rollouts)
|
||||
num_unique_examples = len({r.group_id for r in rollouts})
|
||||
num_tokens = sum(
|
||||
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"] for r in rollouts
|
||||
)
|
||||
num_tokens = sum(r.total_tokens for r in rollouts)
|
||||
|
||||
results_df = pd.DataFrame(
|
||||
{
|
||||
"group_id": [r.group_id for r in rollouts],
|
||||
"example_id": [r.example_id for r in rollouts],
|
||||
"task_idx": [r.task.idx for r in rollouts],
|
||||
"env_name": [r.env_name for r in rollouts],
|
||||
"reward": [r.reward for r in rollouts],
|
||||
"is_truncated": [r.is_truncated for r in rollouts],
|
||||
"is_filtered": [r.is_filtered for r in rollouts],
|
||||
"stop_condition": [r.raw.get("stop_condition") for r in rollouts],
|
||||
"seq_len": [
|
||||
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
|
||||
for r in rollouts
|
||||
],
|
||||
"stop_condition": [r.stop_condition for r in rollouts],
|
||||
"seq_len": [r.total_tokens for r in rollouts],
|
||||
"prefill_len": metrics.rollout_prefill_lens,
|
||||
"decode_len": metrics.rollout_decode_lens,
|
||||
"samples_per_rollout": metrics.samples_per_rollout,
|
||||
"num_turns": [len(r.raw["trajectory"]) for r in rollouts],
|
||||
"num_turns": [r.num_turns for r in rollouts],
|
||||
}
|
||||
)
|
||||
metrics_df = pd.DataFrame([(r.raw.get("metrics") or {}) for r in rollouts])
|
||||
metrics_df = pd.DataFrame([r.metrics for r in rollouts])
|
||||
filter_df = pd.DataFrame([r.filter_results for r in rollouts])
|
||||
timing_df = self.timing_df(rollouts)
|
||||
|
||||
@@ -188,42 +174,14 @@ class MetricsBuilder:
|
||||
for name, count in pre_filter_dropped_by_name.items():
|
||||
to_log[f"pre_filters/all/{name}/rate"] = count / pre_filter_seen
|
||||
|
||||
# Fold in the trainer's token-export metrics for the oldest unlogged stable
|
||||
# step (exports always lag the orchestrator, so this is a past step).
|
||||
to_log.update(self.next_token_export_metrics())
|
||||
|
||||
return to_log
|
||||
|
||||
@property
|
||||
def last_token_export_step_logged(self) -> int:
|
||||
return self._last_token_export_step_logged
|
||||
|
||||
def next_token_export_metrics(self) -> dict[str, float | int]:
|
||||
"""Log-ready token-export metrics for the next unlogged stable step (empty if
|
||||
none), advancing the cursor. They arrive under trainer/, including trainer/step
|
||||
(the run step they belong to) for plotting against a lag-corrected axis. Shared
|
||||
by build() and the orchestrator's end-of-run drain."""
|
||||
token_export = collect_next_token_export_metrics(
|
||||
self.config.output_dir,
|
||||
last_logged_step=self._last_token_export_step_logged,
|
||||
)
|
||||
if token_export:
|
||||
self._last_token_export_step_logged = token_export["trainer/step"]
|
||||
return token_export
|
||||
|
||||
@staticmethod
|
||||
def timing_df(rollouts: list[TrainRollout]) -> pd.DataFrame:
|
||||
return pd.DataFrame(
|
||||
[
|
||||
{
|
||||
"total": r.raw["timing"]["total"],
|
||||
"setup": r.raw["timing"]["setup"]["duration"],
|
||||
"generation": r.raw["timing"]["generation"]["duration"],
|
||||
"model": r.raw["timing"]["model"]["duration"],
|
||||
"env": r.raw["timing"]["env"]["duration"],
|
||||
"scoring": r.raw["timing"]["scoring"]["duration"],
|
||||
"overhead": r.raw["timing"]["overhead"],
|
||||
}
|
||||
for r in rollouts
|
||||
]
|
||||
)
|
||||
def timing_df(rollouts: list[Rollout]) -> pd.DataFrame:
|
||||
"""Per-rollout timing from the v1 Trace (`generation`/`scoring` spans)."""
|
||||
rows = []
|
||||
for r in rollouts:
|
||||
timing = r.timing
|
||||
generation, scoring = timing.generation.duration, timing.scoring.duration
|
||||
rows.append({"total": generation + scoring, "generation": generation, "scoring": scoring})
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
@@ -21,8 +21,6 @@ in ``setup()`` and drives them from ``main_loop()``.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import ctypes
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
@@ -37,8 +35,6 @@ if TYPE_CHECKING:
|
||||
from prime_rl.transport.base import TrainingBatchSender
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.monitor.base import Monitor
|
||||
from verifiers.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats
|
||||
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive imports
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
|
||||
@@ -58,12 +54,10 @@ from prime_rl.orchestrator.train_sink import TrainSink
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
from prime_rl.orchestrator.types import (
|
||||
EvalBatch,
|
||||
EvalRollout,
|
||||
FinishedRollout,
|
||||
Policy,
|
||||
Progress,
|
||||
Rollout,
|
||||
TrainBatch,
|
||||
TrainRollout,
|
||||
)
|
||||
from prime_rl.orchestrator.utils import (
|
||||
compute_teacher_logprobs,
|
||||
@@ -72,11 +66,12 @@ from prime_rl.orchestrator.utils import (
|
||||
save_rollouts,
|
||||
set_default_executor,
|
||||
setup_student_inference_pool,
|
||||
trim_process_memory,
|
||||
)
|
||||
from prime_rl.orchestrator.watcher import WeightWatcher
|
||||
from prime_rl.trainer.model import setup_tokenizer
|
||||
from prime_rl.transport import TrainingBatch, setup_training_batch_sender
|
||||
from prime_rl.utils.async_utils import safe_cancel
|
||||
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
|
||||
from prime_rl.utils.client import init_nccl_broadcast, setup_inference_pool
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
@@ -85,8 +80,6 @@ from prime_rl.utils.pathing import get_log_dir, get_rollout_dir, get_step_path
|
||||
from prime_rl.utils.usage_reporter import UsageReporter
|
||||
from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
get_env_ids_to_install,
|
||||
install_env,
|
||||
resolve_latest_ckpt_step,
|
||||
)
|
||||
|
||||
@@ -108,10 +101,12 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
|
||||
# resumed when the watcher advances ``policy.version``.
|
||||
TARGET_LAG = 1
|
||||
|
||||
# After max_steps, how long to wait for the trainer to finalize the trailing
|
||||
# token-export steps it hadn't flushed yet, and how often to poll for them.
|
||||
TOKEN_EXPORT_DRAIN_TIMEOUT_S = 300.0
|
||||
TOKEN_EXPORT_DRAIN_POLL_S = 2.0
|
||||
# Drop the per-node training tensors when dumping a Trace to disk (rollout jsonl / wandb
|
||||
# tables): the multimodal `mm_kwargs` carrier and the router-replay `routed_experts` array are
|
||||
# training inputs, not part of the rollout record, and would bloat every line. They also can't
|
||||
# round-trip the json dump — their `__nd__` carriers hold raw bytes. `__all__` applies the
|
||||
# exclude to every node in the list.
|
||||
ROLLOUT_DUMP_EXCLUDE = {"nodes": {"__all__": {"multi_modal_data", "routed_experts"}}}
|
||||
|
||||
|
||||
class Orchestrator:
|
||||
@@ -158,10 +153,9 @@ class Orchestrator:
|
||||
def __init__(self, config: OrchestratorConfig) -> None:
|
||||
self.config = config
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
# Silence in-process ``verifiers.*`` library noise but keep
|
||||
# ``verifiers.serve`` (env-server lifecycle) through our handler
|
||||
logging.getLogger("verifiers").setLevel(logging.CRITICAL + 1)
|
||||
intercept_vf_logging(logger="verifiers.serve", level="WARN")
|
||||
# Route the in-process v1 library logging through our handler. The
|
||||
# env server runs in a child process, so its logging is separate.
|
||||
intercept_vf_logging(logger="verifiers.v1", level="WARN")
|
||||
get_logger().info(f"Starting orchestrator ({config.training_mode})")
|
||||
|
||||
if config.bench:
|
||||
@@ -211,12 +205,6 @@ class Orchestrator:
|
||||
with open(config_dir / "orch.toml", "wb") as f:
|
||||
tomli_w.dump(config.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
env_ids_to_install = set(get_env_ids_to_install(config.train.env))
|
||||
if config.eval is not None:
|
||||
env_ids_to_install.update(get_env_ids_to_install(config.eval.env))
|
||||
for env_id in env_ids_to_install:
|
||||
install_env(env_id, prerelease=config.env_install_prerelease)
|
||||
|
||||
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
self.tokenizer = setup_tokenizer(config.tokenizer)
|
||||
|
||||
@@ -242,7 +230,11 @@ class Orchestrator:
|
||||
self.teacher_inference = await setup_inference_pool(
|
||||
config.teacher.client,
|
||||
model_name=config.teacher.model.name,
|
||||
train_client_type="openai_chat_completions",
|
||||
# SFT rolls the teacher out through the renderer client (token-in/out) so its
|
||||
# rollouts carry tokens directly — training is renderer-only. (OPD reads teacher
|
||||
# logprobs via prefill, so its pool client type is moot.)
|
||||
train_client_type="renderer",
|
||||
renderer_config=config.renderer,
|
||||
)
|
||||
|
||||
get_logger().info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
|
||||
@@ -268,7 +260,7 @@ class Orchestrator:
|
||||
post_filters = setup_filters(config.post_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="post-batch")
|
||||
|
||||
get_logger().info("Loading training environments")
|
||||
self.train_envs = TrainEnvs(config.train.env)
|
||||
self.train_envs = TrainEnvs(config.train.env, max_seq_len=config.seq_len)
|
||||
if config.training_mode == "sft":
|
||||
for env in self.train_envs:
|
||||
env.sampling_args.pop("logprobs", None)
|
||||
@@ -387,11 +379,10 @@ class Orchestrator:
|
||||
training_mode=config.training_mode,
|
||||
use_cache_salt=use_cache_salt,
|
||||
)
|
||||
self.metrics = MetricsBuilder(config, start_step=self.progress.step)
|
||||
self.metrics = MetricsBuilder(config)
|
||||
self.train_sink = TrainSink(
|
||||
config,
|
||||
tokenizer=self.tokenizer,
|
||||
renderer=self.renderer,
|
||||
train_envs=self.train_envs,
|
||||
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
|
||||
batch_size=config.batch_size,
|
||||
@@ -465,7 +456,6 @@ class Orchestrator:
|
||||
clean_exit = False
|
||||
try:
|
||||
await self.main_loop()
|
||||
await self._drain_token_export_metrics()
|
||||
clean_exit = True
|
||||
finally:
|
||||
elapsed = format_time(time.perf_counter() - start_time)
|
||||
@@ -482,10 +472,7 @@ class Orchestrator:
|
||||
get_logger().success("Orchestrator finished.")
|
||||
else:
|
||||
get_logger().warning("Orchestrator cleanup complete (forced).")
|
||||
try:
|
||||
ctypes.CDLL("libc.so.6").malloc_trim(0)
|
||||
except Exception as e:
|
||||
get_logger().debug(f"malloc_trim(0) failed: {e}")
|
||||
trim_process_memory()
|
||||
|
||||
async def main_loop(self) -> None:
|
||||
"""Consume ``FinishedRollout``\\ s from the dispatcher and route them
|
||||
@@ -498,53 +485,23 @@ class Orchestrator:
|
||||
break
|
||||
|
||||
try:
|
||||
rollout: FinishedRollout = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
|
||||
rollout: Rollout = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
|
||||
if isinstance(rollout, EvalRollout):
|
||||
if rollout.kind == "eval":
|
||||
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
|
||||
eval_batch = self.eval_sink.add(rollout)
|
||||
if eval_batch is not None:
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
continue
|
||||
|
||||
assert isinstance(rollout, TrainRollout)
|
||||
train_batch = await self.train_sink.add(rollout)
|
||||
# In drain mode any late-arriving train batch is dropped — we
|
||||
# don't want to ship past ``max_steps``
|
||||
if train_batch is not None and not self.draining and not self.stopped.is_set():
|
||||
await self.finalize_train_batch(train_batch)
|
||||
|
||||
async def _drain_token_export_metrics(self) -> None:
|
||||
"""Token exports lag the orchestrator, so once the loop ends the trainer is
|
||||
still finalizing the last shipped steps and ``build`` no longer runs to pick
|
||||
them up. Poll for the remaining stable steps up to ``max_steps - 1`` and log
|
||||
each under its own ``trainer/step`` (a local W&B step axis, so the final
|
||||
checkpoint's ``progress.step`` is untouched)."""
|
||||
if self.config.max_steps is None:
|
||||
return
|
||||
if not (self.config.output_dir / "token_exports").exists():
|
||||
return # token export not enabled for this run — don't block shutdown
|
||||
target = self.config.max_steps - 1
|
||||
if self.metrics.last_token_export_step_logged >= target:
|
||||
return # build() already kept up — nothing trailing to flush
|
||||
wandb_step = self.progress.step
|
||||
deadline = time.perf_counter() + TOKEN_EXPORT_DRAIN_TIMEOUT_S
|
||||
while time.perf_counter() < deadline:
|
||||
token_export = self.metrics.next_token_export_metrics()
|
||||
if not token_export:
|
||||
await asyncio.sleep(TOKEN_EXPORT_DRAIN_POLL_S)
|
||||
continue
|
||||
self.monitor.log(token_export, step=wandb_step)
|
||||
wandb_step += 1
|
||||
if self.metrics.last_token_export_step_logged >= target:
|
||||
return
|
||||
get_logger().warning(
|
||||
f"Token-export drain timed out before step {target} "
|
||||
f"(last logged {self.metrics.last_token_export_step_logged})"
|
||||
)
|
||||
|
||||
async def finalize_train_batch(self, batch: TrainBatch) -> None:
|
||||
"""Ship one ``TrainBatch`` out to the trainer and handle the I/O
|
||||
side-effects (ckpt, save_rollouts, teacher logprobs, sender.send,
|
||||
@@ -591,13 +548,11 @@ class Orchestrator:
|
||||
f"({batch.metrics.n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
|
||||
)
|
||||
|
||||
# Materialize at the I/O boundary so prime-rl metadata travels with
|
||||
# the raw vf payload on disk + in wandb sample tables
|
||||
rollout_dicts = [r.to_dict() for r in batch.rollouts]
|
||||
# Serialize the typed Trace at the I/O boundary (disk + wandb sample tables); drop the
|
||||
# per-node multimodal tensors — they're for training, not the rollout record, and bloat it.
|
||||
rollout_dicts = [r.model_dump(mode="json", exclude=ROLLOUT_DUMP_EXCLUDE) for r in batch.rollouts]
|
||||
step_path = get_step_path(get_rollout_dir(config.output_dir), step)
|
||||
await asyncio.to_thread(
|
||||
save_rollouts, rollout_dicts, step_path / "train_rollouts.jsonl", exclude_keys={"trajectory"}
|
||||
)
|
||||
await asyncio.to_thread(save_rollouts, rollout_dicts, step_path / "train_rollouts.jsonl")
|
||||
|
||||
teacher_logprobs_time = 0.0 # opd only
|
||||
if config.training_mode == "opd" and self.teacher_inference is not None:
|
||||
@@ -614,6 +569,7 @@ class Orchestrator:
|
||||
|
||||
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
|
||||
self.update_dispatch_gate()
|
||||
trim_process_memory()
|
||||
|
||||
metrics = self.metrics.build(
|
||||
step=step,
|
||||
@@ -628,7 +584,7 @@ class Orchestrator:
|
||||
pre_filter_dropped_by_name=dict(self.train_sink.pre_filter_dropped_by_name),
|
||||
)
|
||||
self.monitor.log(metrics, step=step)
|
||||
self.monitor.log_samples(rollout_dicts, step=step)
|
||||
self.monitor.log_samples(batch.rollouts, step=step)
|
||||
self.monitor.log_distributions(
|
||||
distributions={
|
||||
"rewards": [r.reward for r in batch.rollouts],
|
||||
@@ -650,10 +606,7 @@ class Orchestrator:
|
||||
|
||||
num_rollouts = len(batch.rollouts)
|
||||
num_unique_examples = len({r.group_id for r in batch.rollouts})
|
||||
num_tokens = sum(
|
||||
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
|
||||
for r in batch.rollouts
|
||||
)
|
||||
num_tokens = sum(r.total_tokens for r in batch.rollouts)
|
||||
self.progress.total_tokens += num_tokens
|
||||
self.progress.total_samples += num_rollouts
|
||||
self.progress.total_problems += num_unique_examples
|
||||
@@ -663,6 +616,7 @@ class Orchestrator:
|
||||
self.train_sink.reset_pre_filter_stats()
|
||||
self.progress.step += 1
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
trim_process_memory()
|
||||
|
||||
def maybe_trigger_eval(self, step: int) -> None:
|
||||
"""Fire eligible eval epochs and flip to ``PREFER_EVAL`` if anything
|
||||
@@ -760,13 +714,14 @@ class Orchestrator:
|
||||
trainable_rate = (n_trainable / n_survivors) if n_survivors else 0.0
|
||||
reward_mean = sum(r.reward for r in batch.rollouts) / max(n_survivors, 1)
|
||||
max_off_policy = max((r.off_policy_steps for r in batch.rollouts), default=0)
|
||||
turns_mean = sum(len(r.raw.get("trajectory") or []) for r in batch.rollouts) / max(n_survivors, 1)
|
||||
turns_mean = sum(r.num_turns for r in batch.rollouts) / max(n_survivors, 1)
|
||||
branches_mean = sum(r.num_branches for r in batch.rollouts) / max(n_survivors, 1)
|
||||
truncation_rate = sum(1 for r in batch.rollouts if r.is_truncated) / max(n_survivors, 1)
|
||||
|
||||
head = (
|
||||
f"Step {step} | {format_time(step_time):>7} | Reward {reward_mean:.4f} | "
|
||||
f"Trainable {n_trainable}/{n_survivors} ({trainable_rate:.1%}) | "
|
||||
f"Turns {turns_mean:.1f} | Max Off-Policy {max_off_policy} | "
|
||||
f"Turns {turns_mean:.1f} | Branches {branches_mean:.1f} | Max Off-Policy {max_off_policy} | "
|
||||
f"Error {error_rate:.1%} | Truncation {truncation_rate:.1%}"
|
||||
)
|
||||
if len(self.train_envs) <= 1:
|
||||
@@ -784,15 +739,12 @@ class Orchestrator:
|
||||
env_error_rate = (n_env_errors / n_env_arrivals) if n_env_arrivals else 0.0
|
||||
env_reward = (sum(r.reward for r in env_rollouts) / len(env_rollouts)) if env_rollouts else 0.0
|
||||
env_max_off_policy = max((r.off_policy_steps for r in env_rollouts), default=0)
|
||||
env_turns = (
|
||||
sum(len(r.raw.get("trajectory") or []) for r in env_rollouts) / len(env_rollouts)
|
||||
if env_rollouts
|
||||
else 0.0
|
||||
)
|
||||
env_turns = sum(r.num_turns for r in env_rollouts) / len(env_rollouts) if env_rollouts else 0.0
|
||||
env_branches = sum(r.num_branches for r in env_rollouts) / len(env_rollouts) if env_rollouts else 0.0
|
||||
env_truncation = sum(1 for r in env_rollouts if r.is_truncated) / len(env_rollouts) if env_rollouts else 0.0
|
||||
lines.append(
|
||||
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_reward:.4f} | "
|
||||
f"Turns {env_turns:.1f} | Max Off-Policy {env_max_off_policy} | "
|
||||
f"Turns {env_turns:.1f} | Branches {env_branches:.1f} | Max Off-Policy {env_max_off_policy} | "
|
||||
f"Error {env_error_rate:.1%} | Truncation {env_truncation:.1%}"
|
||||
)
|
||||
get_logger().success("\n\t\t ".join(lines))
|
||||
@@ -804,15 +756,14 @@ class Orchestrator:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no surviving rollouts, skipping log")
|
||||
return
|
||||
|
||||
rollout_dicts = [r.to_dict() for r in batch.rollouts]
|
||||
rollout_dicts = [r.model_dump(mode="json", exclude=ROLLOUT_DUMP_EXCLUDE) for r in batch.rollouts]
|
||||
step_path = get_step_path(get_rollout_dir(self.config.output_dir), batch.step)
|
||||
await asyncio.to_thread(
|
||||
save_rollouts,
|
||||
rollout_dicts,
|
||||
step_path / f"eval_rollouts_{batch.env_name}.jsonl",
|
||||
exclude_keys={"trajectory"},
|
||||
)
|
||||
self.monitor.log_eval_samples(rollout_dicts, env_name=batch.env_name, step=batch.step)
|
||||
self.monitor.log_eval_samples(batch.rollouts, env_name=batch.env_name, step=batch.step)
|
||||
policy_versions = {r.policy_version for r in batch.rollouts}
|
||||
policy_version = min(policy_versions)
|
||||
if len(policy_versions) > 1:
|
||||
@@ -827,11 +778,12 @@ class Orchestrator:
|
||||
error_rate = ((batch.metrics.n_cancelled + batch.metrics.n_errored) / n_total) if n_total else 0.0
|
||||
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
|
||||
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
|
||||
branches_mean = sum(r.num_branches for r in batch.rollouts) / len(batch.rollouts)
|
||||
|
||||
get_logger().success(
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {batch.metrics.reward_mean:.4f} | "
|
||||
f"Turns {batch.metrics.num_turns_mean:.1f} | "
|
||||
f"Turns {batch.metrics.num_turns_mean:.1f} | Branches {branches_mean:.1f} | "
|
||||
f"Error {error_rate:.1%} | Truncation {batch.metrics.truncation_rate:.1%}"
|
||||
)
|
||||
|
||||
@@ -876,6 +828,10 @@ class Orchestrator:
|
||||
get_logger().info("Resuming dispatcher")
|
||||
gate.set()
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""No-op: the dispatch gate is re-evaluated in ``on_new_version`` once
|
||||
the new policy version is live."""
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""``VersionObserver`` hook: the watcher just advanced ``policy.version``;
|
||||
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
TOKEN_EXPORT_METRIC_FIELDS = ("mismatch_kl", "entropy")
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Stats:
|
||||
total: float = 0.0
|
||||
count: int = 0
|
||||
maximum: float = -math.inf
|
||||
|
||||
def add(self, value: Any) -> None:
|
||||
if not isinstance(value, int | float):
|
||||
return
|
||||
value = float(value)
|
||||
if not math.isfinite(value):
|
||||
return
|
||||
self.total += value
|
||||
self.count += 1
|
||||
self.maximum = max(self.maximum, value)
|
||||
|
||||
def as_metrics(self, prefix: str) -> dict[str, float]:
|
||||
if self.count == 0:
|
||||
return {}
|
||||
return {
|
||||
f"{prefix}/mean": self.total / self.count,
|
||||
f"{prefix}/max": self.maximum,
|
||||
}
|
||||
|
||||
|
||||
def collect_next_token_export_metrics(output_dir: Path, *, last_logged_step: int) -> dict[str, float | int]:
|
||||
"""Log-ready metrics for the oldest unlogged stable step, namespaced under
|
||||
``trainer/`` and stamped with ``trainer/step`` (the run step they belong to).
|
||||
Empty when there is no new stable step."""
|
||||
stable_steps = [step for step in _stable_token_export_steps(output_dir) if step > last_logged_step]
|
||||
if not stable_steps:
|
||||
return {}
|
||||
|
||||
step = min(stable_steps)
|
||||
metrics: dict[str, float | int] = {
|
||||
f"trainer/{key}": value for key, value in collect_token_export_metrics(output_dir, step).items()
|
||||
}
|
||||
metrics["trainer/step"] = step
|
||||
return metrics
|
||||
|
||||
|
||||
def collect_token_export_metrics(output_dir: Path, step: int) -> dict[str, float | int]:
|
||||
step_dir = output_dir / "token_exports" / f"step_{step}"
|
||||
if not (step_dir / "STABLE").exists():
|
||||
return {}
|
||||
|
||||
stats_by_key: dict[str, _Stats] = {}
|
||||
sequence_count = 0
|
||||
skipped_count = 0
|
||||
|
||||
for export_file in sorted(step_dir.glob("rank_*.jsonl")):
|
||||
with export_file.open(encoding="utf-8") as file:
|
||||
for line in file:
|
||||
if not line.strip():
|
||||
continue
|
||||
# Token exports are best-effort monitoring; a malformed line or a
|
||||
# length-mismatched record shouldn't abort the orchestrator step.
|
||||
try:
|
||||
record = json.loads(line)
|
||||
values_by_field = {field: _loss_token_values(record, field) for field in TOKEN_EXPORT_METRIC_FIELDS}
|
||||
except ValueError:
|
||||
skipped_count += 1
|
||||
continue
|
||||
sequence_count += 1
|
||||
for field, values in values_by_field.items():
|
||||
for value in values:
|
||||
stats_by_key.setdefault(field, _Stats()).add(value)
|
||||
|
||||
if skipped_count:
|
||||
get_logger().warning(f"Skipped {skipped_count} malformed token-export record(s) in {step_dir}")
|
||||
|
||||
metrics: dict[str, float | int] = {}
|
||||
if sequence_count == 0:
|
||||
return metrics
|
||||
for key, stats in sorted(stats_by_key.items()):
|
||||
metrics.update(stats.as_metrics(key))
|
||||
return metrics
|
||||
|
||||
|
||||
def _stable_token_export_steps(output_dir: Path) -> list[int]:
|
||||
token_exports_dir = output_dir / "token_exports"
|
||||
if not token_exports_dir.exists():
|
||||
return []
|
||||
|
||||
steps = []
|
||||
for step_dir in token_exports_dir.glob("step_*"):
|
||||
if not (step_dir / "STABLE").exists():
|
||||
continue
|
||||
try:
|
||||
steps.append(int(step_dir.name.removeprefix("step_")))
|
||||
except ValueError:
|
||||
continue
|
||||
return sorted(steps)
|
||||
|
||||
|
||||
def _loss_token_values(record: dict[str, Any], field: str) -> list[Any]:
|
||||
loss_mask = record.get("loss_mask", [])
|
||||
values = record.get(field, [])
|
||||
if len(loss_mask) != len(values):
|
||||
raise ValueError(
|
||||
f"Token export record has mismatched loss_mask and {field} lengths: {len(loss_mask)} != {len(values)}"
|
||||
)
|
||||
return [value for value, keep in zip(values, loss_mask) if keep]
|
||||
@@ -21,12 +21,8 @@ from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.advantage import assign_advantages
|
||||
from prime_rl.orchestrator.envs import TrainEnvs
|
||||
from prime_rl.orchestrator.filters import RolloutFilter, apply_filters
|
||||
from prime_rl.orchestrator.trajectories import (
|
||||
backfill_rollout_tokens,
|
||||
interleave_rollout,
|
||||
offload_images_to_disk,
|
||||
)
|
||||
from prime_rl.orchestrator.types import TrainBatch, TrainBatchMetrics, TrainRollout
|
||||
from prime_rl.orchestrator.trajectories import trace_to_samples
|
||||
from prime_rl.orchestrator.types import Rollout, TrainBatch, TrainBatchMetrics
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -39,7 +35,6 @@ class TrainSink:
|
||||
config: OrchestratorConfig,
|
||||
*,
|
||||
tokenizer,
|
||||
renderer,
|
||||
train_envs: TrainEnvs,
|
||||
mm_token_type_ids_mapping: dict[int, int] | None,
|
||||
batch_size: int | None,
|
||||
@@ -52,7 +47,6 @@ class TrainSink:
|
||||
)
|
||||
self.config = config
|
||||
self.tokenizer = tokenizer
|
||||
self.renderer = renderer
|
||||
self.train_envs = train_envs
|
||||
self.mm_token_type_ids_mapping = mm_token_type_ids_mapping
|
||||
self.batch_size = batch_size
|
||||
@@ -60,11 +54,15 @@ class TrainSink:
|
||||
self.pre_filters = pre_filters
|
||||
self.post_filters = post_filters
|
||||
|
||||
# Keyed by the dispatcher's group UUID. ``(env_name, example_id)``
|
||||
# isn't unique — the same example can be re-sampled while an
|
||||
# Keyed by the dispatcher's group UUID. ``(env_name, task_idx)``
|
||||
# isn't unique — the same task can be re-sampled while an
|
||||
# earlier group is still in flight
|
||||
self.pending_groups: dict[uuid.UUID, list[TrainRollout]] = defaultdict(list)
|
||||
self.pending_batch: list[TrainRollout] = []
|
||||
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
|
||||
self.pending_batch: list[Rollout] = []
|
||||
# Running token total of ``pending_batch`` (token-batched runs), kept in
|
||||
# sync on append/pop so the readiness check never re-walks the uncached
|
||||
# ``Trace.total_tokens`` graph property per arrival.
|
||||
self.pending_tokens: int = 0
|
||||
|
||||
# Reset by the orchestrator after each ship via ``reset_pre_filter_stats``
|
||||
self.pre_filter_seen = 0
|
||||
@@ -79,13 +77,13 @@ class TrainSink:
|
||||
def group_size_for(self, env_name: str) -> int:
|
||||
return self.train_envs.get(env_name).config.group_size
|
||||
|
||||
def in_progress_groups(self) -> list[list[TrainRollout]]:
|
||||
def in_progress_groups(self) -> list[list[Rollout]]:
|
||||
"""Per-rollout groups currently accumulating in ``pending_groups`` —
|
||||
i.e. groups that haven't hit ``group_size`` yet, so the pipeline log
|
||||
can reflect partial-group progress. Skips group-scoring envs (whose
|
||||
rollouts only make sense as a unit — the user expects per-group
|
||||
fill, not per-rollout, for those)."""
|
||||
out: list[list[TrainRollout]] = []
|
||||
out: list[list[Rollout]] = []
|
||||
for rollouts in self.pending_groups.values():
|
||||
if not rollouts:
|
||||
continue
|
||||
@@ -103,11 +101,7 @@ class TrainSink:
|
||||
if self.batch_size is not None:
|
||||
return len(self.pending_batch), self.batch_size, "rollouts"
|
||||
assert self.token_batch_size is not None
|
||||
tokens = sum(
|
||||
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
|
||||
for r in self.pending_batch
|
||||
)
|
||||
return tokens, self.token_batch_size, "tokens"
|
||||
return self.pending_tokens, self.token_batch_size, "tokens"
|
||||
|
||||
def buffered_count(self) -> int:
|
||||
"""Rollouts that have arrived but sit in not-yet-complete groups
|
||||
@@ -122,13 +116,13 @@ class TrainSink:
|
||||
counts[r.env_name] += 1
|
||||
return dict(counts)
|
||||
|
||||
async def add(self, rollout: TrainRollout) -> TrainBatch | None:
|
||||
async def add(self, rollout: Rollout) -> TrainBatch | None:
|
||||
"""Process one arrival; finalize the group on the ``group_size``-th
|
||||
arrival; return a ``TrainBatch`` if the batch threshold is met."""
|
||||
await self.process_rollout(rollout)
|
||||
env_name = rollout.env_name
|
||||
self.arrivals_by_env[env_name] += 1
|
||||
if rollout.error is not None:
|
||||
if rollout.has_error:
|
||||
self.errors_by_env[env_name] += 1
|
||||
self.pending_groups[rollout.group_id].append(rollout)
|
||||
if len(self.pending_groups[rollout.group_id]) >= self.group_size_for(env_name):
|
||||
@@ -136,37 +130,26 @@ class TrainSink:
|
||||
ready = (
|
||||
len(self.pending_batch) >= self.batch_size
|
||||
if self.batch_size is not None
|
||||
else sum(
|
||||
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
|
||||
for r in self.pending_batch
|
||||
)
|
||||
>= (self.token_batch_size or 0)
|
||||
else self.pending_tokens >= (self.token_batch_size or 0)
|
||||
)
|
||||
if ready:
|
||||
return self.process_batch()
|
||||
return None
|
||||
|
||||
async def process_rollout(self, rollout: TrainRollout) -> None:
|
||||
"""Tokenize the rollout eagerly. Backfills tokens if the env didn't
|
||||
return them (SFT against external teacher APIs); errored rollouts
|
||||
skip tokenization and get dropped at the group level."""
|
||||
if rollout.error is not None:
|
||||
async def process_rollout(self, rollout: Rollout) -> None:
|
||||
"""Build training samples from the rollout's Trace (one per branch), walking the
|
||||
message graph. Training is renderer-only across all modes (RL/OPD student, SFT teacher),
|
||||
so every node already carries its tokens. Errored rollouts are dropped at the group
|
||||
level, so skip them here."""
|
||||
if rollout.has_error:
|
||||
return
|
||||
raw = rollout.raw
|
||||
needs_backfill = any(s["tokens"] is None for s in raw.get("trajectory") or [])
|
||||
if needs_backfill:
|
||||
await asyncio.to_thread(backfill_rollout_tokens, raw, self.tokenizer, renderer=self.renderer)
|
||||
samples = await asyncio.to_thread(
|
||||
interleave_rollout,
|
||||
raw,
|
||||
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
|
||||
trace_to_samples,
|
||||
rollout,
|
||||
env_name=rollout.env_name,
|
||||
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
|
||||
)
|
||||
rollout.samples = samples or []
|
||||
# Offload base64 image bytes to disk as soon as the rollout is
|
||||
# tokenized, so memory stays flat instead of holding every buffered
|
||||
# rollout's images until the batch ships (no-op for text-only).
|
||||
await asyncio.to_thread(offload_images_to_disk, [raw], self.config.output_dir)
|
||||
|
||||
def process_group(self, group_id: uuid.UUID) -> None:
|
||||
"""Finalize one GRPO group: drop errored rollouts (the whole group
|
||||
@@ -176,8 +159,8 @@ class TrainSink:
|
||||
if not group:
|
||||
return
|
||||
env_name = group[0].env_name
|
||||
example_id = group[0].example_id
|
||||
survivors = [r for r in group if r.error is None]
|
||||
task_idx = group[0].task.idx
|
||||
survivors = [r for r in group if not r.has_error]
|
||||
num_errored = len(group) - len(survivors)
|
||||
|
||||
# Group-scoring envs: any failure makes survivors' rewards unsafe
|
||||
@@ -185,23 +168,23 @@ class TrainSink:
|
||||
env = self.train_envs.get(env_name)
|
||||
if num_errored > 0 and env.requires_group_scoring:
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} example_id={example_id} | "
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
f"rollouts={len(group)} (errored={num_errored}) | dropped: group-scored partial"
|
||||
)
|
||||
return
|
||||
if not survivors:
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} example_id={example_id} | "
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
f"rollouts={len(group)} (errored={num_errored}) | dropped: all failed"
|
||||
)
|
||||
return
|
||||
|
||||
assign_advantages(survivors, self.train_envs.get(env_name).advantage_fn)
|
||||
assign_advantages(survivors, env.advantage_fn)
|
||||
|
||||
# Propagate to the pre-tokenized samples so the orchestrator can
|
||||
# collect samples at ship time without re-walking rollouts. The env
|
||||
# has a single sampling temperature; fan it out across each sample's
|
||||
# completion tokens here (interleave leaves it empty).
|
||||
# has a single sampling temperature; fan it out per token (context
|
||||
# tokens are masked out, so their temperature is don't-care).
|
||||
temperature = env.sampling_args["temperature"]
|
||||
for r in survivors:
|
||||
for sample in r.samples:
|
||||
@@ -209,7 +192,7 @@ class TrainSink:
|
||||
sample.reward = r.reward
|
||||
sample.env_name = r.env_name
|
||||
sample.training_mode = self.config.training_mode
|
||||
sample.completion_temperatures = [temperature] * len(sample.completion_ids)
|
||||
sample.temperatures = [temperature] * len(sample.token_ids)
|
||||
|
||||
if self.pre_filters:
|
||||
apply_filters(self.pre_filters, survivors)
|
||||
@@ -229,6 +212,8 @@ class TrainSink:
|
||||
r.filter_results = {}
|
||||
r.is_filtered = False
|
||||
self.pending_batch.append(r)
|
||||
if self.token_batch_size is not None:
|
||||
self.pending_tokens += r.total_tokens
|
||||
|
||||
# Per-group summary. One line per finalized group; per-filter
|
||||
# detection breakdown lives at debug level in ``apply_filters``
|
||||
@@ -236,7 +221,7 @@ class TrainSink:
|
||||
avg_reward = sum(rewards) / len(rewards) if rewards else 0.0
|
||||
filter_str = ", ".join(f"{n}={c}" for n, c in filtered_by_name.items()) if filtered_by_name else "—"
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} example_id={example_id} | "
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
f"rollouts={len(group)} (errored={num_errored}, filtered={num_filtered}) | "
|
||||
f"reward={avg_reward:.4f} | filters: {filter_str}"
|
||||
)
|
||||
@@ -255,12 +240,13 @@ class TrainSink:
|
||||
cut = 0
|
||||
running = 0
|
||||
for i, r in enumerate(self.pending_batch):
|
||||
running += r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
|
||||
running += r.total_tokens
|
||||
cut = i + 1
|
||||
if running >= self.token_batch_size:
|
||||
break
|
||||
cohort = self.pending_batch[:cut]
|
||||
self.pending_batch = self.pending_batch[cut:]
|
||||
self.pending_tokens -= running
|
||||
|
||||
if self.post_filters:
|
||||
apply_filters(self.post_filters, cohort)
|
||||
@@ -278,8 +264,8 @@ class TrainSink:
|
||||
prefill = 0
|
||||
decode = 0
|
||||
for sample in r.samples:
|
||||
sample_decode = sum(sample.completion_mask)
|
||||
sample_prefill = len(sample.prompt_ids) + len(sample.completion_mask) - sample_decode
|
||||
sample_decode = sum(sample.mask)
|
||||
sample_prefill = len(sample.token_ids) - sample_decode
|
||||
decode += sample_decode
|
||||
prefill += sample_prefill
|
||||
if not r.is_filtered:
|
||||
|
||||
@@ -14,7 +14,7 @@ class TrainSource:
|
||||
"""``next_example(available_permits)`` picks a weighted-RR env and
|
||||
returns its next example (or ``None`` when the env's per-call permit
|
||||
cost doesn't fit — the dispatch loop retries when permits free up).
|
||||
Returned dicts carry ``env_name`` + ``example_id``."""
|
||||
Returned dicts carry ``env_name`` + ``task_idx``."""
|
||||
|
||||
def __init__(self, train_envs: TrainEnvs, *, seed: int | None) -> None:
|
||||
self.rng = random.Random(seed)
|
||||
@@ -28,11 +28,9 @@ class TrainSource:
|
||||
# per-rollout envs need 1
|
||||
self.env_costs: dict[str, int] = {}
|
||||
for env in self.envs:
|
||||
rows: list[dict] = []
|
||||
for row in env.get_dataset(seed=seed):
|
||||
ex = dict(row)
|
||||
ex["env_name"] = env.name
|
||||
rows.append(ex)
|
||||
# The orchestrator never loads the env: sample over the task-index
|
||||
# range the server reported via info() (num_tasks).
|
||||
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
|
||||
self.rng.shuffle(rows)
|
||||
self.examples[env.name] = rows
|
||||
self.cursors[env.name] = 0
|
||||
|
||||
@@ -1,652 +1,115 @@
|
||||
import base64
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
"""Turn a v1 `Trace` (the env server's native, typed output) into training data.
|
||||
|
||||
The orchestrator holds a real `vf.Trace` (validated in `envs.py`), so everything here is
|
||||
attribute access — no dicts. The trace is a message graph (`trace.nodes`); each `trace.branches`
|
||||
entry (a root→leaf path) is first-class and carries its own flat token sequence
|
||||
(`branch.token_ids` / `branch.sampled_mask` / `branch.logprobs`), so a branch yields one
|
||||
training sample directly. Token-length readers (`completion_len`, `total_tokens`, `num_turns`)
|
||||
live on `vf.Trace` itself.
|
||||
|
||||
Training is renderer-only across every mode (RL/OPD student, SFT teacher), so every node
|
||||
always carries its tokens — no backfill needed. For multimodal rollouts the branch also carries
|
||||
the images it introduced (`branch.multi_modal_data`), rebuilt here into the flat `mm_kwargs` /
|
||||
`mm_token_type_ids` the trainer forwards.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pybase64
|
||||
import torch
|
||||
import verifiers as vf
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.transport import RoutedExperts, TrainingSample
|
||||
from prime_rl.utils.chat_template import (
|
||||
common_prefix_len,
|
||||
deserialize_tool_calls,
|
||||
normalize_messages,
|
||||
render_messages,
|
||||
strip_message_content,
|
||||
)
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.transport.types import EncodedTensor, RoutedExperts
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# We use list() instead of deepcopy() for flat lists (token IDs, logprobs) - safe because
|
||||
# primitives are immutable. mm_kwargs payloads are not mutated after creation.
|
||||
|
||||
def _to_numpy(val) -> np.ndarray:
|
||||
"""A renderer mm item value (torch tensor or numpy array) -> a contiguous numpy array."""
|
||||
if hasattr(val, "detach"): # torch tensor
|
||||
val = val.detach().cpu().numpy()
|
||||
return np.ascontiguousarray(val)
|
||||
|
||||
|
||||
def align_routed_experts(
|
||||
routed_experts: np.ndarray | None,
|
||||
expected_len: int,
|
||||
) -> np.ndarray | None:
|
||||
"""Align routed_experts length with the expected token count.
|
||||
|
||||
VLLM's capturer uses `num_tokens - 1` slot mappings because the final
|
||||
generated token was never fed as input to a forward pass and has no
|
||||
routing decision. Append zero-filled entries for the missing positions.
|
||||
"""
|
||||
if routed_experts is None:
|
||||
return routed_experts
|
||||
assert routed_experts.ndim == 3
|
||||
if routed_experts.shape[0] > expected_len:
|
||||
return np.ascontiguousarray(routed_experts[:expected_len])
|
||||
deficit = expected_len - routed_experts.shape[0]
|
||||
if deficit <= 0:
|
||||
return routed_experts
|
||||
padding = np.zeros((deficit, routed_experts.shape[1], routed_experts.shape[2]), dtype=routed_experts.dtype)
|
||||
return np.concatenate((routed_experts, padding), axis=0)
|
||||
def _encode_mm_kwargs(mm_items: dict[str, list[dict]]) -> dict[str, EncodedTensor] | None:
|
||||
"""Concatenate the branch's per-image renderer items into the flat `mm_kwargs` the trainer
|
||||
forwards — one `EncodedTensor` per kwarg key (e.g. `pixel_values`, `image_grid_thw`), images
|
||||
cat'd along dim 0 in branch token order. Model-agnostic: the keys are whatever the processor
|
||||
emits. Returns None when there are no items."""
|
||||
bins: dict[str, list[np.ndarray]] = {}
|
||||
for items in mm_items.values(): # per modality
|
||||
for item in items: # per image
|
||||
for key, val in item.items():
|
||||
bins.setdefault(key, []).append(_to_numpy(val))
|
||||
encoded: dict[str, EncodedTensor] = {}
|
||||
for key, arrs in bins.items():
|
||||
arr = np.concatenate(arrs, axis=0)
|
||||
encoded[key] = EncodedTensor(dtype=str(arr.dtype), shape=list(arr.shape), data=arr.tobytes())
|
||||
return encoded or None
|
||||
|
||||
|
||||
def _common_prefix_len(a: list[int], b: list[int]) -> int:
|
||||
return common_prefix_len(a, b)
|
||||
|
||||
|
||||
def _normalize_messages(messages: Any, default_role: str) -> list[dict[str, Any]]:
|
||||
return normalize_messages(messages, default_role)
|
||||
|
||||
|
||||
def _deserialize_tool_calls(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return deserialize_tool_calls(messages)
|
||||
|
||||
|
||||
def _strip_message_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return strip_message_content(messages)
|
||||
|
||||
|
||||
def _render_messages(
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
messages: list[dict[str, Any]],
|
||||
add_generation_prompt: bool = False,
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
) -> list[int]:
|
||||
return render_messages(
|
||||
tokenizer,
|
||||
messages,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
|
||||
def _tokenize_step_from_messages(
|
||||
step: vf.TrajectoryStep,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
prompt = _normalize_messages(step.get("prompt"), default_role="user")
|
||||
completion = _normalize_messages(step.get("completion"), default_role="assistant")
|
||||
|
||||
prompt = _strip_message_content(_deserialize_tool_calls(prompt))
|
||||
completion = _strip_message_content(_deserialize_tool_calls(completion))
|
||||
|
||||
assert all(m.get("role") == "assistant" for m in completion), (
|
||||
"Expected all completion messages to be assistant role for SFT distillation, "
|
||||
f"got roles: {[m.get('role') for m in completion]}"
|
||||
)
|
||||
|
||||
all_messages = prompt + completion
|
||||
prompt_has_assistant_completion = len(completion) > 0 and completion[0].get("role") == "assistant"
|
||||
prompt_ids = _render_messages(
|
||||
tokenizer,
|
||||
prompt,
|
||||
add_generation_prompt=prompt_has_assistant_completion,
|
||||
tools=tools,
|
||||
)
|
||||
full_ids = _render_messages(
|
||||
tokenizer,
|
||||
all_messages,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
split_idx = _common_prefix_len(prompt_ids, full_ids)
|
||||
original_prompt_len = len(prompt_ids)
|
||||
|
||||
prompt_ids = full_ids[:split_idx]
|
||||
completion_ids = full_ids[split_idx:]
|
||||
completion_mask = [True] * len(completion_ids)
|
||||
completion_logprobs = [0.0] * len(completion_ids)
|
||||
|
||||
return {
|
||||
"prompt_ids": prompt_ids,
|
||||
"prompt_mask": [False] * len(prompt_ids),
|
||||
"completion_ids": completion_ids,
|
||||
"completion_mask": completion_mask,
|
||||
"completion_logprobs": completion_logprobs,
|
||||
"routed_experts": None,
|
||||
"prompt_prefix_len": split_idx,
|
||||
"original_prompt_len": original_prompt_len,
|
||||
}
|
||||
|
||||
|
||||
def _convert_tools_to_oai_format(tool_defs: list) -> list[dict[str, Any]] | None:
|
||||
"""Convert verifiers Tool objects or dicts to OAI function-calling format."""
|
||||
if not tool_defs:
|
||||
def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExperts | None:
|
||||
"""The branch's router-replay array (`[tokens, layers, top_k]`) -> the transport
|
||||
`RoutedExperts` the trainer replays. Defensively realigns the token axis to `num_tokens`
|
||||
(the trainer asserts `routed_experts.shape[0] == len(token_ids)`): truncate if longer,
|
||||
zero-pad the tail if shorter. `Branch.routed_experts` already guarantees alignment, so this
|
||||
is a backstop."""
|
||||
if arr is None:
|
||||
return None
|
||||
|
||||
def _get(tool: Any, key: str) -> Any:
|
||||
if isinstance(tool, dict):
|
||||
return tool.get(key)
|
||||
return getattr(tool, key, None)
|
||||
|
||||
return [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": _get(tool, "name"),
|
||||
"description": _get(tool, "description"),
|
||||
"parameters": _get(tool, "parameters"),
|
||||
**({} if _get(tool, "strict") is None else {"strict": _get(tool, "strict")}),
|
||||
},
|
||||
}
|
||||
for tool in tool_defs
|
||||
]
|
||||
arr = np.ascontiguousarray(arr)
|
||||
if arr.shape[0] > num_tokens:
|
||||
arr = arr[:num_tokens]
|
||||
elif arr.shape[0] < num_tokens:
|
||||
pad = np.zeros((num_tokens - arr.shape[0], *arr.shape[1:]), dtype=arr.dtype)
|
||||
arr = np.concatenate([arr, pad], axis=0)
|
||||
return RoutedExperts(data=arr.tobytes(), shape=list(arr.shape), dtype=str(arr.dtype))
|
||||
|
||||
|
||||
def _tokenize_step_with_renderer(
|
||||
step: vf.TrajectoryStep,
|
||||
renderer,
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Tokenize a trajectory step using a Renderer."""
|
||||
from renderers.base import build_trajectory_step
|
||||
|
||||
prompt = _normalize_messages(step.get("prompt"), default_role="user")
|
||||
completion = _normalize_messages(step.get("completion"), default_role="assistant")
|
||||
prompt = _strip_message_content(_deserialize_tool_calls(prompt))
|
||||
completion = _strip_message_content(_deserialize_tool_calls(completion))
|
||||
return build_trajectory_step(renderer, prompt, completion, tools=tools)
|
||||
|
||||
|
||||
def backfill_rollout_tokens(
|
||||
output: vf.RolloutOutput,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
renderer=None,
|
||||
) -> bool:
|
||||
"""Populate missing step tokens from prompt/completion messages.
|
||||
|
||||
When a renderer is provided, uses it for tokenization (faster, deterministic).
|
||||
Otherwise falls back to the tokenizer + apply_chat_template path.
|
||||
"""
|
||||
if all(step["tokens"] is not None for step in output["trajectory"]):
|
||||
return True
|
||||
|
||||
logger = get_logger()
|
||||
tools = _convert_tools_to_oai_format(output.get("tool_defs", []))
|
||||
|
||||
for step_idx, step in enumerate(output["trajectory"]):
|
||||
if step["tokens"] is not None:
|
||||
continue
|
||||
|
||||
if renderer is not None:
|
||||
step["tokens"] = _tokenize_step_with_renderer(step, renderer, tools=tools)
|
||||
else:
|
||||
reconstructed = _tokenize_step_from_messages(step, tokenizer, tools=tools)
|
||||
if reconstructed["prompt_prefix_len"] < reconstructed["original_prompt_len"]:
|
||||
logger.debug(
|
||||
f"Prompt tokenization was non-prefix for example {output['example_id']} step {step_idx}. "
|
||||
f"Using longest common prefix length {reconstructed['prompt_prefix_len']} "
|
||||
f"(original prompt had {reconstructed['original_prompt_len']} tokens)."
|
||||
)
|
||||
reconstructed.pop("prompt_prefix_len")
|
||||
reconstructed.pop("original_prompt_len")
|
||||
step["tokens"] = reconstructed
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def interleave_rollout(
|
||||
output: vf.RolloutOutput,
|
||||
mm_token_type_ids_mapping: dict[int, int] | None = None,
|
||||
def trace_to_samples(
|
||||
trace: vf.Trace,
|
||||
*,
|
||||
env_name: str = "",
|
||||
) -> list[TrainingSample] | None:
|
||||
mm_token_type_ids_mapping: dict[int, int] | None = None,
|
||||
) -> list[TrainingSample]:
|
||||
"""Convert a v1 `Trace` into `TrainingSample`s — one per branch.
|
||||
|
||||
Each `trace.branches` entry is already a flat token sequence (`branch.token_ids` /
|
||||
`branch.sampled_mask` / `branch.logprobs`), so a sample carries it directly: `mask` marks
|
||||
the trainable (model-sampled) tokens, the context tokens between completions stay masked
|
||||
out. On a rollout error the whole completion is masked out. A branch carrying images also
|
||||
gets `mm_kwargs` (the concatenated pixel tensors) and `mm_token_type_ids` (the renderer's
|
||||
`mm_token_type_id_map` applied to the branch tokens). Branches with no sampled tokens
|
||||
(e.g. an openai client carrying none) yield nothing.
|
||||
"""
|
||||
Convert vf.RolloutOutput to trainable rollouts by interleaving trajectory steps
|
||||
where the extension property holds.
|
||||
|
||||
When consecutive steps share token prefixes (extension property), they are
|
||||
merged into a single sample. When extension breaks (e.g., due to context
|
||||
compaction or a change in control-flow), a new sample is started.
|
||||
|
||||
Supports multi-prefix matching to handle interleaved agents. For example,
|
||||
[agent1-step1, agent1-step2, agent2-step1, agent1-step3] produces two samples:
|
||||
agent1 steps merged together, agent2 step separate.
|
||||
|
||||
Returns a list of samples - could be 1 (extension always held) or up to T
|
||||
(extension never held).
|
||||
|
||||
For VLM models, each renderer-produced trajectory step carries its
|
||||
per-image processed tensors inline on ``multi_modal_data``; the last
|
||||
merged step's sidecar covers every image in the sample.
|
||||
"""
|
||||
logger = get_logger()
|
||||
|
||||
trajectory = output["trajectory"]
|
||||
if len(trajectory) == 0:
|
||||
error = output.get("error")
|
||||
stop = output.get("stop_condition")
|
||||
logger.warning(
|
||||
f"No trajectory steps for example {output['example_id']} (error={error}, stop={stop}). Skipping rollout."
|
||||
)
|
||||
return None
|
||||
|
||||
has_error = output["error"] is not None
|
||||
|
||||
def prepare_step_tokens(step: vf.TrajectoryStep, step_idx: int) -> dict[str, Any] | None:
|
||||
tokens = step["tokens"]
|
||||
if tokens is not None:
|
||||
routed_experts_payload = tokens.get("routed_experts")
|
||||
routed_experts = None
|
||||
routed_experts_start = None
|
||||
if routed_experts_payload is not None:
|
||||
decoded_routed_experts = pybase64.b64decode_as_bytearray(routed_experts_payload["data"])
|
||||
routed_experts = np.frombuffer(decoded_routed_experts, dtype=np.uint8).reshape(
|
||||
routed_experts_payload["shape"]
|
||||
)
|
||||
routed_experts_start = routed_experts_payload["start"]
|
||||
|
||||
return {
|
||||
"prompt_ids": list(tokens["prompt_ids"]),
|
||||
"prompt_mask": list(map(bool, tokens["prompt_mask"])),
|
||||
"completion_ids": list(tokens["completion_ids"]),
|
||||
"completion_mask": list(map(bool, tokens["completion_mask"])),
|
||||
"completion_logprobs": list(tokens["completion_logprobs"]),
|
||||
"routed_experts": routed_experts,
|
||||
"routed_experts_start": routed_experts_start,
|
||||
# Renderer-emitted multimodal sidecar (placeholders + per-item
|
||||
# processed tensors). Populated when the rollout went through
|
||||
# a multimodal-aware renderer (e.g. Qwen3VLRenderer); absent
|
||||
# for text-only rollouts.
|
||||
"multi_modal_data": tokens.get("multi_modal_data"),
|
||||
}
|
||||
|
||||
logger.warning(f"Missing rollout tokens for example {output['example_id']} step {step_idx}.")
|
||||
return None
|
||||
|
||||
prepared_steps: list[dict[str, Any]] = []
|
||||
for step_idx, step in enumerate(trajectory):
|
||||
prepared = prepare_step_tokens(step, step_idx)
|
||||
if prepared is None:
|
||||
return None
|
||||
prepared_steps.append(prepared)
|
||||
|
||||
# Deferred routed_experts state per sample: O(N) chunk list concatenated
|
||||
# once at finalize, replacing the prior O(N²) per-extension unpack/repack.
|
||||
sample_routed_state: dict[int, dict[str, Any]] = {}
|
||||
routed_prefix_states: dict[int, list[tuple[list[int], list[int], dict[str, Any]]]] = {}
|
||||
|
||||
# Track (prefix_tokens, sample, step_indices) per active sample. step_indices
|
||||
# is the explicit list of prepared_steps positions merged into this sample —
|
||||
# non-contiguous when other agents' steps interleave.
|
||||
active_samples: list[tuple[list[int], TrainingSample, list[int]]] = []
|
||||
|
||||
def make_sample(tokens: dict[str, Any], step_idx: int) -> TrainingSample:
|
||||
"""Create a new TrainingSample from a trajectory step."""
|
||||
if has_error:
|
||||
completion_mask = [False] * len(tokens["completion_mask"])
|
||||
else:
|
||||
completion_mask = list(tokens["completion_mask"])
|
||||
completion_ids = list(tokens["completion_ids"])
|
||||
|
||||
prompt_ids = list(tokens["prompt_ids"])
|
||||
sample = TrainingSample(
|
||||
prompt_ids=prompt_ids,
|
||||
prompt_mask=list(tokens["prompt_mask"]),
|
||||
completion_ids=completion_ids,
|
||||
completion_mask=completion_mask,
|
||||
completion_logprobs=list(tokens["completion_logprobs"]),
|
||||
completion_temperatures=[],
|
||||
teacher_logprobs=None,
|
||||
advantage=None,
|
||||
env_name=env_name,
|
||||
mm_token_type_ids=None,
|
||||
routed_experts=None, # deferred — finalized at end of interleave_rollout
|
||||
)
|
||||
# Initialize routed-experts state for this sample. First chunk is the
|
||||
# raw step routed_experts (no pad, no copy). running_len is the
|
||||
# cumulative count across chunks; tracked so the boundary fix-up at
|
||||
# each extension is a no-op append rather than a destructive write.
|
||||
step_routed = tokens.get("routed_experts")
|
||||
if step_routed is not None:
|
||||
routed_start = tokens["routed_experts_start"]
|
||||
assert routed_start is not None, f"Missing routed_experts_start for step {step_idx}"
|
||||
chunks: list[np.ndarray] = []
|
||||
running_len = 0
|
||||
if routed_start > 0:
|
||||
source_len = routed_start + 1
|
||||
assert source_len in routed_prefix_states, (
|
||||
f"Missing routed prefix state for step {step_idx}: "
|
||||
f"routed_start={routed_start}, prompt_len={len(tokens['prompt_ids'])}"
|
||||
)
|
||||
source_state = None
|
||||
for prompt_ids, completion_ids, candidate_state in routed_prefix_states[source_len]:
|
||||
prompt_len = len(prompt_ids)
|
||||
if (
|
||||
tokens["prompt_ids"][:prompt_len] == prompt_ids
|
||||
and tokens["prompt_ids"][prompt_len:source_len] == completion_ids
|
||||
):
|
||||
source_state = candidate_state
|
||||
break
|
||||
assert source_state is not None, (
|
||||
f"No matching routed prefix for step {step_idx}: "
|
||||
f"routed_start={routed_start}, prompt_len={len(tokens['prompt_ids'])}"
|
||||
)
|
||||
assert source_state["running_len"] >= routed_start, (
|
||||
f"Routed prefix too short for step {step_idx}: "
|
||||
f"running_len={source_state['running_len']}, routed_start={routed_start}"
|
||||
)
|
||||
remaining = routed_start
|
||||
for chunk in source_state["chunks"]:
|
||||
if remaining == 0:
|
||||
break
|
||||
take = min(remaining, int(chunk.shape[0]))
|
||||
chunks.append(chunk[:take])
|
||||
remaining -= take
|
||||
assert remaining == 0, (
|
||||
f"Could not reconstruct routed prefix for step {step_idx}: "
|
||||
f"remaining={remaining}, routed_start={routed_start}"
|
||||
)
|
||||
running_len = routed_start
|
||||
chunks.append(step_routed)
|
||||
running_len += int(step_routed.shape[0])
|
||||
sample_routed_state[id(sample)] = {
|
||||
"chunks": chunks,
|
||||
"running_len": running_len,
|
||||
}
|
||||
return sample
|
||||
|
||||
def extend_sample(
|
||||
sample: TrainingSample,
|
||||
prefix_len: int,
|
||||
step_idx: int,
|
||||
) -> None:
|
||||
"""Extend an existing sample with a new trajectory step (extension property holds)."""
|
||||
tokens = prepared_steps[step_idx]
|
||||
|
||||
# Extend with new prompt tokens (mask=False, no gradient)
|
||||
new_prompt_ids = tokens["prompt_ids"][prefix_len:]
|
||||
sample.completion_ids.extend(new_prompt_ids)
|
||||
sample.completion_mask.extend([False] * len(new_prompt_ids))
|
||||
sample.completion_logprobs.extend([0.0] * len(new_prompt_ids))
|
||||
|
||||
# Extend with new completion tokens
|
||||
completion_ids = tokens["completion_ids"]
|
||||
sample.completion_ids.extend(completion_ids)
|
||||
if has_error:
|
||||
sample.completion_mask.extend([False] * len(tokens["completion_mask"]))
|
||||
else:
|
||||
sample.completion_mask.extend(tokens["completion_mask"])
|
||||
sample.completion_logprobs.extend(tokens["completion_logprobs"])
|
||||
|
||||
step_routed = tokens.get("routed_experts")
|
||||
state = sample_routed_state.get(id(sample))
|
||||
if state is not None:
|
||||
assert step_routed is not None, f"Missing routed experts for routed sample extension at step {step_idx}"
|
||||
if step_routed is not None:
|
||||
assert state is not None, f"Unexpected routed experts for unrouted sample at step {step_idx}"
|
||||
assert tokens["routed_experts_start"] == prefix_len - 1, (
|
||||
f"Routed experts delta start mismatch at step {step_idx}: "
|
||||
f"start={tokens['routed_experts_start']}, expected={prefix_len - 1}, prefix_len={prefix_len}"
|
||||
)
|
||||
# Delta payloads start at prefix_len - 1. Row 0 fills the boundary
|
||||
# token missing from the previous request; the rest is the new suffix.
|
||||
if prefix_len > 0:
|
||||
boundary_chunk = step_routed[:1]
|
||||
state["chunks"].append(boundary_chunk)
|
||||
state["running_len"] += 1
|
||||
step_routed = step_routed[1:]
|
||||
new_chunk = step_routed
|
||||
state["chunks"].append(new_chunk)
|
||||
state["running_len"] += int(new_chunk.shape[0])
|
||||
|
||||
first_tokens = prepared_steps[0]
|
||||
first_prefix = first_tokens["prompt_ids"] + first_tokens["completion_ids"]
|
||||
first_sample = make_sample(first_tokens, step_idx=0)
|
||||
active_samples.append((first_prefix, first_sample, [0]))
|
||||
first_routed_state = sample_routed_state.get(id(first_sample))
|
||||
if first_routed_state is not None:
|
||||
routed_prefix_states.setdefault(len(first_prefix), []).append(
|
||||
(first_tokens["prompt_ids"], first_tokens["completion_ids"], first_routed_state)
|
||||
)
|
||||
|
||||
for step_idx, _step in enumerate(trajectory[1:], start=1):
|
||||
tokens = prepared_steps[step_idx]
|
||||
step_prompt_ids = tokens["prompt_ids"]
|
||||
|
||||
# Pick the *longest* matching active prefix. With compaction/rollback,
|
||||
# one active sample's prefix can be a strict prefix of another (e.g. a
|
||||
# later sample re-generated tokens that overlap an earlier sample's
|
||||
# prefix). Both would satisfy the slice check; the shorter would
|
||||
# silently absorb the longer sample's generated tokens as user input.
|
||||
matched_idx = None
|
||||
matched_len = -1
|
||||
matching_prefix_lens: list[int] = []
|
||||
for idx, (prefix_tokens, _, _) in enumerate(active_samples):
|
||||
pl = len(prefix_tokens)
|
||||
if step_prompt_ids[:pl] == prefix_tokens:
|
||||
matching_prefix_lens.append(pl)
|
||||
if pl > matched_len:
|
||||
matched_idx = idx
|
||||
matched_len = pl
|
||||
|
||||
if len(matching_prefix_lens) > 1:
|
||||
# Ambiguous extension: rare, but reachable via compaction/rollback
|
||||
# where a new sample's prefix happens to start with an older
|
||||
# sample's prefix. Longest-match is the correct choice; surface
|
||||
# the ambiguity so we can audit if it shows up in real rollouts.
|
||||
logger.warning(
|
||||
f"Ambiguous prefix match at step {step_idx} for example {output['example_id']}: "
|
||||
f"{len(matching_prefix_lens)} of {len(active_samples)} active prefixes match "
|
||||
f"(lens={sorted(matching_prefix_lens)}, step_prompt_len={len(step_prompt_ids)}). "
|
||||
f"Extending the longest (len={matched_len})."
|
||||
)
|
||||
|
||||
if matched_idx is not None:
|
||||
# Extension holds - merge into matched sample
|
||||
prefix_tokens, sample, step_indices = active_samples[matched_idx]
|
||||
extend_sample(sample, len(prefix_tokens), step_idx=step_idx)
|
||||
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
|
||||
active_samples[matched_idx] = (
|
||||
new_prefix,
|
||||
sample,
|
||||
step_indices + [step_idx],
|
||||
)
|
||||
routed_state = sample_routed_state.get(id(sample))
|
||||
if routed_state is not None:
|
||||
routed_prefix_states.setdefault(len(new_prefix), []).append(
|
||||
(tokens["prompt_ids"], tokens["completion_ids"], routed_state)
|
||||
)
|
||||
else:
|
||||
# No prefix matches - start a new sample
|
||||
logger.debug(
|
||||
f"Extension property broke at step {step_idx + 1} for example {output['example_id']}. "
|
||||
f"Starting new sample (active_prefixes={len(active_samples)}, step_prompt_len={len(step_prompt_ids)})."
|
||||
)
|
||||
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
|
||||
sample = make_sample(tokens, step_idx=step_idx)
|
||||
active_samples.append((new_prefix, sample, [step_idx]))
|
||||
routed_state = sample_routed_state.get(id(sample))
|
||||
if routed_state is not None:
|
||||
routed_prefix_states.setdefault(len(new_prefix), []).append(
|
||||
(tokens["prompt_ids"], tokens["completion_ids"], routed_state)
|
||||
)
|
||||
|
||||
# Finalize routed_experts for each sample. One concat per sample (O(N) byte
|
||||
# work) replaces the previous per-step unpack/concat/repack (O(N²)). The
|
||||
# boundary entries between steps were already inserted as one-entry chunks
|
||||
# during extend_sample, so a straight concat is correct.
|
||||
for _, sample, _ in active_samples:
|
||||
state = sample_routed_state.get(id(sample))
|
||||
if state is None:
|
||||
has_error = trace.has_error
|
||||
samples: list[TrainingSample] = []
|
||||
for branch in trace.branches:
|
||||
mask = branch.sampled_mask
|
||||
if not any(mask):
|
||||
continue
|
||||
chunks = state["chunks"]
|
||||
if not chunks:
|
||||
continue
|
||||
combined = np.concatenate(chunks, axis=0) if len(chunks) > 1 else np.ascontiguousarray(chunks[0])
|
||||
expected_len = len(sample.prompt_ids) + len(sample.completion_ids)
|
||||
combined = align_routed_experts(combined, expected_len)
|
||||
combined = np.ascontiguousarray(combined)
|
||||
sample.routed_experts = RoutedExperts(
|
||||
data=combined.tobytes(),
|
||||
shape=list(combined.shape),
|
||||
dtype=str(combined.dtype),
|
||||
token_ids = branch.token_ids
|
||||
mm_kwargs: dict[str, EncodedTensor] | None = None
|
||||
mm_token_type_ids: list[int] | None = None
|
||||
mmd = branch.multi_modal_data
|
||||
if mmd is not None:
|
||||
mm_kwargs = _encode_mm_kwargs(mmd.mm_items)
|
||||
mapping = mm_token_type_ids_mapping or {}
|
||||
mm_token_type_ids = [mapping.get(t, 0) for t in token_ids]
|
||||
samples.append(
|
||||
TrainingSample(
|
||||
token_ids=token_ids,
|
||||
mask=[m and not has_error for m in mask],
|
||||
logprobs=branch.logprobs,
|
||||
temperatures=[], # filled by TrainSink.process_group
|
||||
teacher_logprobs=None,
|
||||
advantage=None,
|
||||
env_name=env_name,
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
routed_experts=_encode_routed_experts(branch.routed_experts, len(token_ids)),
|
||||
)
|
||||
)
|
||||
|
||||
# Attach images by concatenating mm_items across every step the
|
||||
# sample covers. verifiers' ``state_to_output`` ships per-step
|
||||
# *delta* mm_data (each step contains only items not present in the
|
||||
# prior step's cumulative set, with multiset-aware dedup), so
|
||||
# reading the last step alone would miss every earlier-turn image.
|
||||
# Concat in step order recovers the per-sample cumulative set;
|
||||
# deduping again here would drop legitimate duplicate placeholders.
|
||||
for _, sample, step_indices in active_samples:
|
||||
renderer_mm = _union_step_mm_data(prepared_steps, step_indices)
|
||||
if renderer_mm is not None:
|
||||
mm_kwargs = _pack_mm_kwargs_from_renderer(renderer_mm)
|
||||
if mm_kwargs is not None:
|
||||
sample.mm_kwargs = mm_kwargs
|
||||
# ``mm_token_type_ids``: 1 for image-placeholder tokens, 2
|
||||
# for video, 0 otherwise. Renderer-supplied via
|
||||
# ``mm_token_type_id_map`` (single source of truth).
|
||||
if mm_token_type_ids_mapping is not None:
|
||||
sample.mm_token_type_ids = [
|
||||
mm_token_type_ids_mapping.get(token_id, 0)
|
||||
for token_id in sample.prompt_ids + sample.completion_ids
|
||||
]
|
||||
|
||||
return [sample for _, sample, _ in active_samples]
|
||||
|
||||
|
||||
def _union_step_mm_data(
|
||||
prepared_steps: list[dict[str, Any]],
|
||||
step_indices: list[int],
|
||||
) -> "dict[str, Any] | None":
|
||||
"""Concatenate renderer-emitted mm_items across this sample's owned steps.
|
||||
|
||||
``step_indices`` lists exactly the ``prepared_steps`` positions merged into
|
||||
the sample — explicit, not a range, so interleaved-agent trajectories skip
|
||||
steps owned by other agents.
|
||||
|
||||
Verifiers ≥ c7731bbb ships per-step *delta* mm_data instead of
|
||||
cumulative — see ``verifiers/utils/save_utils.py::_delta_intermediate_mm_data``.
|
||||
The cross-step dedup is already done there with multiset semantics
|
||||
(preserving multiplicity for an image that appears in multiple
|
||||
placeholder runs in the token stream). We just concatenate in step
|
||||
order to recover the per-sample cumulative; deduping again here
|
||||
would drop legitimate duplicate placeholders.
|
||||
"""
|
||||
union_items: dict[str, list] = {}
|
||||
union_hashes: dict[str, list] = {}
|
||||
has_any = False
|
||||
for i in step_indices:
|
||||
mm = prepared_steps[i].get("multi_modal_data")
|
||||
if mm is None:
|
||||
continue
|
||||
items = mm.mm_items if hasattr(mm, "mm_items") else (mm or {}).get("mm_items") or {}
|
||||
hashes = mm.mm_hashes if hasattr(mm, "mm_hashes") else (mm or {}).get("mm_hashes") or {}
|
||||
for modality, item_lst in items.items():
|
||||
hash_lst = hashes.get(modality, []) or []
|
||||
for j, item in enumerate(item_lst or []):
|
||||
h = hash_lst[j] if j < len(hash_lst) else None
|
||||
union_items.setdefault(modality, []).append(item)
|
||||
union_hashes.setdefault(modality, []).append(h)
|
||||
has_any = True
|
||||
if not has_any:
|
||||
return None
|
||||
return {"mm_items": union_items, "mm_hashes": union_hashes}
|
||||
|
||||
|
||||
def _pack_mm_kwargs_from_renderer(mm_data: Any) -> "dict[str, Any] | None":
|
||||
"""Batch the renderer's per-image ``mm_items`` into model-agnostic
|
||||
forward kwargs.
|
||||
|
||||
``mm_data`` may arrive as a ``MultiModalData`` instance (in-process
|
||||
for tests) or as a plain dict (after msgpack round-trip from the
|
||||
env-worker). Each item is a dict keyed by the names the model's
|
||||
``forward`` expects (``pixel_values`` + ``image_grid_thw`` for
|
||||
Qwen3-VL, just ``pixel_values`` for Gemma3-VL, etc.). We batch by
|
||||
``torch.cat(..., dim=0)`` per key — generic because every HF VLM
|
||||
processor emits a leading batch/patch dimension, and the renderer
|
||||
always processes one image per call.
|
||||
|
||||
Returns a dict of ``EncodedTensor`` payloads keyed by kwarg name,
|
||||
or ``None`` when no multimodal data is present.
|
||||
"""
|
||||
from verifiers.utils.serve_utils import decode_tensor_payload
|
||||
|
||||
from prime_rl.transport.types import EncodedTensor
|
||||
|
||||
mm_items = mm_data.mm_items if hasattr(mm_data, "mm_items") else (mm_data or {}).get("mm_items") or {}
|
||||
# Flatten across modalities into one kwarg dict — the model's
|
||||
# forward signature is the schema. ``mm_items`` is typically
|
||||
# ``{"image": [...], "video": [...]}`` but each modality's keys
|
||||
# don't collide for any HF VLM we ship today.
|
||||
per_kwarg: dict[str, list] = {}
|
||||
for _modality, items in mm_items.items():
|
||||
for item in items or []:
|
||||
for key, payload in item.items():
|
||||
per_kwarg.setdefault(key, []).append(decode_tensor_payload(payload))
|
||||
if not per_kwarg:
|
||||
return None
|
||||
out: dict[str, EncodedTensor] = {}
|
||||
for key, tensors in per_kwarg.items():
|
||||
cat = torch.cat(tensors, dim=0).contiguous()
|
||||
arr = cat.detach().cpu().numpy()
|
||||
out[key] = EncodedTensor(
|
||||
dtype=str(arr.dtype),
|
||||
shape=list(arr.shape),
|
||||
data=arr.tobytes(),
|
||||
if not samples:
|
||||
get_logger().warning(
|
||||
f"No trainable samples (error={has_error}, stop={trace.stop_condition}, num_turns={trace.num_turns})."
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
_FILE_URL_PREFIX = "file://"
|
||||
|
||||
|
||||
def offload_images_to_disk(rollouts: list[vf.RolloutOutput], output_dir: Path) -> int:
|
||||
"""Replace base64 image data in rollout trajectories with file paths on disk.
|
||||
|
||||
Scans all trajectory step prompts for data:image URLs, writes the decoded
|
||||
image bytes to ``{output_dir}/assets/images/{hash}.png``, and replaces the
|
||||
URL in-place with ``file://{path}``. Deduplicates by content hash so each
|
||||
unique image is written only once.
|
||||
|
||||
Returns the number of unique images written to disk.
|
||||
"""
|
||||
images_dir = output_dir / "assets" / "images"
|
||||
images_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
written: set[str] = set()
|
||||
|
||||
for output in rollouts:
|
||||
for step in output.get("trajectory", []):
|
||||
prompt = step.get("prompt")
|
||||
if not prompt or not isinstance(prompt, list):
|
||||
continue
|
||||
for msg in prompt:
|
||||
content = msg.get("content", [])
|
||||
if not isinstance(content, list):
|
||||
continue
|
||||
for item in content:
|
||||
if item.get("type") != "image_url":
|
||||
continue
|
||||
url = item.get("image_url", {}).get("url", "")
|
||||
if not url.startswith("data:image"):
|
||||
continue
|
||||
b64_data = url.split(",", 1)[1]
|
||||
content_hash = hashlib.sha256(b64_data.encode()).hexdigest()[:16]
|
||||
path = images_dir / f"{content_hash}.png"
|
||||
if content_hash not in written:
|
||||
if not path.exists():
|
||||
path.write_bytes(base64.b64decode(b64_data))
|
||||
written.add(content_hash)
|
||||
item["image_url"]["url"] = f"{_FILE_URL_PREFIX}{path}"
|
||||
|
||||
return len(written)
|
||||
return samples
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from dataclasses import dataclass, field, fields
|
||||
from typing import Literal, Protocol
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Generic, Literal, Protocol
|
||||
|
||||
import verifiers as vf
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import ConfigDict, Field
|
||||
from verifiers.v1.task import TaskT
|
||||
|
||||
from prime_rl.transport import TrainingSample
|
||||
|
||||
@@ -55,7 +57,7 @@ class GroupState:
|
||||
|
||||
kind: RolloutKind
|
||||
env_name: str
|
||||
example: dict
|
||||
task_idx: int
|
||||
rollouts_to_schedule: int
|
||||
target_rollouts: int
|
||||
emitted: int = 0
|
||||
@@ -64,60 +66,25 @@ class GroupState:
|
||||
policy_version_at_start: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class FinishedRollout:
|
||||
"""A completed rollout the sink receives. ``raw`` is the env's untouched
|
||||
``vf.RolloutOutput``; prime-rl metadata lives on typed fields. Train vs
|
||||
eval is discriminated via ``isinstance``. ``rollout_id`` is the only
|
||||
safe key for tracing one rollout — ``(env_name, example_id)`` collides
|
||||
on re-sampling and ``group_id`` covers a whole group."""
|
||||
class Rollout(vf.Trace[TaskT], Generic[TaskT]):
|
||||
"""A completed rollout: the env's typed ``vf.Trace`` *is* the rollout — prime-rl's
|
||||
orchestration metadata lives on it directly (set by the dispatcher once the rollout
|
||||
returns), so there's no wrapper. Train vs eval is the ``kind`` discriminator. All metadata
|
||||
fields are ``exclude=True``, so dumping a Rollout yields a plain trace — the on-disk
|
||||
``results.jsonl`` is unchanged."""
|
||||
|
||||
raw: vf.RolloutOutput
|
||||
env_name: str
|
||||
example_id: int | str
|
||||
group_id: uuid.UUID
|
||||
policy_version: int
|
||||
off_policy_steps: int
|
||||
rollout_id: uuid.UUID = field(default_factory=uuid.uuid4)
|
||||
model_config = ConfigDict(arbitrary_types_allowed=True) # ``samples`` holds msgspec structs
|
||||
|
||||
@property
|
||||
def error(self) -> dict | None:
|
||||
return self.raw.get("error")
|
||||
|
||||
@property
|
||||
def reward(self) -> float:
|
||||
return float(self.raw.get("reward", 0.0))
|
||||
|
||||
@property
|
||||
def is_truncated(self) -> bool:
|
||||
return bool(self.raw.get("is_truncated", False))
|
||||
|
||||
def to_dict(self) -> vf.RolloutOutput:
|
||||
"""``raw`` + metadata merged for I/O (``save_rollouts``,
|
||||
``monitor.log_samples``). Shallow copy; never mutates ``self.raw``."""
|
||||
out: vf.RolloutOutput = dict(self.raw) # type: ignore[assignment]
|
||||
for f in fields(self):
|
||||
if f.name in ("raw", "samples"):
|
||||
continue
|
||||
val = getattr(self, f.name)
|
||||
if f.name == "filter_results":
|
||||
out["filters"] = dict(val)
|
||||
continue
|
||||
out[f.name] = str(val) if isinstance(val, uuid.UUID) else val
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class TrainRollout(FinishedRollout):
|
||||
samples: list[TrainingSample] = field(default_factory=list)
|
||||
advantage: float | None = None
|
||||
is_filtered: bool = False
|
||||
filter_results: dict[str, bool] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class EvalRollout(FinishedRollout):
|
||||
eval_step: int = 0
|
||||
kind: RolloutKind = Field(default="train", exclude=True)
|
||||
env_name: str = Field(default="", exclude=True)
|
||||
group_id: uuid.UUID = Field(default_factory=uuid.uuid4, exclude=True)
|
||||
policy_version: int = Field(default=0, exclude=True)
|
||||
off_policy_steps: int = Field(default=0, exclude=True)
|
||||
samples: list[TrainingSample] = Field(default_factory=list, exclude=True)
|
||||
advantage: float | None = Field(default=None, exclude=True)
|
||||
is_filtered: bool = Field(default=False, exclude=True)
|
||||
filter_results: dict[str, bool] = Field(default_factory=dict, exclude=True)
|
||||
eval_step: int | None = Field(default=None, exclude=True)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -142,7 +109,7 @@ class TrainBatch:
|
||||
"""``samples`` is the trainer-bound payload (post-filter survivors);
|
||||
``rollouts`` is the full cohort kept for orchestrator-side I/O."""
|
||||
|
||||
rollouts: list[TrainRollout]
|
||||
rollouts: list[Rollout]
|
||||
samples: list[TrainingSample]
|
||||
metrics: TrainBatchMetrics
|
||||
|
||||
@@ -197,12 +164,17 @@ class EvalBatch:
|
||||
|
||||
env_name: str
|
||||
step: int
|
||||
rollouts: list[EvalRollout]
|
||||
rollouts: list[Rollout]
|
||||
metrics: EvalBatchMetrics
|
||||
|
||||
|
||||
class VersionObserver(Protocol):
|
||||
"""Notified after each policy update; walked by the watcher after it
|
||||
mutates ``Policy``."""
|
||||
"""Notified around each policy update; walked by the watcher.
|
||||
|
||||
``on_version_pending`` fires *before* the inference engines are paused for
|
||||
the weight update; ``on_new_version`` fires *after* the new weights are live
|
||||
and ``Policy`` has been mutated."""
|
||||
|
||||
async def on_version_pending(self, step: int) -> None: ...
|
||||
|
||||
async def on_new_version(self, step: int) -> None: ...
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
import asyncio
|
||||
import ctypes
|
||||
import gc
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from itertools import cycle
|
||||
from pathlib import Path
|
||||
|
||||
import orjson
|
||||
import verifiers as vf
|
||||
from verifiers.utils.client_utils import setup_openai_client
|
||||
from verifiers.utils.save_utils import make_serializable
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.utils.client import setup_inference_pool
|
||||
from prime_rl.utils.logger import InterceptHandler, get_logger
|
||||
from prime_rl.utils.logger import InterceptHandler, get_logger, setup_logger
|
||||
from prime_rl.utils.utils import (
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
@@ -22,63 +23,38 @@ from prime_rl.utils.utils import (
|
||||
|
||||
|
||||
async def setup_student_inference_pool(*, config: OrchestratorConfig, tokenizer):
|
||||
"""Build the student inference pool + matching renderer. Returns
|
||||
``(renderer | None, inference_pool)``; ``renderer`` is ``None`` on the
|
||||
MITO path (``config.renderer is None``)."""
|
||||
"""Build the student renderer and inference pool, returning ``(renderer, inference_pool)``.
|
||||
|
||||
Training is renderer-only: RL/OPD roll out through the env server's renderer client
|
||||
(token-in/out), and SFT — which rolls out against a chat-completions teacher that returns
|
||||
no tokens — re-renders the conversation with this renderer to backfill them. The renderer
|
||||
is built here from the (always-set) ``config.renderer`` and also supplies the multimodal
|
||||
token-type-id map. The eval client is plain chat-completions (eval traces aren't trained)."""
|
||||
from renderers.base import create_renderer
|
||||
|
||||
client_config = config.student.client
|
||||
model_name = config.student.model.name
|
||||
|
||||
if config.renderer is not None:
|
||||
renderer = create_renderer(tokenizer, config.renderer)
|
||||
get_logger().info(f"Initialized {type(renderer).__name__} for {model_name}")
|
||||
inference_pool = await setup_inference_pool(
|
||||
client_config,
|
||||
model_name=model_name,
|
||||
train_client_type="renderer",
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_config=config.renderer,
|
||||
pool_size=config.pool_size,
|
||||
)
|
||||
get_logger().info("Using direct renderer rollout client")
|
||||
return renderer, inference_pool
|
||||
|
||||
get_logger().info("Using MITO (openai_chat_completions) for rollouts")
|
||||
renderer = create_renderer(tokenizer, config.renderer)
|
||||
get_logger().info("Using renderer rollout client")
|
||||
inference_pool = await setup_inference_pool(
|
||||
client_config,
|
||||
model_name=model_name,
|
||||
train_client_type="openai_chat_completions",
|
||||
train_client_type="renderer",
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_config=config.renderer,
|
||||
pool_size=config.pool_size,
|
||||
)
|
||||
return None, inference_pool
|
||||
return renderer, inference_pool
|
||||
|
||||
|
||||
def get_model_completion_len(output: vf.RolloutOutput) -> int:
|
||||
"""Sum of model-generated completion tokens across all turns (excludes
|
||||
environment-injected tokens between turns)."""
|
||||
return sum(len(step["tokens"]["completion_ids"]) for step in output["trajectory"] if step.get("tokens"))
|
||||
|
||||
|
||||
def get_tool_response_len(output: vf.RolloutOutput) -> int:
|
||||
"""Total tool-response tokens consumed across the whole rollout, read from a
|
||||
harness-emitted metric (e.g. RLM's `rlm_total_tool_response_tokens`, deduped
|
||||
across turns/branches/sub-RLMs). Returns 0 when no such metric is present."""
|
||||
metrics = output.get("metrics") or {}
|
||||
for key, value in metrics.items():
|
||||
if key.endswith("total_tool_response_tokens") and isinstance(value, (int, float)):
|
||||
return int(value)
|
||||
return 0
|
||||
|
||||
|
||||
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path, exclude_keys: set[str] | None = None) -> None:
|
||||
"""Save rollouts to a JSONL file using verifiers serialization."""
|
||||
def save_rollouts(rollouts: list[dict], path: Path, exclude_keys: set[str] | None = None) -> None:
|
||||
"""Save rollouts (Trace dicts, already JSON-serializable) to a JSONL file."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
|
||||
with open(path, "wb") as f:
|
||||
for rollout in rollouts:
|
||||
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
|
||||
f.write(orjson.dumps(row, default=make_serializable, option=opts))
|
||||
f.write(orjson.dumps(row, default=str, option=opts))
|
||||
|
||||
|
||||
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
|
||||
@@ -90,12 +66,30 @@ def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix
|
||||
vf_logger.propagate = False
|
||||
|
||||
|
||||
def setup_env_server_logging(log_level: str, json_logging: bool = False) -> None:
|
||||
"""Configure logging for an env-server process: prime-rl's logger + routing v1's stdlib
|
||||
logs through it. Passed to verifiers' ``serve_env`` so it runs in the broker and in every
|
||||
spawned worker — fresh ``spawn`` processes that otherwise have no handlers and would drop
|
||||
their per-rollout logs."""
|
||||
setup_logger(log_level, json_logging=json_logging)
|
||||
intercept_vf_logging(logger="verifiers.v1", level=log_level)
|
||||
|
||||
|
||||
def set_default_executor(max_workers: int = 64) -> None:
|
||||
"""Scale the default asyncio thread pool so asyncio.to_thread has enough capacity."""
|
||||
get_logger().info(f"Setting default executor to ThreadPoolExecutor(max_workers={max_workers})")
|
||||
asyncio.get_event_loop().set_default_executor(ThreadPoolExecutor(max_workers=max_workers))
|
||||
|
||||
|
||||
def trim_process_memory() -> None:
|
||||
"""Return freed heap pages to the OS on glibc systems."""
|
||||
gc.collect()
|
||||
try:
|
||||
ctypes.CDLL("libc.so.6").malloc_trim(0)
|
||||
except Exception as exc:
|
||||
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
|
||||
|
||||
|
||||
async def compute_teacher_logprobs(
|
||||
clients: list[vf.ClientConfig],
|
||||
model_name: str,
|
||||
@@ -103,10 +97,15 @@ async def compute_teacher_logprobs(
|
||||
) -> list[list[float]]:
|
||||
"""Compute teacher model logprobs for a batch of training samples via prefill."""
|
||||
import httpx
|
||||
from openai import AsyncOpenAI
|
||||
from vllm.entrypoints.serve.disagg.protocol import GenerateResponse
|
||||
|
||||
async def _compute_single(client_config: vf.ClientConfig, sample: TrainingSample) -> list[float]:
|
||||
client = setup_openai_client(client_config)
|
||||
client = AsyncOpenAI(
|
||||
base_url=client_config.base_url,
|
||||
api_key=os.environ.get(client_config.api_key_var, "EMPTY"),
|
||||
default_headers=client_config.headers or None,
|
||||
)
|
||||
|
||||
# Two escape hatches from ``AsyncOpenAI.post``:
|
||||
# 1. URL — ``/inference/v1/generate`` is mounted at server root, not
|
||||
@@ -125,7 +124,7 @@ async def compute_teacher_logprobs(
|
||||
cast_to=httpx.Response,
|
||||
body={
|
||||
"model": model_name,
|
||||
"token_ids": list(sample.prompt_ids) + list(sample.completion_ids),
|
||||
"token_ids": list(sample.token_ids),
|
||||
"sampling_params": {
|
||||
"max_tokens": 1,
|
||||
"temperature": 1.0,
|
||||
|
||||
@@ -92,6 +92,24 @@ class WeightWatcher:
|
||||
f"Orchestrator resumed: checkpoint {next_step} ready (after {format_time(self.last_wait_for_ckpt_time)})"
|
||||
)
|
||||
|
||||
# Drain off-policy rollouts BEFORE pausing the inference engines.
|
||||
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
|
||||
# ``_reqs_not_processed``), which is only propagated to the workers
|
||||
# while the engine is stepping. If we drain after resume instead,
|
||||
# the aborts race with the flush of KV transfers that completed
|
||||
# during the pause and trip ``assert req_id in self.requests`` in
|
||||
# the decode scheduler's ``_update_from_kv_xfer_finished`` — killing
|
||||
# the engine and cascading to every DP rank. Draining first lets the
|
||||
# aborts settle under normal stepping. ``on_new_version`` (below)
|
||||
# still runs post-update for observers that need the live version.
|
||||
for observer in self.observers:
|
||||
try:
|
||||
await observer.on_version_pending(next_step)
|
||||
except Exception as exc:
|
||||
get_logger().warning(
|
||||
f"Observer {type(observer).__name__}.on_version_pending({next_step}) raised: {exc!r}"
|
||||
)
|
||||
|
||||
get_logger().debug(f"Updating weights to step {next_step}")
|
||||
t1 = time.perf_counter()
|
||||
await self.inference.update_weights(weights_path, lora_name=self.lora_name, step=next_step)
|
||||
|
||||
@@ -15,14 +15,20 @@ rank_log() {
|
||||
# launch_inference_rank <port> <cuda_visible_devices> <dp> <rpc_port> <vllm_extra_json|""> <nixl_side_channel_port|""> <log_file>
|
||||
launch_inference_rank() {
|
||||
local port="$1" gpus="$2" dp="$3" rpc="$4" extra="$5" nixl="$6" log="$7"
|
||||
# Per-rank dir for the mooncake-store lookup ipc socket. It must be unique per process:
|
||||
# external-LB runs one engine per process, all with data_parallel_rank_local 0, so the
|
||||
# lookup socket name collides on bind if the dir is shared node-wide. $port is unique per
|
||||
# rank on the node. Node-local /tmp also avoids inheriting an absent submit-node TMPDIR.
|
||||
local rpcbase="/tmp/vllm-rpc-$USER-$SLURM_JOB_ID-$port"
|
||||
mkdir -p "$rpcbase"
|
||||
local -a cmd=(uv run inference @ "$CONFIG_PATH"
|
||||
--server.host 0.0.0.0 --server.port "$port"
|
||||
--parallel.dp "$dp" --data-parallel-size-local 1 --api-server-count 1)
|
||||
[ -n "$rpc" ] && cmd+=(--data-parallel-rpc-port "$rpc")
|
||||
[ -n "$extra" ] && cmd+=(--vllm-extra "$extra")
|
||||
if [ -n "$nixl" ]; then
|
||||
CUDA_VISIBLE_DEVICES="$gpus" VLLM_NIXL_SIDE_CHANNEL_PORT="$nixl" "${cmd[@]}" 2>&1 | tee -a "$log" &
|
||||
CUDA_VISIBLE_DEVICES="$gpus" VLLM_NIXL_SIDE_CHANNEL_PORT="$nixl" VLLM_RPC_BASE_PATH="$rpcbase" "${cmd[@]}" 2>&1 | tee -a "$log" &
|
||||
else
|
||||
CUDA_VISIBLE_DEVICES="$gpus" "${cmd[@]}" 2>&1 | tee -a "$log" &
|
||||
CUDA_VISIBLE_DEVICES="$gpus" VLLM_RPC_BASE_PATH="$rpcbase" "${cmd[@]}" 2>&1 | tee -a "$log" &
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -1,12 +1,63 @@
|
||||
{# Shared router launch helper, included once per template and called by the
|
||||
replica-head rank. vllm-router today; an llm-d (EPP+Envoy) branch can slot in
|
||||
here so the call sites stay router-agnostic. #}
|
||||
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log_file> [replica_idx]
|
||||
replica-head rank. The router backend (vllm-router vs llm-d EPP+Envoy) is
|
||||
chosen here via router.type, so the call sites stay router-agnostic.
|
||||
node_base/node_count locate this replica's nodes in HOSTNAMES for llm-d
|
||||
endpoint discovery (disagg uses NUM_PREFILL_NODES/NUM_DECODE_NODES). #}
|
||||
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log> <replica_idx> <node_base> [node_count]
|
||||
launch_router() {
|
||||
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-}"
|
||||
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-0}" node_base="${7:-0}" node_count="${8:-0}"
|
||||
{%- if router.type == "llm-d" %}
|
||||
echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port for replica $replica" | tee "$log"
|
||||
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
|
||||
local LLMD_DIR="$OUTPUT_DIR/logs/inference/llmd_${replica}"
|
||||
mkdir -p "$LLMD_DIR"
|
||||
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
|
||||
{%- if is_disaggregated %}
|
||||
{%- set ep_disaggregated = true %}
|
||||
{%- set ep_num_prefill = num_prefill_nodes %}
|
||||
{%- set ep_num_decode = num_decode_nodes %}
|
||||
{%- set ep_dp = dp_per_node %}
|
||||
{%- set ep_prefill_port = prefill_port %}
|
||||
{%- set ep_sidecar_port = router.decode_sidecar_port %}
|
||||
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
|
||||
{% include 'llmd/epp_pd.yaml.j2' %}
|
||||
LLMD_EOF
|
||||
cat > "$LLMD_DIR/endpoints.yaml" <<LLMD_EOF
|
||||
{% include 'llmd/endpoints.yaml.j2' %}
|
||||
LLMD_EOF
|
||||
local node=0 ip
|
||||
for ((p=0; p<NUM_PREFILL_NODES; p++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + p))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
|
||||
for ((d=0; d<NUM_DECODE_NODES; d++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + NUM_PREFILL_NODES + d))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
|
||||
{%- else %}
|
||||
{%- set ep_disaggregated = false %}
|
||||
{%- set ep_num_nodes = infer_nodes_per_replica %}
|
||||
{%- set ep_dp = dp_per_node %}
|
||||
{%- set ep_backend_port = backend_port %}
|
||||
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
|
||||
{% include 'llmd/epp_estimate.yaml.j2' %}
|
||||
LLMD_EOF
|
||||
cat > "$LLMD_DIR/endpoints.yaml" <<LLMD_EOF
|
||||
{% include 'llmd/endpoints.yaml.j2' %}
|
||||
LLMD_EOF
|
||||
local ip
|
||||
for ((n=0; n<node_count; n++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + n))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${n}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; done
|
||||
{%- endif %}
|
||||
cat > "$LLMD_DIR/envoy.yaml" <<LLMD_EOF
|
||||
{% include 'llmd/envoy.yaml.j2' %}
|
||||
LLMD_EOF
|
||||
# grpc-health-port avoids 9003: mooncake_master runs its metrics server on 9003 and
|
||||
# shares the replica-head node with the EPP, so 9003 would fail to bind and kill the EPP.
|
||||
epp --pool-name prime-rl --pool-namespace slurm \
|
||||
--config-file "$LLMD_DIR/epp.yaml" \
|
||||
--grpc-port 9002 --grpc-health-port 9013 --metrics-port 9090 \
|
||||
--secure-serving=false --metrics-endpoint-auth=false --tracing=false \
|
||||
>> "$log" 2>&1 &
|
||||
envoy -c "$LLMD_DIR/envoy.yaml" >> "$log" 2>&1 &
|
||||
{%- else %}
|
||||
local tag="vllm-router"; [ "$mode" = pd ] && tag="vllm-router (PD)"
|
||||
echo "Starting $tag on $LOCAL_IP:$port${replica:+ for replica $replica}" | tee "$log"
|
||||
local -a cmd=(vllm-router --policy "$policy" --host 0.0.0.0 --port "$port"
|
||||
--request-id-headers x-session-id
|
||||
--worker-startup-timeout-secs 4200 --log-level debug)
|
||||
if [ "$mode" = pd ]; then
|
||||
cmd+=(--vllm-pd-disaggregation $worker_args)
|
||||
@@ -14,4 +65,5 @@ launch_router() {
|
||||
cmd+=(--worker-urls $worker_args)
|
||||
fi
|
||||
"${cmd[@]}" >> "$log" 2>&1 &
|
||||
{%- endif %}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
SLURM templates inside the per-node `bash -c` body, so NO single quotes / apostrophes.
|
||||
Requires shell vars: LOCAL_IP, INFER_NODE_RANK, OUTPUT_DIR (and SLURM env).
|
||||
Requires jinja vars: kv_offload_cpu_bytes, kv_offload_disk_path, kv_offload_device_name.
|
||||
Exports PYTHONHASHSEED + MOONCAKE_CONFIG_PATH for the vLLM process on this node. -#}
|
||||
Exports PYTHONHASHSEED + MOONCAKE_CONFIG_PATH for the vLLM process. (VLLM_RPC_BASE_PATH,
|
||||
used by the mooncake-store lookup ipc socket, is set per-rank in _launch_rank.sh.j2.) -#}
|
||||
# ---- Mooncake distributed store (shared pool across inference nodes) ----
|
||||
MC_DIR="$OUTPUT_DIR/mooncake/node_${INFER_NODE_RANK}"
|
||||
mkdir -p "$MC_DIR"
|
||||
@@ -23,9 +24,11 @@
|
||||
{%- endif %}
|
||||
if [ "$SLURMD_NODENAME" = "$MC_HEAD" ]; then
|
||||
{%- if kv_offload_disk_path %}
|
||||
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -enable_offload=true -root_fs_dir={{ kv_offload_disk_path }} > "$MC_DIR/master.log" 2>&1 &
|
||||
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -default_kv_lease_ttl=3600000 -enable_offload=true -root_fs_dir={{ kv_offload_disk_path }} > "$MC_DIR/master.log" 2>&1 &
|
||||
{%- else %}
|
||||
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 > "$MC_DIR/master.log" 2>&1 &
|
||||
# default_kv_lease_ttl raised from 5s: KV blocks were expiring before the decode side
|
||||
# reused them ("invalid KV blocks ... may have expired"), the real non-NIC config issue.
|
||||
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -default_kv_lease_ttl=3600000 > "$MC_DIR/master.log" 2>&1 &
|
||||
{%- endif %}
|
||||
fi
|
||||
# Every node waits for the shared master + metadata, then contributes its segment.
|
||||
|
||||
@@ -28,7 +28,7 @@ set -e
|
||||
# Configs
|
||||
export NUM_NODES={{ num_nodes }}
|
||||
export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
{% if disaggregated -%}
|
||||
{% if is_disaggregated -%}
|
||||
export NUM_PREFILL_NODES={{ num_prefill_nodes }}
|
||||
export NUM_DECODE_NODES={{ num_decode_nodes }}
|
||||
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
|
||||
@@ -38,10 +38,13 @@ export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
|
||||
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
|
||||
export PREFILL_PORT={{ prefill_port }}
|
||||
export DECODE_PORT={{ decode_port }}
|
||||
export ROUTER_PORT={{ router_port }}
|
||||
export ROUTER_PORT={{ router.port }}
|
||||
export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
{%- if router.type == "llm-d" %}
|
||||
export DECODE_SIDECAR_PORT={{ router.decode_sidecar_port }}
|
||||
{%- endif %}
|
||||
{%- elif num_nodes > 1 %}
|
||||
export ROUTER_PORT={{ router_port }}
|
||||
export ROUTER_PORT={{ router.port }}
|
||||
export BACKEND_PORT={{ backend_port }}
|
||||
export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
{%- endif %}
|
||||
@@ -70,7 +73,7 @@ uv sync --all-extras
|
||||
# Print inference URLs
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
export HOSTNAMES_STR="${HOSTNAMES[*]}"
|
||||
{% if disaggregated -%}
|
||||
{% if is_disaggregated -%}
|
||||
# Build per-replica router URLs
|
||||
INFER_URLS=""
|
||||
ALL_ROUTER_ARGS=""
|
||||
@@ -132,6 +135,10 @@ srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
# llm-d router procs (EPP + Envoy + decode pd-sidecar) left over from a prior run.
|
||||
pkill -9 -f "[e]pp.*pool-name" 2>/dev/null
|
||||
pkill -9 -f "[e]nvoy.*envoy.yaml" 2>/dev/null
|
||||
pkill -9 -f "[p]d-sidecar" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
@@ -144,7 +151,7 @@ srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -x mooncake_client 2>/dev/null
|
||||
sleep 2
|
||||
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | grep -v grep | wc -l)
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
CLEANUP_SH
|
||||
@@ -179,7 +186,7 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
{% include "_mooncake_store.sh.j2" %}
|
||||
{%- endif %}
|
||||
|
||||
{% if disaggregated -%}
|
||||
{% if is_disaggregated -%}
|
||||
# NVSHMEM libs for DeepEP — ensure the rpath target exists on all nodes
|
||||
if [ ! -d /tmp/deepep_build/nvshmem/lib ] && [ -d "$OUTPUT_DIR/nvshmem/lib" ]; then
|
||||
mkdir -p /tmp/deepep_build/nvshmem
|
||||
@@ -247,7 +254,7 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
{% for key, value in prefill_env_overrides.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{% endfor %}
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\""
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\"{{ prefill_vllm_extra_json }}"
|
||||
else
|
||||
# ── Decode node ──
|
||||
export UCX_NET_DEVICES=mlx5_0:1
|
||||
@@ -262,7 +269,7 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
{% for key, value in decode_env_overrides.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{% endfor %}
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG"
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}"
|
||||
fi
|
||||
|
||||
echo "NODE_RANK=$INFER_NODE_RANK ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT LOCAL_IP=$LOCAL_IP" \
|
||||
@@ -271,8 +278,28 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
# Start the router on the first prefill node of each replica (external LB across per-rank endpoints)
|
||||
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
|
||||
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
|
||||
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router_policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
|
||||
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
|
||||
fi
|
||||
{%- if router.type == "llm-d" %}
|
||||
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
|
||||
# + rank) -> vLLM decode (DECODE_PORT + rank) after orchestrating remote prefill.
|
||||
# Every decode node fronts its own local ranks, so launch on each (not just the
|
||||
# replica head), or decode nodes beyond the head get advertised but unserved endpoints.
|
||||
if [ "$ROLE" = "decode" ]; then
|
||||
SIDECAR_LOG="$OUTPUT_DIR/logs/inference/sidecar_${INFER_NODE_RANK}.log"
|
||||
echo "Starting pd-sidecar on $LOCAL_IP:$DECODE_SIDECAR_PORT(+rank) -> vLLM $DECODE_PORT(+rank)" | tee $SIDECAR_LOG
|
||||
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
|
||||
pd-sidecar \
|
||||
--port $DECODE_SIDECAR_PORT \
|
||||
--vllm-port $DECODE_PORT \
|
||||
--kv-connector nixlv2 \
|
||||
--secure-proxy=false \
|
||||
--enable-ssrf-protection=false \
|
||||
--inference-pool prime-rl \
|
||||
--data-parallel-size {{ dp_per_node }} \
|
||||
>> $SIDECAR_LOG 2>&1 &
|
||||
fi
|
||||
{%- endif %}
|
||||
|
||||
# External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP
|
||||
# slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP
|
||||
@@ -296,7 +323,7 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
|
||||
# Start the router on node 0 (balances across per-rank endpoints — no intra-node DP header)
|
||||
if [ "$INFER_NODE_RANK" -eq 0 ]; then
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router_policy }}" "$OUTPUT_DIR/logs/inference/router.log"
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log" 0 0 "$NUM_NODES"
|
||||
fi
|
||||
|
||||
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
{# llm-d file-discovery endpoints: one entry per DP rank. Rendered (via include)
|
||||
into the sbatch; the per-node address is the __LLMD_ADDR_<node>__ placeholder,
|
||||
filled with each SLURM host's IPv4 inline in the sbatch (file-discovery rejects
|
||||
hostnames). Node ordering matches the sbatch's host loop: prefill then decode.
|
||||
The including sbatch sets ep_* via {% set %}. #}
|
||||
endpoints:
|
||||
{%- if ep_disaggregated %}
|
||||
{%- for node in range(ep_num_prefill) %}
|
||||
{%- for rank in range(ep_dp) %}
|
||||
- name: prefill-{{ node }}-rank-{{ rank }}
|
||||
address: __LLMD_ADDR_{{ node }}__
|
||||
port: "{{ ep_prefill_port + rank }}"
|
||||
namespace: default
|
||||
labels:
|
||||
llm-d.ai/pool: prime-rl
|
||||
llm-d.ai/role: prefill
|
||||
{%- endfor %}
|
||||
{%- endfor %}
|
||||
{%- for node in range(ep_num_decode) %}
|
||||
{%- for rank in range(ep_dp) %}
|
||||
- name: decode-{{ node }}-rank-{{ rank }}
|
||||
address: __LLMD_ADDR_{{ ep_num_prefill + node }}__
|
||||
port: "{{ ep_sidecar_port + rank }}"
|
||||
namespace: default
|
||||
labels:
|
||||
llm-d.ai/pool: prime-rl
|
||||
llm-d.ai/role: decode
|
||||
{%- endfor %}
|
||||
{%- endfor %}
|
||||
{%- else %}
|
||||
{%- for node in range(ep_num_nodes) %}
|
||||
{%- for rank in range(ep_dp) %}
|
||||
- name: backend-{{ node }}-rank-{{ rank }}
|
||||
address: __LLMD_ADDR_{{ node }}__
|
||||
port: "{{ ep_backend_port + rank }}"
|
||||
namespace: default
|
||||
labels:
|
||||
llm-d.ai/pool: prime-rl
|
||||
{%- endfor %}
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
@@ -0,0 +1,97 @@
|
||||
{# Envoy data plane: EPP picks the backend (ext_proc) and sets
|
||||
x-gateway-destination-endpoint; the ORIGINAL_DST cluster routes there. Both
|
||||
/v1/ (MITO) and /inference/v1/ (TITO) go through the picker. EPP gRPC is on
|
||||
loopback 9002; the gateway listens on the configured port. #}
|
||||
admin:
|
||||
address: { socket_address: { address: 127.0.0.1, port_value: 9901 } }
|
||||
static_resources:
|
||||
listeners:
|
||||
- name: prime_rl
|
||||
address: { socket_address: { address: 0.0.0.0, port_value: {{ router.port }} } }
|
||||
filter_chains:
|
||||
- filters:
|
||||
- name: envoy.filters.network.http_connection_manager
|
||||
typed_config:
|
||||
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
|
||||
stat_prefix: prime_rl
|
||||
codec_type: AUTO
|
||||
stream_idle_timeout: 0s
|
||||
request_timeout: 0s
|
||||
route_config:
|
||||
virtual_hosts:
|
||||
- name: prime_rl
|
||||
domains: ["*"]
|
||||
routes:
|
||||
- match: { prefix: "/v1/" }
|
||||
route: { cluster: backend_cluster, timeout: 0s, idle_timeout: 86400s }
|
||||
- match: { prefix: "/inference/v1/" }
|
||||
route: { cluster: backend_cluster, timeout: 0s, idle_timeout: 86400s }
|
||||
http_filters:
|
||||
- name: envoy.filters.http.ext_proc
|
||||
typed_config:
|
||||
"@type": type.googleapis.com/envoy.extensions.filters.http.ext_proc.v3.ExternalProcessor
|
||||
grpc_service:
|
||||
envoy_grpc: { cluster_name: epp_cluster }
|
||||
timeout: 10s
|
||||
processing_mode:
|
||||
request_header_mode: SEND
|
||||
response_header_mode: SEND
|
||||
request_body_mode: FULL_DUPLEX_STREAMED
|
||||
response_body_mode: FULL_DUPLEX_STREAMED
|
||||
request_trailer_mode: SEND
|
||||
response_trailer_mode: SEND
|
||||
message_timeout: 1000s
|
||||
- name: envoy.filters.http.router
|
||||
typed_config:
|
||||
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
|
||||
suppress_envoy_headers: true
|
||||
clusters:
|
||||
- name: backend_cluster
|
||||
type: ORIGINAL_DST
|
||||
lb_policy: CLUSTER_PROVIDED
|
||||
original_dst_lb_config:
|
||||
use_http_header: true
|
||||
http_header_name: x-gateway-destination-endpoint
|
||||
connect_timeout: 5s
|
||||
# Default circuit breakers (~1024) overflow at high inflight concurrency (>=1536),
|
||||
# causing "reset reason: overflow" 500s. Raise far above the max concurrent rollouts.
|
||||
circuit_breakers:
|
||||
thresholds:
|
||||
- priority: DEFAULT
|
||||
max_connections: 100000
|
||||
max_pending_requests: 100000
|
||||
max_requests: 100000
|
||||
max_retries: 1000
|
||||
- priority: HIGH
|
||||
max_connections: 100000
|
||||
max_pending_requests: 100000
|
||||
max_requests: 100000
|
||||
max_retries: 1000
|
||||
- name: epp_cluster
|
||||
type: STRICT_DNS
|
||||
typed_extension_protocol_options:
|
||||
envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
|
||||
"@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
|
||||
explicit_http_config:
|
||||
http2_protocol_options: {}
|
||||
load_assignment:
|
||||
cluster_name: epp_cluster
|
||||
endpoints:
|
||||
- lb_endpoints:
|
||||
- endpoint:
|
||||
address: { socket_address: { address: 127.0.0.1, port_value: 9002 } }
|
||||
connect_timeout: 5s
|
||||
# ext_proc (EPP) connection pool overflows at high concurrency without this — the
|
||||
# gRPC ext_proc calls are 1:1 with inflight requests, so cap well above max rollouts.
|
||||
circuit_breakers:
|
||||
thresholds:
|
||||
- priority: DEFAULT
|
||||
max_connections: 100000
|
||||
max_pending_requests: 100000
|
||||
max_requests: 100000
|
||||
max_retries: 1000
|
||||
- priority: HIGH
|
||||
max_connections: 100000
|
||||
max_pending_requests: 100000
|
||||
max_requests: 100000
|
||||
max_retries: 1000
|
||||
@@ -0,0 +1,34 @@
|
||||
{# llm-d EPP config: single-pool (non-P/D) routing with approximate prefix-cache
|
||||
scoring. The vllmhttp parser embeds the OpenAI parser and also handles
|
||||
/inference/v1/generate (token_ids), so MITO + TITO both get prefix-cache
|
||||
scoring. Included into the sbatch as a heredoc; $LLMD_DIR is the per-replica
|
||||
config dir, expanded at launch time. #}
|
||||
apiVersion: inference.networking.x-k8s.io/v1alpha1
|
||||
kind: EndpointPickerConfig
|
||||
plugins:
|
||||
- name: file-disc
|
||||
type: file-discovery
|
||||
parameters:
|
||||
path: $LLMD_DIR/endpoints.yaml
|
||||
watchFile: true
|
||||
- name: vllmhttp-parser
|
||||
type: vllmhttp-parser
|
||||
{%- for scorer in router.scorers %}
|
||||
- type: {{ scorer }}
|
||||
{%- endfor %}
|
||||
- type: max-score-picker
|
||||
- type: single-profile-handler
|
||||
schedulingProfiles:
|
||||
- name: default
|
||||
plugins:
|
||||
{%- for scorer, weight in router.scorers.items() %}
|
||||
- pluginRef: {{ scorer }}
|
||||
weight: {{ weight }}
|
||||
{%- endfor %}
|
||||
- pluginRef: max-score-picker
|
||||
requestHandler:
|
||||
parser:
|
||||
pluginRef: vllmhttp-parser
|
||||
dataLayer:
|
||||
discovery:
|
||||
pluginRef: file-disc
|
||||
@@ -0,0 +1,56 @@
|
||||
{# llm-d EPP config: prefill/decode disaggregation. disagg-profile-handler runs
|
||||
the prefill profile when prefix-based-pd-decider sees >= nonCachedTokens
|
||||
non-cached prompt tokens, else decode-only. Mirrors the upstream llm-d PD
|
||||
guide: the prefill profile uses prefill_scorers (prefix + queue/kv) and the
|
||||
decode profile uses scorers (prefix + active-request); prefill-filter /
|
||||
decode-filter select endpoints by llm-d.ai/role label. Included into the
|
||||
sbatch as a heredoc; $LLMD_DIR is the per-replica config dir, expanded at
|
||||
launch time. #}
|
||||
apiVersion: inference.networking.x-k8s.io/v1alpha1
|
||||
kind: EndpointPickerConfig
|
||||
plugins:
|
||||
- name: file-disc
|
||||
type: file-discovery
|
||||
parameters:
|
||||
path: $LLMD_DIR/endpoints.yaml
|
||||
watchFile: true
|
||||
- name: vllmhttp-parser
|
||||
type: vllmhttp-parser
|
||||
- name: pd-decider
|
||||
type: prefix-based-pd-decider
|
||||
parameters:
|
||||
nonCachedTokens: {{ router.non_cached_tokens }}
|
||||
- name: profile-handler
|
||||
type: disagg-profile-handler
|
||||
parameters:
|
||||
deciders:
|
||||
prefill: pd-decider
|
||||
- type: prefill-filter
|
||||
- type: decode-filter
|
||||
{%- for scorer in ((router.prefill_scorers.keys() | list) + (router.decode_scorers.keys() | list)) | unique %}
|
||||
- type: {{ scorer }}
|
||||
{%- endfor %}
|
||||
- type: max-score-picker
|
||||
schedulingProfiles:
|
||||
- name: prefill
|
||||
plugins:
|
||||
- pluginRef: prefill-filter
|
||||
{%- for scorer, weight in router.prefill_scorers.items() %}
|
||||
- pluginRef: {{ scorer }}
|
||||
weight: {{ weight }}
|
||||
{%- endfor %}
|
||||
- pluginRef: max-score-picker
|
||||
- name: decode
|
||||
plugins:
|
||||
- pluginRef: decode-filter
|
||||
{%- for scorer, weight in router.decode_scorers.items() %}
|
||||
- pluginRef: {{ scorer }}
|
||||
weight: {{ weight }}
|
||||
{%- endfor %}
|
||||
- pluginRef: max-score-picker
|
||||
requestHandler:
|
||||
parser:
|
||||
pluginRef: vllmhttp-parser
|
||||
dataLayer:
|
||||
discovery:
|
||||
pluginRef: file-disc
|
||||
@@ -32,7 +32,7 @@ export NODES_PER_INFER_REPLICA={{ nodes_per_infer_replica }}
|
||||
export NUM_INFER_REPLICAS={{ num_infer_replicas }}
|
||||
export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
export ROUTER_PORT={{ router_port }}
|
||||
export ROUTER_PORT={{ router.port }}
|
||||
export INFERENCE_TP={{ inference_tp }}
|
||||
export INFERENCE_DP_LOCAL=$((GPUS_PER_NODE / INFERENCE_TP))
|
||||
export INFERENCE_DATA_PARALLEL_RPC_PORT={{ inference_data_parallel_rpc_port }}
|
||||
@@ -45,6 +45,9 @@ export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
|
||||
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
|
||||
export PREFILL_PORT={{ prefill_port }}
|
||||
export DECODE_PORT={{ decode_port }}
|
||||
{%- if router.type == "llm-d" %}
|
||||
export DECODE_SIDECAR_PORT={{ router.decode_sidecar_port }}
|
||||
{%- endif %}
|
||||
{%- else -%}
|
||||
export BACKEND_PORT={{ backend_port }}
|
||||
export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parallel else "0" }}
|
||||
@@ -166,6 +169,10 @@ srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
# llm-d router procs (EPP + Envoy + decode pd-sidecar) left over from a prior run.
|
||||
pkill -9 -f "[e]pp.*pool-name" 2>/dev/null
|
||||
pkill -9 -f "[e]nvoy.*envoy.yaml" 2>/dev/null
|
||||
pkill -9 -f "[p]d-sidecar" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
@@ -178,7 +185,7 @@ srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -x mooncake_client 2>/dev/null
|
||||
sleep 2
|
||||
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | grep -v grep | wc -l)
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
CLEANUP_SH
|
||||
@@ -284,7 +291,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
{% for key, value in prefill_env_overrides.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{% endfor %}
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\""
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\"{{ prefill_vllm_extra_json }}"
|
||||
else
|
||||
export UCX_NET_DEVICES=mlx5_0:1
|
||||
ROLE="decode"
|
||||
@@ -298,7 +305,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
{% for key, value in decode_env_overrides.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{% endfor %}
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG"
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}"
|
||||
fi
|
||||
|
||||
echo "ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT" \
|
||||
@@ -307,8 +314,28 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
# Start the router on the first node of each replica (PD mode, external LB across per-rank endpoints)
|
||||
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
|
||||
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
|
||||
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" consistent_hash "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
|
||||
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
|
||||
fi
|
||||
{%- if router.type == "llm-d" %}
|
||||
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
|
||||
# + rank) -> vLLM decode (DECODE_PORT + rank) after orchestrating remote prefill.
|
||||
# Every decode node fronts its own local ranks, so launch on each (not just the
|
||||
# replica head), or decode nodes beyond the head get advertised but unserved endpoints.
|
||||
if [ "$ROLE" = "decode" ]; then
|
||||
SIDECAR_LOG="$OUTPUT_DIR/logs/inference/sidecar_${INFER_NODE_RANK}.log"
|
||||
echo "Starting pd-sidecar on $LOCAL_IP:$DECODE_SIDECAR_PORT(+rank) -> vLLM $DECODE_PORT(+rank)" | tee $SIDECAR_LOG
|
||||
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
|
||||
pd-sidecar \
|
||||
--port $DECODE_SIDECAR_PORT \
|
||||
--vllm-port $DECODE_PORT \
|
||||
--kv-connector nixlv2 \
|
||||
--secure-proxy=false \
|
||||
--enable-ssrf-protection=false \
|
||||
--inference-pool prime-rl \
|
||||
--data-parallel-size $INFERENCE_DP_LOCAL \
|
||||
>> $SIDECAR_LOG 2>&1 &
|
||||
fi
|
||||
{%- endif %}
|
||||
|
||||
# External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP
|
||||
# slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP
|
||||
@@ -325,7 +352,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
# Start the router on the first node of each replica
|
||||
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
|
||||
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
|
||||
launch_router regular "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" consistent_hash "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
|
||||
launch_router regular "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$((REPLICA_IDX * NODES_PER_INFER_REPLICA))" "$NODES_PER_INFER_REPLICA"
|
||||
fi
|
||||
|
||||
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + d),
|
||||
|
||||
@@ -2,8 +2,10 @@ import copy
|
||||
from collections.abc import Callable, Sequence
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from prime_rl.trainer.utils import balanced_partition
|
||||
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingSample
|
||||
from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
|
||||
|
||||
ROUTED_EXPERTS_DTYPE_ITEMSIZE = {
|
||||
"uint8": 1,
|
||||
@@ -41,26 +43,77 @@ def _pad_routed_experts(micro_batch: MicroBatch, padding_size: int) -> None:
|
||||
routed_experts.shape[0] += padding_size
|
||||
|
||||
|
||||
def _slice_encoded(tensor: EncodedTensor, n_rows: int) -> EncodedTensor:
|
||||
"""First `n_rows` rows of a dim-0-stacked encoded tensor (e.g. pixel_values, image_grid_thw)."""
|
||||
row = int(np.prod(tensor.shape[1:])) if len(tensor.shape) > 1 else 1
|
||||
itemsize = np.dtype(tensor.dtype).itemsize
|
||||
return EncodedTensor(
|
||||
dtype=tensor.dtype,
|
||||
shape=[n_rows, *tensor.shape[1:]],
|
||||
data=tensor.data[: n_rows * row * itemsize],
|
||||
)
|
||||
|
||||
|
||||
def _truncate_mm(
|
||||
mm_token_type_ids: list[int], mm_kwargs: dict[str, EncodedTensor], seq_len: int
|
||||
) -> tuple[int, dict[str, EncodedTensor] | None]:
|
||||
"""Truncating a sample must not split an image's placeholder block, else the surviving image
|
||||
token count no longer matches the image embeddings in `mm_kwargs`. Returns the cut point
|
||||
(<= seq_len, never inside an image block) and `mm_kwargs` sliced to the images whose
|
||||
placeholders fully survive (None if no image survives)."""
|
||||
grid = np.frombuffer(bytearray(mm_kwargs["image_grid_thw"].data), dtype=mm_kwargs["image_grid_thw"].dtype).reshape(
|
||||
mm_kwargs["image_grid_thw"].shape
|
||||
)
|
||||
patches_per_image = [int(g.prod()) for g in grid]
|
||||
total_patches = mm_kwargs["pixel_values"].shape[0]
|
||||
total_tokens = sum(1 for t in mm_token_type_ids if t)
|
||||
ppt = total_patches // total_tokens if total_tokens else 1 # patches per token (merge^2)
|
||||
tokens_per_image = [p // ppt for p in patches_per_image]
|
||||
|
||||
surviving = sum(1 for t in mm_token_type_ids[:seq_len] if t)
|
||||
kept = acc = 0
|
||||
for n in tokens_per_image:
|
||||
if acc + n > surviving:
|
||||
break
|
||||
acc += n
|
||||
kept += 1
|
||||
if acc == surviving:
|
||||
cut = seq_len # surviving image tokens are exactly `kept` whole images
|
||||
else:
|
||||
# `surviving` lands inside image `kept`; cut to its first placeholder, dropping it.
|
||||
seen, cut = 0, seq_len
|
||||
for i, t in enumerate(mm_token_type_ids):
|
||||
if t:
|
||||
seen += 1
|
||||
if seen == acc + 1:
|
||||
cut = i
|
||||
break
|
||||
if not kept:
|
||||
return cut, None
|
||||
kept_patches = sum(patches_per_image[:kept])
|
||||
sliced = {k: _slice_encoded(v, kept if k == "image_grid_thw" else kept_patches) for k, v in mm_kwargs.items()}
|
||||
return cut, sliced
|
||||
|
||||
|
||||
def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch:
|
||||
"""
|
||||
Prepare a problem for sequence packing training.
|
||||
Tokenize and prepare tensors.
|
||||
"""
|
||||
input_ids = training_example.prompt_ids + training_example.completion_ids
|
||||
loss_mask = training_example.prompt_mask + training_example.completion_mask
|
||||
inference_logprobs = [0.0] * len(training_example.prompt_ids) + training_example.completion_logprobs
|
||||
input_ids = training_example.token_ids
|
||||
loss_mask = training_example.mask
|
||||
inference_logprobs = training_example.logprobs
|
||||
advantages = [training_example.advantage] * len(input_ids)
|
||||
reward = training_example.reward if training_example.reward is not None else float("nan")
|
||||
rewards = [reward] * len(input_ids)
|
||||
position_ids = list(range(len(input_ids)))
|
||||
mm_token_type_ids = training_example.mm_token_type_ids
|
||||
mm_kwargs = training_example.mm_kwargs
|
||||
assert training_example.env_name != "all", "env_name='all' is reserved for aggregate metric keys"
|
||||
env_names = [training_example.env_name] * len(input_ids)
|
||||
|
||||
# Per-token temperatures: prompt tokens use first completion temp (masked out anyway)
|
||||
# Default to 1.0 if completion is empty (e.g., model generated only tool calls with no text)
|
||||
prompt_temp = training_example.completion_temperatures[0] if training_example.completion_temperatures else 1.0
|
||||
temperatures = [prompt_temp] * len(training_example.prompt_ids) + training_example.completion_temperatures
|
||||
# Per-token sampling temperatures (context tokens are masked out, so theirs are don't-care).
|
||||
temperatures = training_example.temperatures
|
||||
|
||||
# Teacher logprobs already cover the full sequence (prompt + completion),
|
||||
# computed via prefill in the orchestrator when a teacher model is configured
|
||||
@@ -70,20 +123,25 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
)
|
||||
|
||||
if len(input_ids) > seq_len:
|
||||
input_ids = input_ids[:seq_len]
|
||||
loss_mask = loss_mask[:seq_len]
|
||||
inference_logprobs = inference_logprobs[:seq_len]
|
||||
position_ids = position_ids[:seq_len]
|
||||
advantages = advantages[:seq_len]
|
||||
rewards = rewards[:seq_len]
|
||||
temperatures = temperatures[:seq_len]
|
||||
# Multimodal: never split an image's placeholder block — cut to a whole-image boundary
|
||||
# and slice mm_kwargs to match, so image-token count == image-embedding count.
|
||||
cut = seq_len
|
||||
if mm_token_type_ids is not None and mm_kwargs is not None:
|
||||
cut, mm_kwargs = _truncate_mm(mm_token_type_ids, mm_kwargs, seq_len)
|
||||
input_ids = input_ids[:cut]
|
||||
loss_mask = loss_mask[:cut]
|
||||
inference_logprobs = inference_logprobs[:cut]
|
||||
position_ids = position_ids[:cut]
|
||||
advantages = advantages[:cut]
|
||||
rewards = rewards[:cut]
|
||||
temperatures = temperatures[:cut]
|
||||
if teacher_logprobs is not None:
|
||||
teacher_logprobs = teacher_logprobs[:seq_len]
|
||||
teacher_logprobs = teacher_logprobs[:cut]
|
||||
if routed_experts is not None:
|
||||
routed_experts = _slice_routed_experts(routed_experts, seq_len)
|
||||
routed_experts = _slice_routed_experts(routed_experts, cut)
|
||||
if mm_token_type_ids is not None:
|
||||
mm_token_type_ids = mm_token_type_ids[:seq_len]
|
||||
env_names = env_names[:seq_len]
|
||||
mm_token_type_ids = mm_token_type_ids[:cut]
|
||||
env_names = env_names[:cut]
|
||||
|
||||
assert (
|
||||
len(input_ids)
|
||||
@@ -124,7 +182,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
routed_experts=routed_experts,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
env_names=env_names,
|
||||
mm_kwargs=training_example.mm_kwargs,
|
||||
mm_kwargs=mm_kwargs,
|
||||
training_mode=training_example.training_mode,
|
||||
)
|
||||
|
||||
|
||||
@@ -510,6 +510,18 @@ def get_model(
|
||||
model_config.use_index_cache = True
|
||||
model_config.index_topk_freq = config.index_cache.topk_freq
|
||||
model_config.index_topk_pattern = config.index_cache.topk_pattern
|
||||
# Explicit override supersedes the model's native IndexShare schedule.
|
||||
model_config.indexer_types = None
|
||||
else:
|
||||
# Auto-enable IndexShare from the model's own indexer schedule (e.g. GLM-5.2). The model
|
||||
# reads `indexer_types` directly: shared layers reuse cached indices and carry no indexer weights.
|
||||
indexer_types = getattr(model_config, "indexer_types", None)
|
||||
if indexer_types and any(t == "shared" for t in indexer_types):
|
||||
model_config.use_index_cache = True
|
||||
logger.info(
|
||||
f"Auto-enabled IndexShare from indexer_types schedule "
|
||||
f"({sum(t == 'full' for t in indexer_types)}/{len(indexer_types)} full layers)"
|
||||
)
|
||||
|
||||
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
|
||||
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
|
||||
|
||||
@@ -227,7 +227,11 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
# .contiguous(): the per-layer slice is a strided view of [tokens, layers, topk]
|
||||
# (dim-1 stride = layers*topk); torch.compile's MoE kernel asserts a contiguous input.
|
||||
routed_experts_layer = (
|
||||
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
|
||||
)
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user