Compare commits

...
Author SHA1 Message Date
samsjaandGitHub bf3d381cfe refactor: remove "auto" option from fused_lm_head_token_chunk_size (#2890)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The "auto" value for fused_lm_head_token_chunk_size previously resolved
to 8192 for RL training via a config validator. This was redundant since
users can simply set the integer explicitly. Remove the "auto" option,
its validator (auto_setup_fused_lm_head_token_chunk_size), and update
docs/CHANGELOG accordingly.

The type changes from int | Literal["auto", "disabled"] to
int | Literal["disabled"]. Users who relied on "auto" should set
fused_lm_head_token_chunk_size = 8192 explicitly.
2026-06-27 14:31:46 -07:00
halleriteandGitHub 0be5ac452a feat: algorithm abstraction — named algorithm classes + inline frozen-model references (grpo, opd, sft_distill, self_distill, echo) (#2746)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-27 21:15:02 +02:00
c5afcaa2e2 feat: default ep to auto for MoE models (#2868)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: default ep to "auto" for MoE models

ep now defaults to "auto" which resolves at trainer startup to the
largest valid EP degree up to 8. The resolution loads AutoConfig 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, auto resolves to 1.

Changes:
- ModelConfig.ep type: int -> int | Literal["auto"], default "auto"
- Added resolve_ep() in parallel_dims.py, called before
  get_parallel_dims() in both rl/train.py and sft/train.py
- Fixed validators (validate_ep_comm_backend, ep_only_with_custom_impl)
  to handle the "auto" string without comparing to int
- get_parallel_dims() now asserts ep is resolved to int
- Updated docs/scaling.md and CHANGELOG.md

* fix: ruff format parallel_dims.py

* feat: enable memory-saving defaults (ac, ac_offloading, compile, optim_cpu_offload, chunk loss)

- model.ac: None -> ActivationCheckpointConfig() (full mode)
- model.ac_offloading: None -> ActivationOffloadingConfig()
- model.compile: None -> CompileConfig() (fullgraph=false)
- model.optim_cpu_offload: False -> True
- model.fused_lm_head_token_chunk_size: disabled -> 1024
- SFT silently disables fused_lm_head_token_chunk_size
- Multi-run CI config sets optim_cpu_offload=false
- Debug configs disable compile

* refactor: replace ep="auto" string with auto_ep boolean

- Replace ep: int | Literal["auto"] = "auto" with auto_ep: bool = True + ep: int = 1
- Update validators to check auto_ep instead of string comparisons
- Revert SFT changes to main (ep_only_with_custom_impl, sft/train.py)
- Keep SFT validate_and_disable_chunked_loss fix (silently disable)
- Remove isinstance assertion in get_parallel_dims (ep is always int now)
- Update docs and changelog

* fix: address review comments

- Rename resolve_ep to resolve_auto_ep (samsja)
- Add impl guard in resolve_auto_ep: skip EP for hf impl (bugbot)
- Add runtime check: raise if deepep resolves to ep=1 (bugbot)
- Revert configs/debug/moe/sft/train.toml to keep compile enabled (mika)

* fix: update benchmark baselines for memory-saving defaults

The new memory-saving defaults (ac, ac_offloading, compile, optim_cpu_offload,
fused_lm_head_token_chunk_size) reduce throughput. Update both 1-GPU and 4-GPU
baselines to the actual metrics from the CI run.

* refactor: replace auto_ep boolean with ep: int | Literal["auto"]

- Remove the auto_ep boolean field from ModelConfig
- Change ep type from int to int | Literal["auto"], default "auto"
- Rename resolve_auto_ep back to resolve_ep, check config.ep != "auto"
- Update validators to handle ep being a string (isinstance check)
- Add assertion in get_parallel_dims that ep is resolved to int
- Update docs/scaling.md and CHANGELOG.md

* fix(sft): handle ep="auto" in ep_only_with_custom_impl validator

The SFT validator used  which raises TypeError when ep is
"auto" (a str). Match the RL trainer's approach using != comparisons
to handle both int and str types.

* fix(sft): call resolve_ep before get_parallel_dims in SFT trainer

* Simplify resolve_ep: min(fsdp_island_size, 8) for MoE, 1 otherwise

Remove the magic auto-resolution that searched for the largest EP degree
satisfying num_experts divisibility, FSDP island divisibility, and cp
multiple constraints. Now just checks if the model is MoE and resolves
to min(fsdp_island_size, 8).

* docs(inference): document required NIXL/UCX from-source build for P/D disaggregation

---------

Co-authored-by: samsja <samsja@users.noreply.github.com>
2026-06-26 16:17:13 -07:00
3cbeb5d0f1 feat: vLLM 0.23 bump + GLM-5.2 16-node P/D inference config (mooncake + llm-d) (#2883)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: bump vLLM to 0.23.0 and prune/adapt monkeypatches

Bump vllm 0.22.0 -> 0.23.0 (pyproject + regenerated uv.lock).

Remove two now-redundant monkeypatches (verified against 0.23.0 source,
adversarially double-checked):
- monkey_patch_deep_gemm_silu_mul_quant_int64: upstream kernel already uses
  int64 pointer arithmetic, so the patch was a behavioral no-op.
- _patch_qwen35_lora (vllm#36372): the Qwen3.5 GDN LoRA IndexError is fixed
  natively in vLLM; the patch is redundant and would corrupt the native path.

Adapt two patches the bump moved/changed:
- serving_tokens: get_max_tokens moved out of the deleted vllm.entrypoints.utils
  to vllm.entrypoints.serve.utils.api_utils (import-time breakage otherwise).
- monkey_patch_minimax_m2_for_lora: the MoE gate is now GateLinear (was
  ReplicatedLinear); rebuild as GateLinear(out_dtype=float32) with a bf16 weight
  so the LoRA Triton kernel's bf16/fp16 assertion passes while router logits
  stay fp32.

Default VLLM_USE_V2_MODEL_RUNNER=0: vLLM 0.23.0 routes dense Llama/Mistral/Qwen3
to the V2 GPU model runner, which has no _preprocess hook for the padded-input
scrub and does not zero the padded decode tail itself, reproducing NaN logits.
Forcing V1 keeps the scrub effective for every model and is also required for
routed-experts capture. setdefault keeps it overridable.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(inference): cite vllm#44814 as the NemotronH mixer.D reload fix

The _restore_reload_corrupted_params workaround's removal trigger was vague
("once the upstream bug is fixed"). The upstream fix is vllm-project/vllm#44814
(merged 2026-06-10), which is NOT in the pinned 0.23.0 release, so the workaround
is still required. Record the root cause (mixer.A's composed_weight_loader
double-count drops the trailing mixer.D) and the exact removal condition.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(configs): add GLM-5.2 16-node P/D mooncake + llm-d inference config

Standalone `inference` deployment for GLM-5.2-FP8 on 16 nodes: disaggregated
8 prefill (4 replicas) + 8 decode, mooncake distributed CPU KV store, llm-d
router (EPP+Envoy), vLLM 0.23. Requires source-built NIXL/UCX 1.19.x
(scripts/install_nixl_from_source.sh) — the wheel UCX segfaults on P/D KV
transfer. Validated: 1000-req/500-concurrent burst, 0 faults / 0 RPC_FAIL.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(inference): keep Qwen3.5-MoE on 2D per-expert LoRA format

Dropping _patch_qwen35_lora wholesale also removed the
Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = False override.
vLLM 0.23.0 defaults that flag to True, so the LoRA loader expects 3D
stacked-expert adapters, but our trainer emits the 2D per-expert layout
(MultiLoRAGroupedExperts.state_dict_for_adapter) which vLLM only reads
when is_3d_moe_weight is False (or enable_mixed_moe_lora_format=True).
Without the override Qwen3.5-MoE LoRA adapters fail to load.

Re-add it as a minimal standalone patch. The rest of the old shim
(in_proj_qkvz packed-mapping + N-slice can_replace_layer/slice_lora_a for
vllm#36372) stays removed -- 0.23.0 handles it natively via expand_packed_lora.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(dockerfile): bake NIXL-from-source into base image

The PyPI nixl wheel ships its own UCX that segfaults on prefill->decode KV
transfer (#2883). Rebuild NIXL against the UCX 1.19 we already compile in
the builder stage so the disagg P/D path works without per-host rebuilds.

Adds ~5 min to the amd64 build. arm64 unchanged for now — NIXL upstream
should support it but hasn't been validated here.

* gate NIXL build behind INCLUDE_NIXL_FROM_SOURCE arg

Default off — base build stays identical. The hosted-rl workflow that builds
the disagg P/D variant passes --build-arg INCLUDE_NIXL_FROM_SOURCE=1 (and
should tag-suffix the result, e.g. prime-rl:<ver>-nixl-amd64, to keep image
streams disambiguated).

* fix(dockerfile): seed pip into venv before building NIXL wheel

uv-created venvs don't include pip by default. Mirror install_nixl_from_source.sh
which seeds it via 'uv pip install pip' before invoking 'python -m pip wheel'.
Also swap the final install to 'uv pip install' so we don't depend on the
.venv/bin/pip shim either.

* feat(dockerfile): opt-in disagg extras build (INCLUDE_DISAGG_EXTRAS)

Adds --build-arg INCLUDE_DISAGG_EXTRAS=0 (default) gating --extra disagg
in the uv sync step. The disagg extra installs deep-ep, deep-gemm and
quack — heavy source builds only the disaggregated-MoE inference path
needs (e.g. GLM-5.2 16-node P/D with deepep_high_throughput).

Default off so training-only / single-node inference builds are unaffected.
Enable via --build-arg INCLUDE_DISAGG_EXTRAS=1; pairs with --build-arg
INCLUDE_NIXL_FROM_SOURCE=1 (#2885) for full disagg P/D images.

---------

Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: faresobeid <fares@primeintellect.ai>
Co-authored-by: Jannik Straube <info@jannik-straube.de>
2026-06-26 15:48:47 -07:00
f8660256f0 Qwen3.5 MRoPE VLM model (#2819)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix qwen3.5 mrope vlm model

* fix(qwen3.5): handle adjacent VLM image groups

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: eligotts <eligotts@users.noreply.github.com>
Co-authored-by: hubert-marek <hubert@uni.minerva.edu>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Hubert <163992334+hubert-marek@users.noreply.github.com>
2026-06-26 15:47:42 -07:00
minh hoangandGitHub a66f8bed1b [ENG-4094] docker: include cuda toolkit with runtime image (#2826)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* docker: copy cuda toolkit from builder into runtime image

* use slim bookworm for glibc 2.36

* use nvidia cuda base image at runtime to avoid glibc mismatches; include cuda 13 runtime

* bug bot fixes

* fix groupadd collision

* include python3.12-dev in runtime image

* use cuda 13 runtime libs source

* trim cuda12 toolkit to just the nvcc JIT essentials
2026-06-26 14:09:55 -07:00
d1f366b1bc chore: bump verifiers + research-environments to main (#2887)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: bump verifiers + research-environments to main

Bump deps/verifiers (62dc38a5 -> aa95826d, 0.1.15.dev396 -> dev400; adds the
reusable vf.Judge) and deps/research-environments (0687a15c -> 99ebd2e1) to
their latest main, and follow the env ports / removals they shipped.

research-environments removed six v0 envs prime-rl pinned (ported to v1):
- code-env -> i3-code-v1
- ifeval -> ifeval-v1
- math500 -> math500-v1
- mmlu-pro -> mmlu-pro-v1
- science-env -> i3-science-v1
- simpleqa-verified -> simpleqa-verified-v1

Also drop v0 envs that nothing references anymore: hle, rlm-swe, rlm-search,
tau2-bench (tau2-bench-v1 stays).

Configs:
- Migrate the math500 eval env onto math500-v1 (hendrycks_math, nemotron_4node,
  nemotron_debug).
- Remove the stale env_mix and math_group configs.

Bump the verifiers floor dev396 -> dev400 and relock.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: keep rlm-swe + rlm-search env deps

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 11:29:56 -07:00
halleriteandGitHub eb89285418 fix(orchestrator): eval completion_len is always 0 on the token-less relay (#2880)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 22:47:59 +02:00
halleriteandGitHub 9e1c011ce1 chore(utils): remove dead processor= path from chat_template (#2881)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 21:19:26 +02:00
halleriteandGitHub d507aeafc0 chore(configs): remove dead BaseModelConfig.is_vlm property (#2876)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 08:12:28 +02:00
halleriteandGitHub 3dd3b30e75 chore(client): remove dead InferencePool.get_metrics() (#2875)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 08:12:15 +02:00
halleriteandGitHub 3a5f617969 chore(utils): delete unused duplicate utils/messages.py (#2874)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 08:11:59 +02:00
halleriteandGitHub c268702f55 chore(filters): remove unconsumed FilterResult.detection_index (#2877)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 08:11:05 +02:00
halleriteandGitHub 62702bafa7 docs(inference): correct stale serving_tokens.py docstrings for vLLM 0.22 (#2878)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 08:10:26 +02:00
35b452b01c chore: bump verifiers + research-environments to main (#2873)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Bump deps/verifiers (b055799f -> 20abcd91) and deps/research-environments
(dbc58e14 -> 0687a15c) to their latest main, and follow the env
deprecations/ports they shipped.

research-environments removed several v0 envs and ported others to v1:
- drop dead v0 env deps (removed upstream): color-codeword,
  mini-swe-agent-plus, opencode-{cp,deepdive,math,science,swe}
- migrate ported envs v0 -> v1: deepdive, gpqa, livecodebench
- migrate the two multimodal color-codeword configs onto the
  color-codeword-v1 taskset (default harness, subprocess runtime)

Also bump the verifiers floor 0.1.15.dev388 -> dev394 to match the new pin
and relock.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 21:36:03 -07:00
halleriteandGitHub 2e29c66fd7 fix(orchestrator): align gibberish/repetition filters to v1 branch streams (#2872)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-25 06:02:41 +02:00
120 changed files with 4801 additions and 2348 deletions
+3
View File
@@ -2,6 +2,9 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`model.fused_lm_head_token_chunk_size` `"auto"` option removed**: The `"auto"` value is no longer accepted. Use an explicit integer (e.g. `8192`) or `"disabled"`. The `"auto"` value previously resolved to `8192` for RL training — set `fused_lm_head_token_chunk_size = 8192` explicitly to get the same behavior.
- **Memory-saving defaults enabled**: `trainer.model.ac`, `trainer.model.ac_offloading`, `trainer.model.compile`, `trainer.model.optim_cpu_offload`, and `trainer.model.fused_lm_head_token_chunk_size` are now enabled by default to provide sane memory-efficient defaults out of the box. Specifically: `ac` defaults to `ActivationCheckpointConfig()` (full mode), `ac_offloading` defaults to `ActivationOffloadingConfig()`, `compile` defaults to `CompileConfig()` (`fullgraph=false`), `optim_cpu_offload` defaults to `true`, and `fused_lm_head_token_chunk_size` defaults to `1024`. SFT training silently disables `fused_lm_head_token_chunk_size` (sets it to `"disabled"`). Configs using `max_concurrent_runs > 1` must explicitly set `optim_cpu_offload = false`. To disable any of these, set the field to `None` / `"None"` / `false` / `"disabled"` as appropriate.
- **`model.ep` defaults to `"auto"`**: The `ep` field type changed from `int` to `int | Literal["auto"]`, defaulting to `"auto"`. At trainer startup, `resolve_ep()` checks if the model is MoE (via `AutoConfig`); if so, it resolves to `min(fsdp_island_size, 8)` where `fsdp_island_size = world_size // dp_replicate`. For non-MoE models, `"auto"` resolves to 1 (no-op). Set `ep` to an explicit integer to override.
- **verifiers v1 training integration** (collection of removals/renames). The orchestrator now trains against a v1 env server returning `vf.Trace` rollouts, renderer-only, with a unified token schema.
- **`[[orchestrator.train.env]]` is now a v1 `vf.EnvServerConfig`**: a v1 env is `taskset = { id = "<id>" }` + `harness = { id = "default", runtime = { type = "subprocess" } }`. A bare `id = "<id>"` (optionally with `args`) runs the v0 env through the verifiers legacy bridge — old flat `id`/`args`-only configs keep working as legacy envs; v1 envs must use the `taskset`/`harness` shape.
- **`orchestrator.train.env` no longer defaults to a `reverse-text` env**: the default is now empty (`[]`), so configs must declare `[[orchestrator.train.env]]` explicitly.
+68 -3
View File
@@ -82,6 +82,10 @@ COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pr
# 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 \
@@ -96,18 +100,62 @@ RUN --mount=type=cache,target=/app/.cache/uv \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
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
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 \
@@ -128,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
@@ -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
}
}
}
@@ -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
}
}
}
@@ -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
@@ -1,10 +1,10 @@
# Smoke test for the RL-entrypoint OPD (on-policy distillation) training mode.
# The student inference deployment is launched by the rl entrypoint on GPU 0;
# the teacher inference server is started externally by the test fixture (see
# Smoke test for the RL-entrypoint opd algorithm (on-policy distillation).
# The policy inference deployment is launched by the rl entrypoint on GPU 0;
# the frozen reference server is started externally by the test fixture (see
# tests/integration/test_reverse_text_rl_opd.py) on the same GPU. Trainer
# takes GPU 1. Training config mirrors `reverse_text/start.toml`.
max_steps = 5
max_steps = 15
seq_len = 2048
[model]
@@ -15,10 +15,16 @@ project = "reverse-text-ci"
name = "ci-rl-opd"
[orchestrator]
training_mode = "opd"
batch_size = 128
group_size = 16
[orchestrator.algo]
type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
[orchestrator.renderer]
name = "qwen3"
@@ -38,12 +44,6 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
@@ -1,10 +1,10 @@
# Smoke test for the RL-entrypoint SFT (on-policy hard distillation) training
# mode. The student inference deployment is launched by the rl entrypoint on
# GPU 0; the teacher inference server is started externally by the test
# fixture (see tests/integration/test_reverse_text_rl_sft.py) on the same GPU.
# Trainer takes GPU 1. Training config mirrors `reverse_text/start.toml`.
# Smoke test for the RL-entrypoint sft algorithm (hard distillation).
# The policy inference deployment is launched by the rl entrypoint on GPU 0;
# the frozen sampling server is started externally by the test fixture (see
# tests/integration/test_reverse_text_rl_sft.py) on the same GPU. Trainer
# takes GPU 1. Training config mirrors `reverse_text/start.toml`.
max_steps = 5
max_steps = 15
seq_len = 2048
[model]
@@ -15,13 +15,25 @@ project = "reverse-text-ci"
name = "ci-rl-sft"
[orchestrator]
training_mode = "sft"
batch_size = 128
group_size = 16
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `default` (wraps the student tokenizer's
# apply_chat_template) so the CE target is faithful to the student's actual
# chat template. The stock `qwen3` renderer reimplements the Qwen format and
# injects an empty `<think></think>` block, which this model's custom template
# does not emit — corrupting the distillation target.
[orchestrator.renderer]
name = "qwen3"
name = "default"
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -39,12 +51,6 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
@@ -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]
+62
View File
@@ -0,0 +1,62 @@
# Algorithm — Debug Configs
Minimal end-to-end configs for the algorithms against bundled verifiers envs, using `PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT` as the policy.
| Config | Algorithm | Frozen model | Notes |
|---|---|---|---|
| `grpo.toml` | `grpo` | none | |
| `max_rl.toml` | `max_rl` | none | GRPO with mean-normalized advantages (maximum-likelihood RL) |
| `opd.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `opd_lora.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
| `sft_distill.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `sft_distill_lora.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
| `self_distill.toml` | `opsd` | none (self-distills against the live policy) | SDFT; demo from reverse-text's `answer` field |
| `echo.toml` | `echo` | none | multi-turn `alphabet-sort`; CE on observation tokens |
| `mixed_grpo_opd.toml` | `grpo` + `opd` (per env) | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | two envs, one run; heterogeneous batches (with/without `ref_logprobs`) |
The policy inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local frozen model (used by `opd*.toml`, `sft_distill.toml` / `sft_distill_lora.toml`, and `mixed_grpo_opd.toml`) is **not** auto-launched — start it manually on GPU 1.
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for `opd`, `[orchestrator.algo.sampling.source]` for `sft` — with `name` + `base_url`. `opsd` declares none (it self-distills against the live policy). prime-rl never hosts them; only the trainable policy's server is managed by the `rl` entrypoint.
## Start the local frozen model
Needed for `opd*.toml`, `sft_distill.toml` / `sft_distill_lora.toml`, and `mixed_grpo_opd.toml`:
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--server.port 8001 \
--gpu-memory-utilization 0.5 \
--model.enforce-eager
```
## Run the debug configs
Every config writes to the default `outputs/` directory, so running two back-to-back — or re-running one — fails with `FileExistsError`. Pass a distinct `--output-dir outputs/<algo>` per config (recommended for a sweep) or `--clean-output-dir` to wipe and restart.
```bash
# GRPO (no frozen model)
uv run rl @ configs/debug/algorithms/grpo.toml --output-dir outputs/grpo
# MaxRL (no frozen model)
uv run rl @ configs/debug/algorithms/max_rl.toml --output-dir outputs/max_rl
# OPD (needs the frozen model on port 8001)
uv run rl @ configs/debug/algorithms/opd.toml --output-dir outputs/opd
uv run rl @ configs/debug/algorithms/opd_lora.toml --output-dir outputs/opd_lora
# SFT distillation (needs the frozen model on port 8001)
uv run rl @ configs/debug/algorithms/sft_distill.toml --output-dir outputs/sft_distill
uv run rl @ configs/debug/algorithms/sft_distill_lora.toml --output-dir outputs/sft_distill_lora
# Self-distillation against the live policy (no frozen model)
uv run rl @ configs/debug/algorithms/self_distill.toml --output-dir outputs/self_distill
# ECHO (no frozen model; multi-turn env)
uv run rl @ configs/debug/algorithms/echo.toml --output-dir outputs/echo
# Mixed per-env algorithms: GRPO + OPD in one run (needs the frozen model on port 8001)
uv run rl @ configs/debug/algorithms/mixed_grpo_opd.toml --output-dir outputs/mixed_grpo_opd
```
See [docs/algorithms.md](../../../docs/algorithms.md) for what each algorithm does and how to author your own.
+50
View File
@@ -0,0 +1,50 @@
# ECHO on the multi-turn alphabet-sort env (bundled with verifiers): GRPO on
# action tokens + weighted CE on the env's observation tokens.
# uv run rl @ configs/debug/algorithms/echo.toml
max_steps = 20
seq_len = 4096
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "algorithms-debug"
name = "debug-echo"
[orchestrator]
batch_size = 32
group_size = 4
# alphabet-sort's feedback arrives as user messages, so train the user role
# instead of echo's tool default.
[orchestrator.algo]
type = "echo"
[orchestrator.algo.roles.user]
alpha = 0.1
[[orchestrator.train.env]]
id = "alphabet-sort"
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
[orchestrator.train.sampling]
max_completion_tokens = 512
# ECHO learns from observation tokens even when the GRPO advantage collapses
# to zero — keep zero-advantage rollouts in the batch.
[[orchestrator.post_batch_filters]]
type = "zero_advantage"
enforce = false
# Qwen3 finetune with the standard PI template patch; always re-emits prior
# <think> blocks, matched by the qwen3 renderer's preserve_all_thinking.
[orchestrator.renderer]
name = "qwen3"
preserve_all_thinking = true
[trainer.optim]
lr = 1e-6
[inference]
gpu_memory_utilization = 0.5
@@ -5,14 +5,16 @@ seq_len = 2048
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
project = "algorithms-debug"
name = "debug-rl"
[orchestrator]
training_mode = "rl"
batch_size = 128
group_size = 16
[orchestrator.algo]
type = "grpo"
[orchestrator.renderer]
name = "qwen3"
+43
View File
@@ -0,0 +1,43 @@
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "algorithms-debug"
name = "debug-max-rl"
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.algo]
type = "max_rl"
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -1,9 +1,12 @@
# Start the teacher inference server first (on a separate GPU):
# Mixed per-env algorithms in one run: a GRPO env and an OPD env, both on
# reverse-text. Exercises heterogeneous train batches — OPD samples ship
# ref_logprobs, GRPO samples don't, and both pack into the same micro batches.
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/opd.toml
# uv run rl @ configs/debug/algorithms/mixed_grpo_opd.toml
max_steps = 20
seq_len = 2048
@@ -12,14 +15,16 @@ seq_len = 2048
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-opd"
project = "algorithms-debug"
name = "debug-mixed-grpo-opd"
[orchestrator]
training_mode = "opd"
batch_size = 128
group_size = 16
[orchestrator.algo]
type = "grpo"
[orchestrator.renderer]
name = "qwen3"
@@ -28,9 +33,21 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-grpo"
[[orchestrator.train.env]]
id = "reverse-text"
name = "reverse-text-opd"
[orchestrator.train.env.algo]
type = "opd"
[orchestrator.train.env.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
[orchestrator.eval]
interval = 1
interval = 5
num_examples = 128
[orchestrator.eval.sampling]
@@ -39,16 +56,8 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -1,9 +1,9 @@
# Start the teacher inference server first (on a separate GPU):
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/sft.toml
# uv run rl @ configs/debug/algorithms/opd.toml
max_steps = 20
seq_len = 2048
@@ -12,13 +12,19 @@ seq_len = 2048
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-sft"
project = "algorithms-debug"
name = "debug-opd"
[orchestrator]
training_mode = "sft"
batch_size = 128
group_size = 4
group_size = 16
[orchestrator.algo]
type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
@@ -40,12 +46,6 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
@@ -1,9 +1,9 @@
# Start the teacher inference server first (on a separate GPU):
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/opd_lora.toml
# uv run rl @ configs/debug/algorithms/opd_lora.toml
max_steps = 20
seq_len = 2048
@@ -12,14 +12,21 @@ seq_len = 2048
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
project = "algorithms-debug"
name = "debug-opd-lora"
[orchestrator]
training_mode = "opd"
batch_size = 128
group_size = 16
[orchestrator.algo]
type = "opd"
[orchestrator.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.renderer]
name = "qwen3"
@@ -39,12 +46,6 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 1e-4
@@ -0,0 +1,49 @@
# Self-distillation (SDFT, https://arxiv.org/abs/2601.19897) against the live
# policy itself: the reference for each completion is the current model
# conditioned on the expert demonstration — no extra deployment needed.
# reverse-text carries the demonstration in its top-level `answer` field.
# uv run rl @ configs/debug/algorithms/self_distill.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "algorithms-debug"
name = "debug-self-distill"
[orchestrator]
batch_size = 32
group_size = 1
# reverse-text's demo lives in the "answer" column.
[orchestrator.algo]
type = "opsd"
demo_key = "answer"
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[trainer.optim]
lr = 3e-6
[inference]
gpu_memory_utilization = 0.5
+60
View File
@@ -0,0 +1,60 @@
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/algorithms/sft_distill.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "algorithms-debug"
name = "debug-sft"
[orchestrator]
batch_size = 128
group_size = 4
[orchestrator.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `default` (wraps the student tokenizer's
# apply_chat_template) so the CE target is faithful to the student's actual
# chat template. The stock `qwen3` renderer injects an empty `<think></think>`
# block this model's custom template never emits, corrupting the target.
[orchestrator.renderer]
name = "default"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -1,9 +1,9 @@
# Start the teacher inference server first (on a separate GPU):
# Start the frozen reference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/sft_lora.toml
# uv run rl @ configs/debug/algorithms/sft_distill_lora.toml
max_steps = 20
seq_len = 2048
@@ -12,17 +12,28 @@ seq_len = 2048
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
project = "algorithms-debug"
name = "debug-sft-lora"
[orchestrator]
training_mode = "sft"
batch_size = 128
group_size = 4
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
[orchestrator.algo]
type = "sft"
# sft's teacher IS the model it samples from.
[orchestrator.algo.sampling.source]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = ["http://localhost:8001/v1"]
# The student's renderer tokenizes the teacher's messages into the student's
# token space (backfill). Use `default` (wraps the student tokenizer's
# apply_chat_template) so the CE target is faithful to the student's actual
# chat template. The stock `qwen3` renderer injects an empty `<think></think>`
# block this model's custom template never emits, corrupting the target.
[orchestrator.renderer]
name = "qwen3"
name = "default"
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -40,12 +51,6 @@ max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 1e-4
@@ -9,7 +9,6 @@ project = "reverse-text-debug"
name = "debug-multi-env"
[orchestrator]
training_mode = "rl"
batch_size = 128
group_size = 16
+3 -2
View File
@@ -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
View File
@@ -5,3 +5,4 @@ batch_size = 2
[model]
seq_len = 1024
compile = "None"
+2 -1
View File
@@ -1,7 +1,8 @@
max_steps = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B"
name = "PrimeIntellect/Qwen3-0.6B"
compile = "None"
[data]
type = "fake"
-42
View File
@@ -1,42 +0,0 @@
# Training Mode — Debug Configs
Minimal end-to-end configs for the three training modes (`rl` / `opd` / `sft`) against the `reverse-text` env, using `PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT` as the student.
| Config | Mode | Teacher | Notes |
|---|---|---|---|
| `rl.toml` | `rl` | none | |
| `opd.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `opd_lora.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
| `sft.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `sft_lora.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
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
Needed for `opd*.toml` and `sft.toml` / `sft_lora.toml`:
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--server.port 8001 \
--gpu-memory-utilization 0.5 \
--model.enforce-eager
```
## Run the debug configs
```bash
# RL (no teacher)
uv run rl @ configs/debug/training_modes/rl.toml
# OPD (needs teacher on port 8001)
uv run rl @ configs/debug/training_modes/opd.toml
uv run rl @ configs/debug/training_modes/opd_lora.toml
# SFT hard distill (needs teacher on port 8001)
uv run rl @ configs/debug/training_modes/sft.toml
uv run rl @ configs/debug/training_modes/sft_lora.toml
```
See [docs/training.md](../../docs/training.md#training-modes-rl--opd--sft-via-orchestrator) for what each mode does.
-1
View File
@@ -32,7 +32,6 @@ freq = 1
[trainer.model.compile]
[orchestrator]
training_mode = "rl"
batch_size = 256
rollouts_per_example = 8
max_off_policy_steps = 32
-1
View File
@@ -15,7 +15,6 @@ name = "gsm8k-v1"
name = "Qwen/Qwen3-0.6B"
[orchestrator]
training_mode = "rl"
batch_size = 512
group_size = 16
-1
View File
@@ -14,7 +14,6 @@ name = "v1"
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
training_mode = "rl"
batch_size = 128
group_size = 16
+1 -1
View File
@@ -8,7 +8,7 @@ To test the elastic inference pool without having the `rl` entrypoint start the
uv run rl @ examples/alphabet_sort/rl_elastic.toml
```
The config uses `[orchestrator.client.elastic]` with `hostname = "localhost"` and `port = 8000`. The orchestrator will wait for at least one ready server before starting rollouts.
The config uses `[orchestrator.model.client.elastic]` with `hostname = "localhost"` and `port = 8000`. The orchestrator will wait for at least one ready server before starting rollouts.
2. **Start the inference server manually** (in a separate terminal or on another machine):
+1 -1
View File
@@ -35,7 +35,7 @@ group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 768
[orchestrator.client.elastic]
[orchestrator.model.client.elastic]
hostname = "localhost"
port = 8000
sync_interval = 5.0
-18
View File
@@ -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
```
-52
View File
@@ -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
+50
View File
@@ -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"
+2 -1
View File
@@ -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
-41
View File
@@ -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]]
name = "aime2024"
taskset = { id = "aime24-v1" }
num_examples = 30
group_size = 4
[trainer.model]
seq_len = 4096
[inference.model]
max_model_len = 2048
+2 -1
View File
@@ -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
+2 -1
View File
@@ -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
+1 -1
+4 -2
View File
@@ -139,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.
+200 -101
View File
@@ -1,25 +1,151 @@
# Algorithms
This page covers the math and the configurable algorithmic components: how off-policy training works, the default loss and advantage functions, how to plug in your own, the filters applied between rollout and training, and how multi-turn rollouts get merged into training samples.
This page covers the math and the configurable algorithmic components: the algorithm abstraction and its algorithms, how off-policy training works, the loss components and advantage functions, how to plug in your own, the filters applied between rollout and training, and how multi-turn rollouts get merged into training samples.
## Table of Contents
- [The Algorithm Abstraction](#the-algorithm-abstraction)
- [Model References](#model-references)
- [The Algorithms](#the-algorithms)
- [Customizing Components](#customizing-components)
- [Per-Env Algorithms](#per-env-algorithms)
- [The Algorithm Classes](#the-algorithm-classes)
- [Async / Off-Policy Training](#async--off-policy-training)
- [Loss](#loss)
- [Default Loss](#default-loss)
- [Loss Components](#loss-components)
- [Default RL Loss](#default-rl-loss)
- [Custom Loss](#custom-loss)
- [Advantage](#advantage)
- [Default Advantage](#default-advantage)
- [Custom Advantage](#custom-advantage)
- [Authoring an Algorithm](#authoring-an-algorithm)
- [Reference Scoring](#reference-scoring)
- [Filters](#filters)
- [Difficulty Pools](#difficulty-pools)
- [Online Difficulty Filtering](#online-difficulty-filtering)
- [Multi-Turn Trajectories](#multi-turn-trajectories)
- [Extension Property](#extension-property)
- [Best-Effort Interleaving](#best-effort-interleaving)
- [Renderers](#renderers)
- [Discontinuous Trajectories](#discontinuous-trajectories)
## The Algorithm Abstraction
A training algorithm in `prime-rl` is configured under `[orchestrator.algo]`, where **`type` names the algorithm** (`grpo`, `opd`, `sft`, …) and the class defaults are its vetted setting. It has two parts:
1. **Sampling** (`algo.sampling`) — how train rollouts are produced: which model generates them. `source` is a [model reference](#model-references): `"policy"` (the live policy, the default) or an inline frozen hosted model. Group sizing stays on the env config (`group_size`).
2. **The per-token training signal** — credit assignment and loss routing, fused; the algorithm's own parameters sit directly on `algo`. One mapping from a finalized rollout to per-token *(loss component, weight)* pairs — the credit a token gets and the loss that consumes it are two coordinates of the same output. Group-relative algorithms compute credit on the orchestrator and ship per-token advantage streams; reference-KL algorithms query a reference model at batch-ship time (bounded concurrency) and ship its prefill logprobs for the trainer to evaluate against the live policy. The `type` determines which loss component consumes the action tokens (`rl` / `ce` / `ref_kl`) and what happens to env-provided observation tokens in multi-turn rollouts (masked out by default; `echo` trains on them with weighted CE).
The trainer is algorithm-blind: the loss is a sum of three components (rl, ce, ref_kl), each normalized by its own global token count; per-token streams ship on the wire (the `rl_weights` / `ce_weights` / `ref_kl_weights` component weights plus the `advantages` stream on each training sample) and the trainer just executes them. Adding an algorithm never touches the dispatcher, packer, or trainer hot path.
### Model References
`prime-rl` hosts exactly one model: the trainable policy (`[orchestrator.model]`). Every other model an algorithm uses is an external OpenAI-compatible endpoint, declared *inline on the component that uses it*. A model reference is either the string `"policy"` (the live policy) or a frozen hosted model (`name` + `base_url`):
```toml
[orchestrator.algo]
type = "opd"
[orchestrator.algo.teacher] # opd's teacher: the frozen model it scores against
name = "Qwen/Qwen3-32B"
base_url = ["http://localhost:8001/v1"]
```
Model *roles* are algorithm-local vocabulary — each algorithm names its reference on the field where the model is actually used, and there is no shared `teacher` slot. `opd` declares a `teacher` field (the frozen model whose reverse KL the policy distills toward); `sft`'s teacher *is* its `sampling.source` (the frozen model it imitates); `opsd` self-distills against the live policy and names no model at all. No role exists outside the algorithm that declares it: the dispatcher, sink, and trainer branch on liveness alone, never on what an algorithm calls a model.
So for `opd` set `[orchestrator.algo.teacher]`; for `sft` set `[orchestrator.algo.sampling.source]`; `opsd` needs neither. `opd`'s teacher must be a frozen endpoint — it is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero); `opsd`'s teacher *is* the live policy by definition (self-distillation conditioned on a demonstration), so it exposes no reference to configure.
Liveness is a property of the reference, not of any role: rollouts sampled from `"policy"` get version-salted prefix caches, carry sampling logprobs for importance ratios, and age off-policy as weights update; rollouts and scores from frozen models get a stable prefix cache and never go stale. Frozen models are externally hosted (`base_url` is required) — `prime-rl` never launches or updates them, and each env's algorithm builds its own client pool to the endpoints it declares.
### The Algorithms
The `algo.type` names the algorithm, and each type's class defaults are its vetted setting — picking a type with no other keys IS the algorithm:
```toml
[orchestrator.algo]
type = "grpo" # the default
```
| `type` | Sampling | Loss | What it is |
|---|---|---|---|
| `grpo` | policy | `rl` on actions | Standard group-relative RL. |
| `max_rl` | policy | `rl` on actions | MaxRL ([arXiv:2602.02710](https://arxiv.org/abs/2602.02710)): GRPO's centered reward normalized by the group **mean** instead of the standard deviation — the gradient is unbiased for the order-`group_size` truncation of the maximum-likelihood objective, upweighting hard examples like `1/p`. |
| `opd` | policy | `ref_kl` on actions | On-policy distillation ([Thinking Machines](https://thinkingmachines.ai/blog/on-policy-distillation/)): the policy samples, per-token reverse KL against a reference model as the gradient signal. Needs a `teacher`. |
| `sft` | *(the teacher)* | `ce` on actions | Hard distillation: a frozen model generates rollouts, the policy trains with CE on its tokens. Needs a frozen `sampling.source` (the teacher it samples from). |
| `opsd` | policy | `ref_kl` on actions | SDFT ([arXiv:2601.19897](https://arxiv.org/abs/2601.19897)): the model is its own reference, conditioned on an expert demonstration. The teacher *is* the live policy (the paper's setting, no extra deployment) — no model to configure. |
| `echo` | policy | `rl` on actions + weighted `ce` on observations | ECHO: standard GRPO plus a cross-entropy loss on env-provided tokens already present in the rollout, selected by message role (needs the renderer's role attribution). Defaults to tool-response bodies at `alpha = 0.1` (ECHO's λ); set `roles` to train other roles, each at its own weight. |
### Customizing Components
Every key beyond `type` is visibly your own assembly — there is no preset layer to diverge from. The vetted setting is the class defaults; what you set is what runs:
```toml
# echo on tool AND user feedback tokens, each at its own weight.
# Setting any role replaces the whole table.
[orchestrator.algo]
type = "echo"
[orchestrator.algo.roles.tool]
alpha = 0.25
[orchestrator.algo.roles.user]
alpha = 0.05
```
A new algorithm is a named class in code, not a config that points at an import path — see [Authoring an Algorithm](#authoring-an-algorithm).
Echo also takes an optional user-supplied token filter that narrows the role selection per rollout — e.g. dropping warning lines from tool output, or tokens the sampler found unlikely:
```toml
[orchestrator.algo.filter]
import_path = "my_module.drop_warnings"
kwargs = { patterns = ["WARNING"] }
```
```python
# my_module.py — sees the raw rollout (message text, sampling logprobs);
# returns one keep-mask per trainable branch, spanning that branch's
# token_ids. False = never echo-trained.
def drop_warnings(rollout, *, patterns: list[str]) -> list[list[bool]]: ...
```
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and aborts after repeated zero-trainable batches), not at config time.
### Per-Env Algorithms
Both components resolve per environment. Each env inherits `[orchestrator.algo]` unless it sets its own, so a single run can mix algorithms across envs — e.g. GRPO on math, ECHO on a terminal env:
```toml
[orchestrator.algo]
type = "grpo"
[[orchestrator.train.env]]
id = "math-env" # inherits grpo
[[orchestrator.train.env]]
id = "terminal-env"
algo = { type = "echo" } # this env runs its own algorithm
```
### The Algorithm Classes
At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_rl.orchestrator.sampler`) from the `sampling` component — the pool rollouts are generated from, and the home of future sampling strategies like replay buffers or branching — and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
| `grpo` | `GRPOAlgorithm` | `score_group`: group-norm credit (optional length penalty) |
| `echo` | `EchoAlgorithm` | `score_rollout`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
| `max_rl` | `MaxRLAlgorithm` | `score_group`: mean-normalized group credit |
| `opd` | `OPDAlgorithm` | `score_rollout`: own-context prefill under the teacher |
| `opsd` | `OPSDAlgorithm` | `score_rollout`: demo-conditioned prefill under the live policy |
| `sft` | `SFTDistillAlgorithm` | `score_group`: group-norm credit (feeds filters) |
Each class owns its hooks outright — reading one top to bottom reads the algorithm, and everything on the class is an override point. The two hooks are one scope-and-timing ladder — the wider scope is unlocked by a later barrier, so the two axes coincide. Each is handed the `Rollout` directly — the env's typed trace (`reward`, `nodes`, `num_turns`, ...) with `samples` attached, plus `assign_advantages` to write credit:
- `async score_rollout(rollout)` — one rollout, **on arrival** (as it's tokenized, before its group is complete): rollout-local credit (`rollout.assign_advantages(...)`, scalar broadcast or per-token), observation ce weights, **or** model I/O — query a reference pool (e.g. `self.teacher_pool`, connected in `setup()` via `self.connect(...)`, or the live `self.policy_pool` for opsd) and attach per-token results (e.g. teacher logprobs) with bounded concurrency. No siblings. `echo` weights observation tokens here, identifying env-provided observation nodes by their non-sampled status and source step role attribution, applying the optional user filter, and writing the `ce_weights` stream. Model I/O runs *before* the pre-batch filters, so it pays compute on rollouts that may then be filtered out.
- `score_group(group)` — the cohort, **before filtering** (filters read the streams), synchronous: group-relative credit (GRPO/MaxRL baselines). `group` is a list of `Rollout`.
The pipeline drives the hooks through two non-virtual methods it never looks inside: `algorithm.finalize_rollout(rollout)` per arrival (rollout-local scoring + reference I/O) and `algorithm.finalize_group(rollouts)` per group (scoring + wire stamping; after this the records are frozen — groups die at stamping). Sample construction (interleaving) is pure pipeline — observation-token provenance is available through structural attribution (`node.sampled`, `node.is_content`) for any algorithm that trains on env-provided tokens.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy pool (`self.policy_pool`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
## Async / Off-Policy Training
`prime-rl` is asynchronous by default. The trainer and inference always run one step overlapped: while the trainer is producing $\pi_n$ from rollouts at step $n$, inference is already generating the rollouts for step $n+1$ using $\pi_{n-1}$. With matched trainer and inference step times this produces fully-overlapped pipeline parallelism — neither side ever idles.
@@ -35,7 +161,21 @@ Step indices are 0-indexed so the gap holds at startup — inference is exactly
## Loss
### Default Loss
### Loss Components
The training loss is a **sum of three components**, each with its own per-token weight stream and its own normalization:
$$
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
$$
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the group-relative algorithms (`grpo`, `max_rl`, and `echo`'s action tokens).
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens, so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
### Default RL Loss
The default RL loss is a DPPO policy-gradient term combined with a KL regularizer similar to Kimi-K2.5. For each prompt $x_j$ we sample a group of $G$ rollouts $\{y_i\}_{i=1}^G$, score them to get $s_i$, then optimize:
@@ -66,20 +206,14 @@ The knobs (under `[trainer.loss]` with `type = "default"`):
| Knob | Default | What it does |
|---|---|---|
| `dppo_mask_low` / `dppo_mask_high` | 0.2 / 0.2 | Lower / upper thresholds for DPPO-style token-level masking. |
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 for pure distillation (no RL signal). |
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
The trainer dispatches automatically based on the batch's training mode (set by the orchestrator via `orchestrator.training_mode`):
- `rl` mode → DPPO + KL with the advantage signal.
- `opd` mode → KL distillation against the teacher's per-token logprobs. The teacher must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
- `sft` mode → standard token-level NLL on teacher-generated rollouts.
Set `[trainer.loss] type = "default"` and configure via the knobs above. SFT and OPD modes ignore the policy-gradient–specific fields.
Set `[trainer.loss] type = "default"` and configure via the knobs above. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
### Custom Loss
The loss is computed **per sequence**: you write a function that takes one sequence's tensors and returns a scalar loss. The trainer iterates and aggregates.
`[trainer.loss] type = "custom"` replaces the `rl` component. The loss is computed **per sequence**: you write a function that takes one sequence's tensors and returns a scalar loss. The trainer iterates and aggregates. `inputs.loss_mask` selects exactly the rl member tokens (for a plain GRPO run, all trainable tokens).
```python
# my_module.py
@@ -116,9 +250,10 @@ The dataclasses:
class LossInputs:
trainer_logprobs: Float[Tensor, "seq"] # current policy
inference_logprobs: Float[Tensor, "seq"] # rollout-time policy
teacher_logprobs: Float[Tensor, "seq"] | None # only set in OPD mode
ref_logprobs: Float[Tensor, "seq"] | None # set by reference-scoring algorithms
advantages: Float[Tensor, "seq"]
loss_mask: Bool[Tensor, "seq"]
loss_mask: Bool[Tensor, "seq"] # this component's member tokens
loss_weights: Float[Tensor, "seq"] | None # the component's weight stream (None = 1.0)
@dataclass
class LossOutputs:
@@ -130,68 +265,71 @@ Anything you put in `metrics` is averaged across sequences and logged with the o
## Advantage
The per-token training signal is set by `algo.type` and the [algorithm](#the-algorithm-abstraction)'s parameters — every signal is a per-token advantage stream, varying in evaluation site (orchestrator vs. trainer). The `algo.type` values:
| Type | Component | Effect |
|---|---|---|
| `grpo` | `rl` | Group-norm: reward minus per-group baseline, optional length penalty. |
| `max_rl` | `rl` | Mean-normalized group credit (maximum-likelihood RL). |
| `echo` | `rl` + `ce` | Group-norm on action tokens, plus weighted CE on env-provided tokens selected by message role (each role's `alpha` is its ECHO λ), optionally narrowed by a user filter. |
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`model`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream; `group_size` only fans out sampling. |
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream. |
| `sft` | `ce` | Cross-entropy on the sampled tokens. Assigns no advantage — trains on every sampled token. |
### Default Advantage
The default advantage is per-group reward minus per-group baseline (DR-GRPO without std normalization). For each prompt's group of `group_size` rollouts, every token in rollout $i$ receives advantage $s_i - \bar{s}$ where $\bar{s}$ is the group mean.
This is intentionally simple — it does the right thing for most envs. Switch to a [custom advantage](#custom-advantage) when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …).
This is intentionally simple — it does the right thing for most envs. Write a named algorithm class when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …) — see [Authoring an Algorithm](#authoring-an-algorithm).
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:
Two built-in **length penalties** (`length_penalty` on the `grpo`-family algorithms) can be layered on top to discourage rambling: `tokens` penalizes long completions by weighted token cost, `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
```
[orchestrator.algo]
type = "grpo"
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
[orchestrator.algo.length_penalty]
type = "tokens"
```
### Custom Advantage
### Authoring an Algorithm
Advantages are computed **per group**. You write a function that takes one group of rollouts and returns one advantage scalar per rollout. The orchestrator handles groups of varying size automatically — partial-group training kicks in when some rollouts in a group errored.
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class. The hook receives the group's `Rollout`s (each the env's typed `verifiers.Trace` — turns, tool calls, metadata in `info` — with `samples` attached) and writes credit via `assign_advantages`:
```python
# my_module.py
import statistics
from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
# src/prime_rl/orchestrator/algo/my_algo.py
import torch
def normalized_advantage(inputs: AdvantageInputs, eps: float = 1e-8) -> AdvantageOutputs:
rewards = [r["reward"] for r in inputs.rollouts]
mean = statistics.fmean(rewards)
std = statistics.pstdev(rewards) if len(rewards) > 1 else 0.0
return AdvantageOutputs(advantages=[(r - mean) / (std + eps) for r in rewards])
from prime_rl.orchestrator.algo.base import Algorithm
class MyAlgorithm(Algorithm):
async def score_group(self, group):
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
advantages = ... # one value per rollout
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
rollout.assign_advantages(advantage)
```
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick the hook by *when* your signal is ready: `score_rollout` for per-arrival credit or credit that needs a model call (it's `async`), `score_group` for group-relative credit (GRPO/MaxRL). `assign_advantages` takes a scalar (broadcast over the rollout's trainable tokens — the common case) or a full-length per-token list aligned to the concatenated sample token_ids (process rewards, step-level credit; `0.0` off-mask). Shared math like `efficiency_shaping` lives in `prime_rl.orchestrator.algo.advantage`.
Each per-token list must match the rollout's completion-token count exactly — validated loudly when the view writes it. Advantage-based filters and metrics derive from the streams (the zero-advantage filter checks for all-zero streams; logged distributions use per-rollout means). Signals that depend on the live policy's weights (like OPD's reverse KL) cannot be precomputed here; those are reference-scoring algorithms, evaluated in the trainer.
### Reference Scoring
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_rollout`: as each rollout arrives they query a reference (the sample's own context for `opd`, the demo-conditioned context for `opsd`) and attach per-token reference logprobs to each sample. Rollouts are consumed serially by the orchestrator's main loop and each carries only a handful of samples, so the in-flight request count is naturally bounded — no explicit concurrency cap:
- `opd` — score each sample's own context under the `teacher` (a frozen [model reference](#model-references)) via prefill; fills `ref_logprobs` for the `ref_kl` loss component (on-policy distillation). The `teacher` is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero).
- `opsd` — SDFT: prepend an expert demonstration as a leading system message (`template`, with a `{demonstration}` placeholder) and score the sample under that demo-conditioned context. The sample is scored verbatim (`hint_block + token_ids`, slicing the hint's logprobs back off), so the join is BPE-clean and it's robust to tool/multimodal prompts and any number of turns. The scoring reference *is* the live policy — self-distillation names no teacher. opsd builds its own renderer to tokenize the hint block: the tokenizer is always the live policy's (not configurable — there is no separate model), and only the `renderer` family is settable (defaults to `"auto"`, resolved from the policy tokenizer; set it to match a non-auto policy renderer). The demonstration is read from the example's `info[demo_key]`, falling back to a top-level rollout field of the same name (e.g. `answer`).
```toml
[orchestrator.advantage]
type = "custom"
import_path = "my_module.normalized_advantage"
kwargs = { eps = 1e-8 }
[orchestrator.algo]
type = "opsd"
demo_key = "demonstration"
```
`AdvantageInputs.rollouts` is a list of `verifiers.RolloutOutput`, so you have access to the full rollout (turns, tool calls, custom metadata) — not just the reward. Use this for anything reward-shaping-like that needs trajectory context.
### Per-Env Advantage
`advantage` can be set per training environment. Each env inherits the top-level `[orchestrator.advantage]` when it doesn't set its own, so mixed-env runs can give each env its own advantage computation:
```toml
[orchestrator.advantage]
type = "default" # the default every env inherits unless it overrides
[[orchestrator.train.env]]
id = "math-env" # inherits the default above
[[orchestrator.train.env]]
id = "agent-env"
advantage = { type = "custom", import_path = "my_module.normalized_advantage" }
```
Scoring runs at arrival, *before* the pre-batch filters, so a rollout that is later filtered still cost its reference compute — accepted for the simpler one-rollout-at-a-time shape (advantage-based filters never fire for opd/opsd anyway, since neither assigns an advantage).
## Filters
@@ -203,58 +341,19 @@ Filters drop rollouts between scoring and training. Built-ins (composable):
| `repetition` | Drops rollouts with high n-gram repetition. |
| `zero_advantage` | Drops rollouts whose advantage is zero, so the trainer doesn't waste tokens on them. |
The default `[orchestrator]` config already includes all three filters with their defaults. To override, set `filters` explicitly — the list replaces the defaults wholesale:
The default `[orchestrator]` config registers all three in both filter slots: `post_batch_filters` enforce by default (flagged rollouts are recorded but not shipped to the trainer), while `pre_batch_filters` run in monitor mode (`enforce = false`); flip `enforce = true` there to drop matching rollouts before they consume a slot in the batch. Setting a slot replaces its defaults wholesale:
```toml
[[orchestrator.filters]]
[[orchestrator.post_batch_filters]]
type = "zero_advantage"
[[orchestrator.filters]]
[[orchestrator.post_batch_filters]]
type = "repetition"
threshold = 0.4
```
Filtered rollouts still appear in W&B distributions, just not in the trainer batch — useful for spotting whether filtering is doing its job.
## Difficulty Pools
Difficulty pools gradually retire problems the model has solved or never solves. After each rollout, the average reward across a problem's group is compared to two thresholds:
- `buffer.easy_threshold` — at or above this, the problem moves into the `easy` pool and is no longer sampled.
- `buffer.hard_threshold` — at or below this, the problem moves into the `hard` pool and is no longer sampled.
- Otherwise the problem stays in `normal` and remains in the sampling rotation.
Pool assignments persist across checkpoints (`easy_examples.jsonl` / `hard_examples.jsonl` under each step's orchestrator checkpoint). When you resume — or want to broaden the curriculum mid-run — `buffer.easy_fraction` / `buffer.hard_fraction` randomly lift that fraction of pooled problems back into `normal` so they re-enter sampling.
```toml
[orchestrator.buffer]
easy_threshold = 0.95
hard_threshold = 0.05
easy_fraction = 0.0 # default; bump on resume to bring some easy problems back
hard_fraction = 0.0 # default; bump on resume to bring some hard problems back
```
Watch `pool/{env}/{easy,normal,hard}` (current pool ratios) and `evicted_examples/{env}/{easy,hard}` (per-step eviction rate).
## Online Difficulty Filtering
Online difficulty filtering (ODF) drops collapsed-advantage groups on the way *into* the buffer. Set `buffer.online_difficulty_filtering = true` (default `false`) to enable:
- Average reward across the group is **0.0** (every rollout failed) → drop the group, count under `filtered_rollouts/{env}/hard`.
- Average reward **1.0** (every rollout succeeded) → drop, count under `filtered_rollouts/{env}/easy`.
- Otherwise → into the buffer.
These are exactly the groups whose within-group advantage collapses to zero — DR-GRPO produces no gradient signal for them, so the trainer would burn step time on tokens it can't learn from.
```toml
[orchestrator.buffer]
online_difficulty_filtering = true
```
**Tradeoff: trainer stability vs. inference speed.** With ODF on, every rollout that reaches the trainer carries non-zero advantage — each trainer step's effective batch is predictable and the gradient signal is denser. The cost is paid on the inference side: rollouts get produced and then thrown away, so the orchestrator has to oversample to keep the trainer fed. If the orchestrator is your bottleneck (`time/wait_for_batch` high on the trainer), ODF can starve the loop. Bump `orchestrator.oversampling_factor` so inference produces enough groups per step to absorb the drops.
ODF is orthogonal to the [pools](#difficulty-pools): ODF reacts to the *current* group's reward distribution, the pools track the *running* per-problem average. Many configs use both — ODF for per-step density, pools for long-horizon curriculum cleanup.
## Multi-Turn Trajectories
Multi-turn rollouts (tool use, browser environments, long conversations) used to be stitched into a single fake "single-turn" sample, which silently corrupted the importance ratio when chat templates didn't roundtrip. Since [`verifiers` v0.1.8](https://github.com/PrimeIntellect-ai/verifiers/releases/tag/v0.1.8), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
+4 -2
View File
@@ -189,12 +189,12 @@ Both backends support the 2 most important things:
### Routing policies
The 2 policies you might want to configure are:
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - this works by hashing a request header to determine where to route the request to. You can configure what to hash by setting
`orchestrator.student.client.extra_headers_from_state` to the header the `router` expects to be set.
`orchestrator.model.client.extra_headers_from_state` to the header the `router` expects to be set.
We set it to a sensible default, that works with all verifiers environments.
```toml
[orchestrator.student.client.extra_headers_from_state]
[orchestrator.model.client.extra_headers_from_state]
X-Session-ID = "trajectory_id" # this is the default - each rollout has a unique trajectory_id and router expects X-Session-ID
```
@@ -245,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
+17 -30
View File
@@ -41,7 +41,7 @@ uv run rl @ rl.toml \
--inference.parallel.dp 6
```
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next, teacher last. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
For quick A/B ablations on the same node, run two RL instances side-by-side in separate tmux sessions, each pinned to half the GPUs and a separate inference port:
@@ -54,7 +54,7 @@ CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --output-dir outputs/exp1
bash scripts/tmux.sh -s exp2 -o outputs/exp2
CUDA_VISIBLE_DEVICES=2,3 uv run rl @ rl.toml \
--inference.server.port 8001 \
--orchestrator.client.base-url http://localhost:8001/v1 \
--orchestrator.model.client.base-url http://localhost:8001/v1 \
--output-dir outputs/exp2
```
@@ -92,10 +92,12 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is <= 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
```toml
[trainer.model]
impl = "custom"
ep = 8 # EP degree; must divide num_experts
ep = 8 # explicit EP degree; must divide num_experts
ep_comm_backend = "torch" # or "deepep"
```
@@ -121,7 +123,7 @@ cp_style = "ulysses" # "ring"
| `trainer.model.ac.mode = "selective"` | medium | small |
| `trainer.model.ac_offloading` | extra | a bit more |
Enable selective AC (custom impl only) for the best memory/throughput tradeoff:
AC and AC offloading are enabled by default (full mode). For the best memory/throughput tradeoff, switch to selective AC (custom impl only):
```toml
[trainer.model.ac]
@@ -129,55 +131,40 @@ mode = "selective"
targets = ["norm", "attn_proj"] # see Reference for the full list per architecture
```
We reccomend also using `ac_offloading` and `ac_offloading.max_inflight_activations = 5` to further reduce the memory footprint in tradeoff for some throughput. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput:
```toml
[trainer.model.ac_offloading]
max_inflight_activations = 5
```
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
### Optimizer Offloading
Offloading optimizer states to CPU is a near-free memory win at low GPU counts:
Offloading optimizer states to CPU is enabled by default (`optim_cpu_offload = true`) — a near-free memory win at low GPU counts:
```toml
[trainer.optim]
# any optimizer type
type = "adamw"
[trainer.model]
optim_cpu_offload = true
optim_cpu_offload = true # already the default
```
Mutually exclusive with `fsdp_cpu_offload`. Also incompatible with `trainer.max_concurrent_runs > 1` (multi-tenant training). Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
Mutually exclusive with `fsdp_cpu_offload`. Also incompatible with `trainer.max_concurrent_runs > 1` (multi-tenant training) — set `optim_cpu_offload = false` for multi-run. Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
### LM Head Chunking
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization:
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization. It defaults to `1024` for RL training:
```toml
[trainer.model]
fused_lm_head_token_chunk_size = "auto" # picks 8192 for RL
# or explicit:
# fused_lm_head_token_chunk_size = 1024 # smaller = lower memory, more launches
# fused_lm_head_token_chunk_size = "disabled" # default; vanilla LM head
fused_lm_head_token_chunk_size = 1024 # default
# fused_lm_head_token_chunk_size = "disabled" # vanilla LM head
```
`auto` is a safe starting point for RL. Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. Only available with `model.impl = "custom"`, and currently RL-only — the SFT trainer rejects integer values.
Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. SFT training silently disables this (not supported yet). Only available with `model.impl = "custom"`.
## Memory-Tight Recipe
The kitchen-sink config for fitting large MoE on limited GPUs at acceptable throughput:
The kitchen-sink config for fitting large MoE on limited GPUs at acceptable throughput. AC, AC offloading, compile, fused LM head chunking, optimizer offload, and EP auto-resolution are on by default — only CP needs to be set explicitly (and EP overridden if auto-resolution is not desired):
```toml
[trainer.model]
impl = "custom"
fused_lm_head_token_chunk_size = 1024
ep = 8
cp = 2
optim_cpu_offload = true
[trainer.model.compile]
[trainer.model.ac]
freq = 1
@@ -186,7 +173,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
@@ -237,7 +224,7 @@ gpus_per_node = 8
Full multi-node configs ship in [`examples/multinode/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/multinode):
- [`rl.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/multinode/rl.toml) — two-node RL run with NCCL weight broadcast on a 30B MoE student.
- [`rl.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/multinode/rl.toml) — two-node RL run with NCCL weight broadcast on a 30B MoE policy.
- [`sft.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/multinode/sft.toml) — two-node SFT against the same model.
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), and the launcher prints one URL per node. Front the URLs with a router or point clients at any of them.
+18 -13
View File
@@ -1,6 +1,6 @@
# Training
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer, the SFT trainer, and the related on-policy distillation mode. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md).
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md).
> **AI agents working in this repo:** the equivalent runbooks are at [`skills/training/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/skills/training) — top-level routing in [`skills/training/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/SKILL.md), launch details in [`skills/training/start-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/start-run/SKILL.md), and check-in / restart procedures in [`skills/training/monitor-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/monitor-run/SKILL.md).
@@ -10,7 +10,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover
- [RL Trainer](#rl-trainer)
- [Launch](#launch)
- [Useful Knobs](#useful-knobs)
- [Training Modes (RL / OPD / SFT)](#training-modes-rl--opd--sft)
- [Algorithms](#algorithms)
- [Important Metrics](#important-metrics)
- [SFT Trainer](#sft-trainer)
- [Dataset Format](#dataset-format)
@@ -59,7 +59,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | How many distinct policies may have contributed to one rollout before it's discarded (default 8). The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `errored_rollouts` and `mismatch_kl/all/mean` when tuning. |
| `orchestrator.training_mode` | `rl` (default), `opd`, or `sft`. See [Training modes](#training-modes-rl--opd--sft). |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
| `[[orchestrator.train.env]]` | Training environments. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Environments](configuration.md#environments-orchestratortrainenv). |
| `[[orchestrator.eval.env]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
@@ -81,24 +81,29 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
| `--dry-run` | Resolve + validate the full config, write per-process TOMLs to `<output_dir>/configs/`, and exit without launching. The fastest way to debug a misbehaving config. |
### Training Modes (RL / OPD / SFT)
### Algorithms
The RL entrypoint supports three training modes, switched via `orchestrator.training_mode`:
The RL entrypoint supports several training algorithms, switched via `[orchestrator.algo]`'s `type` (see [Algorithms](algorithms.md#the-algorithm-abstraction) for the full reference, model references, and per-algorithm customization):
| Mode | Student | Teacher | Use case |
|---|---|---|---|
| `rl` | Required | Forbidden | Standard RL |
| `opd` | Required | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): student generates rollouts, trainer minimizes KL to teacher logprobs |
| `sft` | Required | Required, any OpenAI-compatible endpoint | Hard-distill: teacher generates rollouts, student trains on them |
| `algo.type` | Frozen model | Use case |
|---|---|---|
| `grpo` (default) | None | Standard group-relative RL |
| `max_rl` | None | [MaxRL](https://arxiv.org/abs/2602.02710): GRPO with mean-normalized advantages (maximum-likelihood RL) |
| `opd` | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): the policy generates rollouts, the trainer minimizes per-token reverse KL to a reference model |
| `sft` | Required, any OpenAI-compatible endpoint | Hard-distill: a frozen model generates rollouts, the policy trains on its tokens |
| `opsd` | None — the live policy is its own reference (no deployment) | [SDFT](https://arxiv.org/abs/2601.19897): the model is its own reference conditioned on expert demonstrations |
| `echo` | None | GRPO plus cross-entropy on env-observation tokens |
The `rl` entrypoint only manages student-policy inference. For OPD and (local-vLLM) SFT, start the teacher inference server manually and point `[orchestrator.teacher.client]` at it:
A new algorithm is a named class in code, not a config — see [Algorithms § Authoring an Algorithm](algorithms.md#authoring-an-algorithm).
Frozen models are declared inline on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for `opd` (the frozen model scored against), `[orchestrator.algo.sampling.source]` for `sft` (the model it samples from) — each with `name` + `base_url`. `opsd` declares no frozen model: it self-distills against the live policy. The `rl` entrypoint only manages policy inference — start frozen-model servers yourself and point `base_url` at them:
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name <teacher> --server.port 8001
--model.name <frozen-model> --server.port 8001
```
The standalone `uv run sft` entrypoint is the more traditional SFT path — pure dataset-based, no teacher, no orchestrator. Use `orchestrator.training_mode = "sft"` only when you want a teacher to generate the supervision on the fly.
The standalone `uv run sft` entrypoint is the more traditional SFT path — pure dataset-based, no orchestrator. Use the `sft` algorithm only when you want a frozen model to generate the supervision on the fly.
### Important Metrics
-3
View File
@@ -108,9 +108,6 @@ 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
+1 -1
View File
@@ -66,7 +66,7 @@ group_size = 16
oversampling_factor = 3
max_off_policy_steps = 16
[orchestrator.student.model]
[orchestrator.model]
name = "zai-org/GLM-5-FP8"
[orchestrator.eval]
+1 -1
View File
@@ -10,7 +10,7 @@ dependencies = [
"renderers>=0.1.8.dev28",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.1.15.dev388",
"verifiers>=0.1.15.dev390",
]
[build-system]
@@ -0,0 +1,326 @@
"""Algorithm abstraction: sampling and the per-token training signal.
An algorithm is a named, self-contained config — a discriminated union keyed
on ``type`` (``grpo``, ``max_rl``, ``opd``, ``opsd``, ``sft``, ``echo``).
The bundle *is* the algorithm: each variant carries
its sampling component and its credit-assignment / loss-routing parameters,
and its class defaults are the vetted setting — ``type = "opd"`` with a
teacher IS on-policy distillation; any key you set is visibly your own
assembly. There is no separate ``advantage`` sub-component and no preset layer.
Each algorithm fixes two things:
1. **Sampling** — which model generates train rollouts. ``sampling.source`` is
a model reference: ``"policy"`` (the live policy) or an inline frozen hosted
model.
2. **The per-token training signal** — credit assignment and loss routing,
fused: one mapping from a finalized rollout to per-token ``(loss component,
weight)``. Group-relative algorithms compute scalars on the orchestrator and
ship numbers; reference-KL algorithms ship reference prefill logprobs and the
trainer evaluates the per-token signal against the live policy. The algorithm
determines which loss component consumes the action tokens (``rl`` / ``ce`` /
``ref_kl``, via the ``action_loss_type`` class declaration) and what happens
to env-provided observation tokens (masked out by default; ``echo`` trains on
them with weighted CE).
prime-rl only ever hosts the trainable policy. Every other model an algorithm
uses is an external OpenAI-compatible endpoint, declared inline on the
algorithm that uses it (a :class:`FrozenModelConfig`). Model roles like
"teacher" are algorithm-local vocabulary over these references; the pipeline
branches on liveness alone. The trainer is algorithm-blind: the loss is a sum
of three components (rl, ce, ref_kl), each normalized by its own global token
count; per-token component weights ship on the wire and the trainer just
executes them.
"""
from typing import Annotated, Any, ClassVar, Literal, TypeAlias
from pydantic import Field, model_validator
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.config import BaseConfig
class FrozenModelConfig(ClientConfig):
"""An externally hosted model behind an OpenAI-compatible endpoint: the
client config plus the served model's ``name``.
prime-rl never launches or updates these — only the trainable policy is
ever hosted by prime-rl itself. Frozen models are reachable-but-unmanaged:
``base_url`` is required, their weights never change, and rollouts or
scores from them never go stale (stable prefix cache, no off-policy
aging)."""
name: str
"""Served model name, sent as the ``model`` field of every request."""
@model_validator(mode="after")
def require_explicit_endpoint(self):
if "base_url" not in self.model_fields_set and not self.is_elastic:
raise ValueError(
"a frozen model reference needs base_url — frozen models are externally "
"hosted; prime-rl only ever hosts the trainable policy."
)
return self
ModelReference: TypeAlias = Literal["policy"] | FrozenModelConfig
"""``"policy"`` (the live policy — weight-updated: prefix caches salted per
version, sampling logprobs carried, rollouts age off-policy) or an inline
externally-hosted frozen model."""
ActionLossType: TypeAlias = Literal["rl", "ce", "ref_kl"]
# ---------------------------------------------------------------------------
# Sampling
# ---------------------------------------------------------------------------
class SamplingConfig(BaseConfig):
source: ModelReference = "policy"
"""Model reference for train rollout generation: ``"policy"`` (the live
policy — prefix caches salted per version, sampling logprobs requested,
rollouts age off-policy) or an inline frozen hosted model (stable prefix
cache, no sampling logprobs, rollouts never go stale)."""
# ---------------------------------------------------------------------------
# Shared sub-configs (length penalty, echo roles)
# ---------------------------------------------------------------------------
class TokensLengthPenaltyConfig(BaseConfig):
type: Literal["tokens"] = "tokens"
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
"""Weight on model completion tokens. Finite and non-negative."""
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
class TurnsLengthPenaltyConfig(BaseConfig):
type: Literal["turns"] = "turns"
LengthPenaltyConfig: TypeAlias = Annotated[
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
Field(discriminator="type"),
]
class EchoRoleConfig(BaseConfig):
"""Echo CE supervision for one message role."""
alpha: float = Field(0.1, gt=0)
"""Per-token ce weight for this role's env-provided tokens (ECHO's lambda)."""
class EchoRolesConfig(BaseConfig):
"""Which env-provided message roles train, each at its own weight.
Setting any role replaces the whole table — unset roles stay disabled."""
system: EchoRoleConfig | None = None
user: EchoRoleConfig | None = None
assistant: EchoRoleConfig | None = None
tool: EchoRoleConfig | None = None
@model_validator(mode="after")
def require_a_role(self):
if self.system is None and self.user is None and self.assistant is None and self.tool is None:
raise ValueError("echo needs at least one role enabled (system, user, assistant, or tool)")
return self
class EchoFilterConfig(BaseConfig):
"""User-supplied per-token filter narrowing the role-selected echo tokens.
The callable is imported at startup and invoked once per rollout as
``filter_fn(rollout, **kwargs) -> list[list[bool]]`` — one keep-mask per
trainable branch, each spanning that branch's ``token_ids``. Tokens with
``False`` never receive echo weight; the
filter can only narrow the role selection, not widen it. The raw rollout
exposes message text and sampling logprobs, so content filters (e.g.
dropping tool-output warnings) and sampling-probability filters need no
extra framework surface."""
import_path: str
"""Import path to the filter callable (e.g. ``my_module.drop_warnings``)."""
kwargs: dict[str, Any] = Field(default_factory=dict)
"""Kwargs forwarded to the filter."""
# ---------------------------------------------------------------------------
# The algorithms (a discriminated union keyed on ``type``)
# ---------------------------------------------------------------------------
class BaseAlgoConfig(BaseConfig):
"""Base for every algorithm: the shared sampling component and the
cross-cutting source/loss compatibility check. Each subclass sets ``type``
(the discriminator), declares its loss routing (``action_loss_type``), and
adds its own parameters — including any reference model it needs, named
where that model is actually used (opd scores against a frozen ``teacher``;
sft samples from its ``sampling.source``; opsd self-distills against the
live policy and names no model).
The bundle IS the algorithm — there is no separate ``advantage``
sub-component. ``algo.type`` names it, and the class defaults are the
vetted setting."""
action_loss_type: ClassVar[ActionLossType] = "rl"
sampling: SamplingConfig = SamplingConfig()
"""Sampling component: which model generates train rollouts."""
@model_validator(mode="after")
def validate_sampling_source(self):
"""The on-policy loss types (rl, ref_kl) need the live policy's own
sampling logprobs, so they must sample from ``"policy"``; only sft (ce)
may sample from a frozen model."""
if self.action_loss_type in ("rl", "ref_kl") and self.sampling.source != "policy":
raise ValueError(
f"algorithm '{self.type}' trains with the "
f"{self.action_loss_type} loss type but sampling.source is a frozen model — "
"the importance ratio and trust region need the live policy's own sampling logprobs. "
"Use the 'sft' algorithm to distill frozen-model tokens."
)
return self
class GRPOAlgoConfig(BaseAlgoConfig):
type: Literal["grpo"] = "grpo"
"""GRPO: scalar advantage = reward minus the per-group mean baseline,
consumed by the ``rl`` loss component on the rollout's action tokens."""
action_loss_type: ClassVar[ActionLossType] = "rl"
length_penalty: LengthPenaltyConfig | None = None
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
class EchoAlgoConfig(GRPOAlgoConfig):
type: Literal["echo"] = "echo" # type: ignore[assignment]
"""ECHO: group-relative advantage on action tokens (GRPO), plus weighted
CE on env-provided tokens of later turns (tool output, user feedback),
selected by message role via the renderer's per-token ``is_content``
attribution (renderers that don't attribute content fall back to weighting
the whole non-sampled span). Selected tokens feed the ``ce`` loss component
at their role's ``alpha`` and stay outside the rl mask and its denominator."""
roles: EchoRolesConfig = EchoRolesConfig(tool=EchoRoleConfig())
"""The role table. The default — tool-response bodies at ``alpha = 0.1``
— is the vetted ECHO setting."""
filter: EchoFilterConfig | None = None
"""Optional user-supplied filter narrowing the role-selected tokens."""
class MaxRLAlgoConfig(BaseAlgoConfig):
type: Literal["max_rl"] = "max_rl"
"""MaxRL (arXiv:2602.02710): scalar advantage = (reward − group mean) /
group mean, consumed by the ``rl`` loss component. Normalizing by the
mean instead of GRPO's standard deviation makes the policy gradient
unbiased for the order-``group_size`` truncation of the maximum-likelihood
objective: low-pass-rate examples get ~1/p weight, and ``group_size`` is
the truncation order interpolating REINFORCE (1) → exact maximum
likelihood (∞). Designed for non-negative (canonically binary) rewards;
a group with mean reward 0 carries zero advantages everywhere (the
zero-advantage filter drops it, matching the paper's K=0 convention)."""
action_loss_type: ClassVar[ActionLossType] = "rl"
class OPDAlgoConfig(BaseAlgoConfig):
type: Literal["opd"] = "opd"
"""On-policy distillation: the per-token signal is the reverse KL to
a reference model, evaluated in the trainer from reference prefill
logprobs scored over each sample's own context (``ref_logprobs`` on the
wire, ``ref_kl`` loss component). No scalar advantage is assigned —
rollouts keep ``advantages=None`` (advantage-based filters never fire) and
samples ship no advantage stream. ``group_size`` only fans out sampling."""
action_loss_type: ClassVar[ActionLossType] = "ref_kl"
teacher: FrozenModelConfig
"""The teacher — an inline frozen hosted model (``name`` + ``base_url``)
whose reverse KL the policy distills toward. Required, and necessarily a
frozen endpoint: scoring the policy under itself yields zero KL signal, so
``"policy"`` is not even representable here (use ``opsd`` for
demo-conditioned self-teaching)."""
class OPSDAlgoConfig(BaseAlgoConfig):
type: Literal["opsd"] = "opsd"
"""On-policy self-distillation (SDFT, https://arxiv.org/abs/2601.19897):
the per-token signal is the reverse KL against the live policy conditioned
on an expert demonstration. The teacher *is* the policy — self-distillation
names no separate model — scoring each sample with the demonstration
prepended as a leading system message. The sample is scored verbatim (no
re-rendering), so it's robust to tool/multimodal prompts and works for any
number of turns. No scalar advantage is assigned — rollouts keep
``advantages=None`` (advantage-based filters never fire) and samples ship no
advantage stream."""
action_loss_type: ClassVar[ActionLossType] = "ref_kl"
demo_key: str = "demonstration"
"""Key holding the expert demonstration text — looked up in the example's
``info`` dict first, then as a top-level rollout field (e.g. ``answer``)."""
template: str = "Here is an example of an expert response:\n<demonstration>\n{demonstration}\n</demonstration>"
"""Content of the leading system message carrying the demonstration.
Receives ``{demonstration}``; the original question stays in the (verbatim)
user turn, so it isn't templated here."""
renderer: RendererConfig = AutoRendererConfig()
"""Renderer family for the hint block. The tokenizer is always the live
policy's (self-distillation has no separate model — not configurable).
Defaults to ``"auto"`` (resolved from the policy tokenizer); set explicitly
to match a non-auto policy renderer."""
class SFTAlgoConfig(BaseAlgoConfig):
type: Literal["sft"] = "sft"
"""SFT distillation: cross-entropy on the sampled tokens. The ``ce`` loss
ignores advantages and SFT assigns none — it trains on every sampled token.
Reward-based filtering, if wanted, is an explicit filter, not smuggled
through an unused advantage stream."""
action_loss_type: ClassVar[ActionLossType] = "ce"
@model_validator(mode="after")
def require_frozen_source(self):
"""sft's teacher is the model it samples from — ``sampling.source`` must
be a frozen hosted model, not the policy (CE on the policy's own tokens
is not a distillation target)."""
if self.sampling.source == "policy":
raise ValueError(
f"algorithm '{self.type}' needs a teacher to sample rollouts from — "
"CE on the policy's own tokens is not a distillation target. Set "
"sampling.source to an inline hosted model (name + base_url)."
)
return self
AlgoConfig: TypeAlias = Annotated[
GRPOAlgoConfig | EchoAlgoConfig | MaxRLAlgoConfig | OPDAlgoConfig | OPSDAlgoConfig | SFTAlgoConfig,
Field(discriminator="type"),
]
"""The training algorithm: sampling plus the per-token training signal (credit
assignment and loss routing, fused). The ``type`` selects the algorithm, and
its class defaults are the vetted setting.
- ``grpo`` — policy group sampling, group-relative advantage, RL loss (the default).
- ``max_rl`` — GRPO with mean-normalized advantages (maximum-likelihood RL).
- ``opd`` — on-policy distillation: policy samples, per-token reverse KL against a reference model. Needs ``teacher``.
- ``opsd`` — SDFT: policy samples, demo-conditioned reverse KL against the live policy (the teacher is the policy itself).
- ``sft`` — a frozen model samples, the policy trains with CE on its tokens. Needs a frozen ``sampling.source``.
- ``echo`` — GRPO on action tokens + weighted CE on tool-response observation tokens.
A new credit-assignment scheme is a new named algorithm in code (subclass
``Algorithm``, register it), not a config that points at an import path.
"""
@@ -6,6 +6,10 @@ import verifiers.v1 as vf
from pydantic import AliasChoices, Field, model_validator
from renderers import AutoRendererConfig, RendererConfig
from prime_rl.configs.algorithm import (
AlgoConfig,
GRPOAlgoConfig,
)
from prime_rl.configs.shared import (
BaseModelConfig,
ClientConfig,
@@ -40,6 +44,9 @@ class ModelConfig(BaseModelConfig):
lora: LoRAConfig | None = None
"""Per-run LoRA configuration. If None, LoRA is disabled."""
client: ClientConfig = ClientConfig()
"""Client of the live deployment (``[orchestrator.model.client]``)."""
class TrainSamplingConfig(BaseConfig):
temperature: float = Field(1.0, ge=0)
@@ -205,40 +212,6 @@ class EnvConfig(vf.EnvServerConfig):
return self
class LinearLengthPenaltyConfig(BaseConfig):
coef: float = Field(0.25, ge=0, allow_inf_nan=False)
"""Scale on the linear length penalty. Each reward is reduced by ``coef * pass_rate * (model completion tokens / orchestrator.seq_len)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative."""
gate_by_correctness: bool = False
"""When True, scale each rollout's penalty by its reward (``penalty * reward``), so correct rollouts (``reward == 1``) are penalized and incorrect ones (``reward == 0``) are not. When False, every rollout is penalized equally."""
class DefaultAdvantageConfig(BaseConfig):
type: Literal["default"] = "default"
length_penalty: LinearLengthPenaltyConfig | None = None
"""Length penalty applied during advantage computation. Subtracts a ``coef * pass_rate * (completion tokens / orchestrator.seq_len)`` term from each reward (``pass_rate`` = group mean reward) before the baseline subtraction, so solved-often problems get the strongest concision pressure and never-solved groups get none. None disables the penalty."""
length_weighted_baseline: bool = False
"""When True, the GRPO baseline is the token-length-weighted mean reward (``sum(len_i * reward_i) / sum(len_i)``) instead of the plain group mean, centering advantages by per-token expected reward."""
class CustomAdvantageConfig(BaseConfig):
type: Literal["custom"] = "custom"
import_path: str
"""Import path to the advantage function (e.g. ``my_module.my_advantage``)."""
kwargs: dict[str, Any] = Field(default_factory=dict)
"""Kwargs forwarded to the advantage function."""
AdvantageConfig: TypeAlias = Annotated[
DefaultAdvantageConfig | CustomAdvantageConfig,
Field(discriminator="type"),
]
class TrainEnvConfig(EnvConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
@@ -247,10 +220,10 @@ class TrainEnvConfig(EnvConfig):
"""Rollouts generated per example for GRPO group-relative advantages.
Inherits from ``orchestrator.group_size`` when unset."""
advantage: AdvantageConfig | None = None
"""Advantage strategy for this env's GRPO groups. Inherits from the top-level
``orchestrator.advantage`` when unset; set a different ``default``/``custom``
config to give this env its own advantage computation."""
algo: AlgoConfig | None = None
"""Training algorithm for this env. Inherits from the top-level
``orchestrator.algo`` when unset; set ``type`` (and its params) to give
this env its own algorithm."""
class EvalEnvConfig(EnvConfig):
@@ -473,21 +446,18 @@ class OrchestratorExperimentalConfig(BaseConfig):
pass
class RolloutModelConfig(BaseConfig):
model: ModelConfig = ModelConfig()
client: ClientConfig = ClientConfig()
class OrchestratorConfig(BaseConfig):
training_mode: Literal["rl", "opd", "sft"] = "rl"
"""Training mode. ``rl``: student generates rollouts, no teacher. ``opd``: student generates rollouts, teacher computes logprobs (teacher_tau > 0). ``sft``: teacher generates rollouts, student inference pool used for evals and weight sync."""
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm: sampling plus the per-token training signal (credit
assignment and loss routing, fused — its ``type`` names the algorithm).
Defaults to ``grpo``. Override per env via ``[[orchestrator.train.env]]``'s
``algo``."""
student: RolloutModelConfig = Field(RolloutModelConfig(), validation_alias=AliasChoices("student", "model"))
"""Student rollout participant (model + client) — the model being trained."""
teacher: RolloutModelConfig | None = Field(None, validation_alias=AliasChoices("teacher", "teacher_model"))
"""Teacher rollout participant (model + client). Role depends on ``training_mode``: ``opd`` — teacher computes logprobs; ``sft`` — teacher generates rollouts."""
model: ModelConfig = ModelConfig()
"""The model being trained: its model fields plus the client of the live
vLLM deployment (``[orchestrator.model] name = ...`` with
``[orchestrator.model.client]``). Algorithm components reference it as
``"policy"``."""
train: TrainConfig = TrainConfig()
@@ -510,8 +480,6 @@ class OrchestratorConfig(BaseConfig):
eval: EvalConfig | None = None
"""Evaluation configuration."""
advantage: AdvantageConfig | None = DefaultAdvantageConfig()
pre_batch_filters: list[FilterConfig] = [
GibberishFilterConfig(enforce=False),
RepetitionFilterConfig(enforce=False),
@@ -540,7 +508,7 @@ class OrchestratorConfig(BaseConfig):
"""Collect inference-server metrics (requires wandb)."""
inference_metrics_roles: list[Literal["prefill", "decode"]] | None = None
"""Role for each student admin client when collecting P/D inference metrics."""
"""Role for each policy admin client when collecting P/D inference metrics."""
ckpt: CheckpointConfig | None = None
"""Checkpoint configuration."""
@@ -593,67 +561,6 @@ class OrchestratorConfig(BaseConfig):
experimental: OrchestratorExperimentalConfig = OrchestratorExperimentalConfig()
@model_validator(mode="before")
@classmethod
def fold_student_shortcuts(cls, data: Any) -> Any:
"""Accept top-level ``[orchestrator.model]`` / ``[orchestrator.client]``
as shorthand for the student sub-config. Useful for ergonomic rl configs
where ``[orchestrator.student.*]`` is overkill, and required for
pre-refactor configs that used the flat layout to keep parsing:
- [orchestrator.client.*] -> [orchestrator.student.client.*]
- [orchestrator.model.<k>] -> [orchestrator.student.model.<k>]
(where <k> is any ModelConfig field)
Teacher must always be configured under [orchestrator.teacher.*]
(no equivalent shortcut), because rl mode forbids a teacher and we
don't want the same shortcut to silently route to two different roles.
"""
if not isinstance(data, dict):
return data
def deep_merge(dst: dict, src: dict) -> None:
"""In-place recursive merge of ``src`` into ``dst``. ``src`` wins at the leaf."""
for k, v in src.items():
if isinstance(v, dict) and isinstance(dst.get(k), dict):
deep_merge(dst[k], v)
else:
dst[k] = v
# 1. Re-nest top-level [orchestrator.client] under student.client.
legacy_client = data.pop("client", None)
if isinstance(legacy_client, dict):
student = data.setdefault("student", {})
if isinstance(student, dict):
deep_merge(student.setdefault("client", {}), legacy_client)
else:
# Mismatched types - put it back and let pydantic surface the error.
data["client"] = legacy_client
# 2. Consolidate the legacy `model` alias into `student` so the
# flat-layout fix-up below sees a single target. Deep-merge with the
# legacy keys winning so a CLI `--model.<k>` overrides TOML `student.model.<k>`.
legacy_model = data.pop("model", None)
if legacy_model is not None:
existing = data.get("student")
if existing is None:
data["student"] = legacy_model
elif isinstance(existing, dict) and isinstance(legacy_model, dict):
deep_merge(existing, legacy_model)
else:
# Mismatched types - put it back and let pydantic surface the error.
data["model"] = legacy_model
# 3. Re-nest flat ModelConfig keys under student.model.
model_only_keys = set(ModelConfig.model_fields)
student = data.get("student")
if isinstance(student, dict):
flat = {k: student.pop(k) for k in list(student) if k in model_only_keys}
if flat:
student.setdefault("model", {}).update(flat)
return data
@model_validator(mode="before")
@classmethod
def _env_to_train(cls, data: Any) -> Any:
@@ -684,15 +591,15 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
self.tokenizer.name = self.student.model.name
self.tokenizer.name = self.model.name
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.student.model.trust_remote_code
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def auto_setup_session_headers(self):
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
self.student.client.extra_headers_from_state.setdefault("X-Session-ID", "trajectory_id")
self.model.client.extra_headers_from_state.setdefault("X-Session-ID", "trajectory_id")
return self
@model_validator(mode="after")
@@ -716,13 +623,33 @@ class OrchestratorConfig(BaseConfig):
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 in ("opd", "sft") and not has_teacher:
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
def inherit_env_algorithms(self):
"""Envs without their own algorithm inherit the top-level one.
Declared before any validator that reads ``algo``."""
for env_cfg in self.train.env:
if env_cfg.algo is None:
env_cfg.algo = self.algo.model_copy(deep=True)
return self
@property
def any_policy_sourced(self) -> bool:
"""True when at least one train env samples rollouts from the live policy."""
return any(env.algo is not None and env.algo.sampling.source == "policy" for env in self.train.env)
@model_validator(mode="after")
def validate_pool_size(self):
"""``pool_size`` sizes the renderer-client pool for policy-sourced
sampling. Reject it when that path never runs — no train env samples
from the policy — so callers don't silently pass it and wonder why
it's ignored."""
if self.pool_size is None:
return self
if not self.any_policy_sourced:
raise ValueError(
f"orchestrator.pool_size={self.pool_size!r} is set but no train env samples "
"from the policy — the renderer-client sampling pool never runs (the renderer "
"is still used for client-side tokenization). Remove pool_size."
)
return self
@model_validator(mode="after")
@@ -742,7 +669,7 @@ class OrchestratorConfig(BaseConfig):
return self
from renderers.base import MODEL_RENDERER_MAP
model_id = self.tokenizer.name or self.student.model.name
model_id = self.tokenizer.name or self.model.name
if model_id in MODEL_RENDERER_MAP:
return self
raise ValueError(
@@ -799,11 +726,6 @@ class OrchestratorConfig(BaseConfig):
if "group_size" not in env_cfg.model_fields_set:
env_cfg.group_size = self.group_size
# Propagate the top-level ``advantage`` into each train env that didn't set its own.
for env_cfg in self.train.env:
if "advantage" not in env_cfg.model_fields_set:
env_cfg.advantage = self.advantage
return self
@model_validator(mode="after")
@@ -822,13 +744,15 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def resolve_env_config(self):
"""Set vLLM sampling defaults on each train env from top-level fields."""
if self.training_mode == "sft":
return self
"""Set vLLM sampling defaults + legacy env kwargs on each train env from top-level fields."""
for env in self.train.env:
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)
# Policy-sourced rollouts hit our vLLM server; frozen-sourced
# rollouts may hit external OAI endpoints that reject these knobs.
assert env.algo is not None
if env.algo.sampling.source == "policy":
env.sampling.extra_body.setdefault("top_k", -1)
env.sampling.extra_body.setdefault("min_p", 0.0)
env.sampling.extra_body.setdefault("return_token_ids", True)
if env.is_legacy:
# v0 env: cap per-turn response tokens to the training budget (the legacy
# bridge applies extra_env_kwargs via env.set_kwargs).
@@ -373,40 +373,40 @@ class RLConfig(BaseConfig):
if self.trainer.weight_broadcast.type == "nccl":
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
if self.orchestrator.student.model.lora is None:
if self.orchestrator.model.lora is None:
from prime_rl.configs.orchestrator import LoRAConfig
self.orchestrator.student.model.lora = LoRAConfig()
self.orchestrator.model.lora = LoRAConfig()
if (
self.orchestrator.student.model.lora.rank is not None
and self.orchestrator.student.model.lora.rank != self.trainer.model.lora.rank
self.orchestrator.model.lora.rank is not None
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
):
raise ValueError(
f"orchestrator.student.model.lora.rank ({self.orchestrator.student.model.lora.rank}) conflicts with "
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
f"Remove orchestrator.student.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
)
if (
self.orchestrator.student.model.lora.alpha is not None
and self.orchestrator.student.model.lora.alpha != self.trainer.model.lora.alpha
self.orchestrator.model.lora.alpha is not None
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
):
raise ValueError(
f"orchestrator.student.model.lora.alpha ({self.orchestrator.student.model.lora.alpha}) conflicts with "
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
f"Remove orchestrator.student.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
)
if self.orchestrator.student.model.lora.rank is None:
self.orchestrator.student.model.lora.rank = self.trainer.model.lora.rank
if self.orchestrator.model.lora.rank is None:
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
if self.orchestrator.student.model.lora.alpha is None:
self.orchestrator.student.model.lora.alpha = self.trainer.model.lora.alpha
if self.orchestrator.model.lora.alpha is None:
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
if self.orchestrator.student.model.lora.name is None:
self.orchestrator.student.model.lora.name = (
f"r{self.orchestrator.student.model.lora.rank}-a{self.orchestrator.student.model.lora.alpha}"
if self.orchestrator.model.lora.name is None:
self.orchestrator.model.lora.name = (
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
)
if self.inference is not None:
@@ -623,23 +623,26 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_inference_client(self):
"""Auto-configure orchestrator student client from the inference server config.
"""Auto-configure the orchestrator policy client from the inference server config.
Direct single-node runs expose all local DP ranks behind one base URL,
so pin logical clients with ``X-data-parallel-rank``. Multi-node SLURM
runs expose a vllm-router URL instead; the router balances across
per-rank backend URLs and forwards request headers, so the orchestrator
must not inject a DP-rank header there.
must not inject a DP-rank header there. When no train env samples from
the policy (e.g. sft_distill), also set base_url — policy-sourced
algorithms rely on the ClientConfig default (``["http://localhost:8000/v1"]``)
which already matches the auto-launched policy vLLM at inference.server.port = 8000.
"""
if self.inference is None:
return self
client = self.orchestrator.student.client
client = self.orchestrator.model.client
if "dp_rank_count" not in client.model_fields_set:
if self.deployment.type == "multi_node":
client.dp_rank_count = 1
else:
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
if self.orchestrator.training_mode == "sft" and "base_url" not in client.model_fields_set:
if not self.orchestrator.any_policy_sourced and "base_url" not in client.model_fields_set:
host = self.inference.server.host or "localhost"
port = self.inference.server.port
client.base_url = [f"http://{host}:{port}/v1"]
@@ -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
@@ -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["disabled"] = 1024
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. SFT training silently disables this (not supported yet)."""
@model_validator(mode="before")
@classmethod
@@ -258,7 +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
@@ -510,7 +510,7 @@ class TrainerConfig(BaseConfig):
data: DataLoaderConfig = DataLoaderConfig()
loss: LossConfig = DefaultLossConfig()
"""Loss config for rl-mode batches. opd and sft batches dispatch to their own loss fns unconditionally and do not read this."""
"""Loss config for the rl loss component (see ``setup_rl_loss_fn``). The ce / ref_kl components are fixed and do not read this."""
optim: OptimizerConfig = AdamWConfig()
@@ -657,16 +657,9 @@ class TrainerConfig(BaseConfig):
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def auto_setup_fused_lm_head_token_chunk_size(self):
if self.model.fused_lm_head_token_chunk_size == "auto":
self.model.fused_lm_head_token_chunk_size = 8192
return self
@model_validator(mode="after")
def ep_only_with_custom_impl(self):
if self.model.ep > 1 and self.model.impl not in ("custom", "auto"):
if self.model.ep != 1 and self.model.ep != "auto" and self.model.impl not in ("custom", "auto"):
raise ValueError("EP is only supported with the custom implementation or auto mode")
return self
@@ -22,9 +22,6 @@ def propagate_shared_fields(data: Any) -> Any:
The original footgun the mutex was designed to catch — a sub-config
value silently winning over a later CLI shared override — is still
caught because that scenario produces *different* values.
- **Aliased sub-paths**: ``orchestrator.model.*`` is checked against its
``orchestrator.student.model.*`` alias (and vice versa), so the
conflict fires regardless of which spelling the user wrote.
"""
if not isinstance(data, dict):
return data
@@ -51,36 +48,34 @@ def propagate_shared_fields(data: Any) -> Any:
conflicts: list[tuple[str, str]] = []
def propagate(shared_path: str, *targets: str, aliases: tuple[str, ...] = ()) -> None:
"""Verbatim shared → targets. Records *disagreeing* overlap (incl. alias
spellings) into ``conflicts`` and fills each target if the shared value
is set. Matching values are silently accepted so the materialized
config round-trips through re-load.
def propagate(shared_path: str, *targets: str) -> None:
"""Verbatim shared → targets. Records *disagreeing* overlap into
``conflicts`` and fills each target if the shared value is set. Matching
values are silently accepted so the materialized config round-trips
through re-load.
"""
value = get(shared_path)
if value is None:
return
for sub in (*targets, *aliases):
sub_value = get(sub)
for target in targets:
sub_value = get(target)
if sub_value is not None and sub_value != value:
conflicts.append((shared_path, sub))
conflicts.append((shared_path, target))
for target in targets:
fill(target, value)
# [model] → trainer / orchestrator (student, via AliasChoices) / inference.
# [model] → trainer / orchestrator / inference.
propagate(
"model.name",
"trainer.model.name",
"inference.model.name",
"orchestrator.model.name",
aliases=("orchestrator.student.model.name",),
)
propagate(
"model.vlm",
"trainer.model.vlm",
"inference.model.vlm",
"orchestrator.model.vlm",
aliases=("orchestrator.student.model.vlm",),
)
# [log]
@@ -224,18 +219,18 @@ def validate_shared_model_name(
) -> None:
# Orchestrator must match inference (it queries the inference server)
if inference is not None:
if inference.model.name != orchestrator.student.model.name:
if inference.model.name != orchestrator.model.name:
raise ValueError(
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.student.model.name}) are not the same. "
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
"The orchestrator queries the inference server and must use the same model name."
)
return
if trainer.model.name.startswith("Jackmin108/"): # The TT MoE models will have a different name on the orchestrator
return
if trainer.model.name != orchestrator.student.model.name:
if trainer.model.name != orchestrator.model.name:
raise ValueError(
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.student.model.name}) are not the same. Please specify the same model name for both."
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. Please specify the same model name for both."
)
+23 -41
View File
@@ -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,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers>=0.1.15.dev388",
"verifiers>=0.1.15.dev400",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -67,32 +67,14 @@ flash-attn-cute = [
]
envs = [
"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",
"uuid-ctf-v1",
"science-env",
"simpleqa-verified",
"tau2-bench",
"wiki-search",
"wordle",
"reverse-text-v1",
@@ -104,6 +86,9 @@ envs = [
"alphabet-sort-v1",
"scaleswe-v1",
"color-codeword-v1",
"deepdive-v1",
"gpqa-v1",
"livecodebench-v1",
"r2e-gym-v1",
"terminal-bench-2-v1",
"code-golf-v1",
@@ -116,6 +101,12 @@ envs = [
"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'",
@@ -175,7 +166,7 @@ override-dependencies = [
"transformers==5.6.2",
"torch>=2.9.0",
"openenv-core",
"verifiers>=0.1.15.dev388",
"verifiers>=0.1.15.dev400",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
@@ -228,32 +219,14 @@ verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", 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 }
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 }
uuid-ctf-v1 = { path = "deps/research-environments/environments/uuid_ctf_v1", 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 }
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 }
@@ -265,6 +238,9 @@ aime26-v1 = { path = "deps/research-environments/environments/aime26_v1", editab
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 }
@@ -277,6 +253,12 @@ 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" }
@@ -285,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" }
+5 -3
View File
@@ -47,9 +47,11 @@ id = "reverse-text"
CLI: `--env.0.id reverse-text --env.1.id math-env`.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--vllm-extra '{"key1": "value1"}'`.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--vllm-extra '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
**Discriminated unions** — set the `type` field to pick the variant (`[trainer.loss] type = "sft"`). Omit `type` to keep the default variant.
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-env override: `[orchestrator.train.env.algo] type = "opd"` (the env assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
@@ -62,7 +64,7 @@ In TOML, an empty section header (`[ckpt]`) does the same.
## RL trainer token exports
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Single-run/fallback exports go under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`; multi-run trainer exports with packer metadata go under the owning run directory, `output_dir/<run_id>/token_exports/step_<run_step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Single-run/fallback exports go under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`; multi-run trainer exports with packer metadata go under the owning run directory, `output_dir/<run_id>/token_exports/step_<run_step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
```toml
enable_token_export = true
+20 -12
View File
@@ -12,6 +12,7 @@ from threading import Event, Thread
import pynvml
import tomli_w
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.inference import vllm_overrides_fragment
@@ -118,16 +119,16 @@ def rl_local(config: RLConfig):
}
# Validate client port matches inference server port
if config.inference is not None and not config.orchestrator.student.client.is_elastic:
if config.inference is not None and not config.orchestrator.model.client.is_elastic:
from urllib.parse import urlparse
base_url = config.orchestrator.student.client.base_url[0]
base_url = config.orchestrator.model.client.base_url[0]
parsed = urlparse(base_url)
client_port = parsed.port
expected_port = config.inference.server.port
if client_port != expected_port:
raise ValueError(
f"orchestrator.student.client.base_url port ({client_port}) does not match "
f"orchestrator.model.client.base_url port ({client_port}) does not match "
f"inference.server.port ({expected_port}). "
f"Update the base_url to use port {expected_port} to match the inference server."
)
@@ -181,19 +182,26 @@ def rl_local(config: RLConfig):
monitor_threads.append(monitor_thread)
else:
logger.warning(
"No [inference] block configured - the student inference server will not be started here. "
"All training modes (rl/opd/sft) require a student inference pool for evals + weight sync; "
"make sure one is running at orchestrator.student.client.base_url "
f"({', '.join(config.orchestrator.student.client.base_url)}), otherwise the orchestrator "
"No [inference] block configured - the policy inference server will not be started here. "
"Every algorithm requires a policy inference pool for evals + weight sync; "
"make sure one is running at orchestrator.model.client.base_url "
f"({', '.join(config.orchestrator.model.client.base_url)}), otherwise the orchestrator "
"will hang waiting for it."
)
if config.orchestrator.teacher:
frozen_endpoints: list[str] = []
for env in config.orchestrator.train.env:
algo = env.algo
assert algo is not None, "TrainEnvConfig.algo must be resolved before launch (inherit_env_algorithms)"
for ref in (algo.sampling.source, getattr(algo, "teacher", None)):
if isinstance(ref, FrozenModelConfig):
frozen_endpoints.append(f"{ref.name} ({', '.join(ref.base_url)})")
if frozen_endpoints:
endpoints = ", ".join(dict.fromkeys(frozen_endpoints))
logger.info(
"orchestrator.teacher is configured - the rl entrypoint does not start teacher inference "
"servers. Make sure your teacher endpoint at "
f"{', '.join(config.orchestrator.teacher.client.base_url)} is running before the "
"orchestrator starts, otherwise rollouts will hang."
"Frozen model references are configured - the rl entrypoint does not start them. "
f"Make sure these endpoints are serving before the orchestrator starts: {endpoints}; "
"otherwise rollouts will hang."
)
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_TOML).as_posix()]
+28 -197
View File
@@ -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,10 +14,9 @@ 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()
@@ -184,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.
@@ -781,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
@@ -805,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",
)
+9
View File
@@ -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
+18 -22
View File
@@ -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(
+10 -5
View File
@@ -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] = {}
-115
View File
@@ -1,115 +0,0 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable
import torch
if TYPE_CHECKING:
import verifiers.v1 as vf
from prime_rl.orchestrator.types import Rollout
from prime_rl.configs.orchestrator import (
AdvantageConfig,
CustomAdvantageConfig,
LinearLengthPenaltyConfig,
)
from prime_rl.utils.utils import import_object
@dataclass
class AdvantageInputs:
"""Inputs for advantage computation of a single group (one example × N rollouts)."""
rollouts: list[vf.Trace]
@dataclass
class AdvantageOutputs:
"""Outputs from advantage computation of a single group."""
advantages: list[float]
AdvantageFn = Callable[..., AdvantageOutputs]
"""Type for an advantage function.
Expected signature:
def my_advantage(inputs: AdvantageInputs, **kwargs) -> AdvantageOutputs:
...
The function receives a single group and returns a list of advantages with one
entry per rollout. `assign_advantages` calls it on one already-grouped cohort.
"""
def default_advantage_fn(
inputs: AdvantageInputs,
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`` subtracts ``coef * pass_rate * (completion tokens / max_seq_len)``
from each reward (``pass_rate`` = group mean reward), optionally gated to correct
(``reward == 1``) rollouts. ``length_weighted_baseline`` uses the token-length-weighted
mean reward as the baseline instead of the plain mean.
"""
rewards = torch.tensor([r.reward for r in inputs.rollouts], dtype=torch.float32)
lengths = torch.tensor([r.completion_len for r in inputs.rollouts], dtype=rewards.dtype)
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
if length_weighted_baseline:
baseline = (lengths * rewards).sum() / lengths.sum()
else:
baseline = rewards.mean()
return AdvantageOutputs(advantages=(rewards - baseline).tolist())
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)
kwargs = config.kwargs
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
return custom_fn(inputs, **kwargs)
return advantage_fn
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
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[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 ``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 for r in rollouts]))
for rollout, advantage in zip(rollouts, result.advantages):
rollout.advantage = advantage
@@ -0,0 +1,82 @@
"""Orchestrator-side algorithm runtime.
The config side (``prime_rl.configs.algorithm``) defines *what* an algorithm
is — a bundle of sampling and the per-token training signal. This package
turns the signal half into runtime objects (the sampling half is the env's
:class:`~prime_rl.orchestrator.sampler.Sampler`):
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``opd``,
``opsd``, ``sft``) — each named class owns its scoring hooks
(``score_rollout`` / ``score_group``) and declares what it needs (loss
component, a "teacher", ...). One instance per env, built by
:func:`build_algorithm`. A new credit-assignment scheme is a new named class:
subclass :class:`Algorithm`, assign advantages in the hook whose timing fits,
and register it below.
- ``base`` — the :class:`Algorithm` base class, whose non-virtual
``finalize_rollout`` / ``finalize_group`` methods the pipeline drives.
- ``advantage`` — shared advantage math (``efficiency_shaping``). Advantages
are per-token everywhere they are stored or shipped — there is no scalar
advantage in the pipeline. An algorithm assigns credit in its scoring hook
via ``Rollout.assign_advantages``: a scalar that is *broadcast* over the
rollout's completion tokens (uniform credit, the common case), or an explicit
full-length-N per-token list aligned to the concatenated sample token_ids
(0.0 off-mask).
- ``routing`` — wire-field stamping: per-token component weight streams
(rl / ce / ref_kl) and the per-token advantage stream.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_pool
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
from prime_rl.orchestrator.algo.max_rl import MaxRLAlgorithm
from prime_rl.orchestrator.algo.opd import OPDAlgorithm
from prime_rl.orchestrator.algo.opsd import OPSDAlgorithm
from prime_rl.orchestrator.algo.routing import stamp_advantages, stamp_loss_routing
from prime_rl.orchestrator.algo.sft import SFTDistillAlgorithm
from prime_rl.orchestrator.types import Rollout
if TYPE_CHECKING:
from prime_rl.configs.algorithm import AlgoConfig
from prime_rl.utils.client import InferencePool
# Runtime dispatch is keyed on ``algo.type`` — it names the algorithm, and
# each config class's defaults are its vetted parameterization.
ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
"grpo": GRPOAlgorithm,
"echo": EchoAlgorithm,
"max_rl": MaxRLAlgorithm,
"opd": OPDAlgorithm,
"opsd": OPSDAlgorithm,
"sft": SFTDistillAlgorithm,
}
def build_algorithm(config: AlgoConfig, policy_pool: InferencePool) -> Algorithm:
cls = ALGORITHM_CLASSES[config.type]
assert cls.action_loss_type == config.action_loss_type # config and runtime declare in two places
# The Algorithm is the runtime of the algorithm config's training signal
# (its sibling Sampler interprets the sampling half). Every algorithm is
# handed the live policy pool — opsd self-distills against it, others may
# judge against it or ignore it. Other models (a frozen teacher, a hint
# renderer) are built from the algorithm's own config in setup().
return cls(config, policy_pool)
__all__ = [
"Algorithm",
"EchoAlgorithm",
"GRPOAlgorithm",
"MaxRLAlgorithm",
"OPDAlgorithm",
"OPSDAlgorithm",
"Rollout",
"SFTDistillAlgorithm",
"build_algorithm",
"connect_frozen_pool",
"stamp_advantages",
"stamp_loss_routing",
]
@@ -0,0 +1,41 @@
from __future__ import annotations
from jaxtyping import Float
from torch import Tensor
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()
+165
View File
@@ -0,0 +1,165 @@
"""The per-env algorithm runtime: the :class:`Algorithm` base class.
Each named class in this package *is* one training algorithm, one module per
algorithm: it owns the algorithm's two scoring hooks directly —
``score_rollout`` (per arrival) and ``score_group`` (per group) — and declares
which loss component its action tokens feed (``action_loss_type``). Reading a
module top to bottom reads the algorithm; writing your own is subclassing
:class:`Algorithm` and overriding the hooks its signal needs. Shared math (group
normalization, prefill alignment) lives as plain functions in ``advantage.py``;
duplication of orchestration between similar algorithms (e.g. OPD and OPSD) is
accepted so each module stays self-contained.
The two hooks are one scope-and-timing ladder — the wider scope is unlocked by
a later barrier, so the two axes coincide. Both are ``async`` (either may do
I/O); a hook that only does advantage math never awaits:
- ``score_rollout(rollout)`` — one rollout, on arrival: rollout-local signals
(raw reward, process rewards, echo's observation weighting) *and* per-rollout
I/O against another model — an inference pool the algorithm connected in
``setup()`` (a frozen teacher) or the live policy (opsd's self-distillation),
queried with bounded concurrency. No siblings.
- ``score_group(group)`` — the cohort, on group completion, *before* filtering
(filters read the streams): group-relative credit (GRPO/MaxRL baselines).
How rollouts are *produced* is not the algorithm's concern: that is the env's
:class:`~prime_rl.orchestrator.sampler.Sampler`, and sample construction
(interleaving, with observation-token provenance via structural node
attribution) is pure pipeline.
The pipeline (train sink) drives each algorithm through its non-virtual
:meth:`Algorithm.finalize_rollout` / :meth:`Algorithm.finalize_group` methods
and reads the class declarations; it never branches on algorithm config fields
or model roles — liveness of a reference is the only runtime distinction.
prime-rl hosts exactly one model — the trainable policy, whose pool every
algorithm is handed (``self.policy_pool``): use it for anything that scores
against the live model (opsd's self-distillation teacher, an LLM judge, ...).
Every *frozen* model an algorithm needs is an external endpoint it *connects to*
(never launches) and owns, in :meth:`Algorithm.setup`.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar
from prime_rl.configs.algorithm import ActionLossType, AlgoConfig, FrozenModelConfig
from prime_rl.orchestrator.algo.routing import stamp_advantages, stamp_loss_routing
from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.orchestrator.types import Rollout
from prime_rl.utils.client import InferencePool
async def connect_frozen_pool(
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
) -> InferencePool:
"""Connect a client pool to an inline frozen model and wait for it to be
ready. The endpoint is externally hosted — prime-rl connects and waits,
never launches.
When ``renderer_config`` is set, the pool's train client is the renderer
(token-in/out) client — required when the frozen model *generates* rollouts
(sft), so the rollout carries tokens. Left as plain chat-completions
otherwise (opd/opsd read teacher logprobs via prefill, where the train
client type is moot)."""
from prime_rl.utils.client import setup_inference_pool
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={', '.join(config.base_url)})")
if renderer_config is not None:
pool = await setup_inference_pool(
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
)
else:
pool = await setup_inference_pool(config, model_name=config.name)
await pool.wait_for_ready(config.name)
return pool
class Algorithm:
"""Base class for one env's training algorithm — the runtime of the
algorithm config's per-token training signal (its sibling :class:`Sampler`
interprets the ``sampling`` half).
Everything on this class is yours to override; the pipeline drives the
compilation through the non-virtual :meth:`finalize_rollout` /
:meth:`finalize_group` methods and never calls anything else. The surface is:
- declarations — which loss component the action tokens feed
(``action_loss_type``);
- lifecycle — :meth:`setup` connects client pools to the frozen models
the algorithm declares, resolving each reference via :meth:`connect`;
- the two scoring hooks, each ``async`` and given the :class:`Rollout`
directly — read the trace, write credit via
:meth:`Rollout.assign_advantages`. They are
async so either stage may do I/O — e.g. a process-reward model or a
teacher at arrival, or a judge at group time whose signal a pre-batch
filter then reads; a hook that only does advantage math simply never
awaits.
- :meth:`score_rollout` — one rollout, on arrival: rollout-local credit,
observation ce weights, or per-token results from a model the algorithm
connected in :meth:`setup` (e.g. teacher reference logprobs). Default:
nothing.
- :meth:`score_group` — the cohort, *before* filtering (filters read the
streams): group-relative credit. Default: nothing — rollouts keep
``advantages=None``, so advantage-based filters skip them.
Model I/O lives in :meth:`score_rollout`: it runs at arrival, *before* the
pre-batch filters, so it pays compute on rollouts that may then be filtered
out — accepted for the simpler one-rollout-at-a-time shape.
Constructed with the algorithm config it interprets plus the live policy
pool (``self.policy_pool`` — always available, never closed by the
algorithm). An algorithm that needs to tokenize (e.g. opsd's demonstration
hint) builds its own renderer in :meth:`setup` from its config; the policy's
renderer is not threaded in."""
action_loss_type: ClassVar[ActionLossType] = "rl"
def __init__(self, config: AlgoConfig, policy_pool: InferencePool):
self.policy_pool = policy_pool
self.connected_pools: list[InferencePool] = [] # frozen pools connected in setup(); closed at shutdown
async def setup(self) -> None:
"""Connect client pools to the algorithm's frozen models — override
and resolve each reference via :meth:`connect`. The base has nothing
to connect."""
async def connect(self, reference: FrozenModelConfig) -> InferencePool:
"""Connect a client pool to a frozen model endpoint and track it in
``connected_pools`` — the host closes what the algorithm opened, at
shutdown. The live policy is never connected here; opsd receives the
policy pool directly."""
pool = await connect_frozen_pool(reference)
self.connected_pools.append(pool)
return pool
async def score_rollout(self, rollout: Rollout) -> None:
"""Arrival phase, one rollout, before its group is complete: write
rollout-local credit (``rollout.assign_advantages``), observation ce
weights (echo), or per-token results from a model — an inference pool
connected in :meth:`setup`, or the live policy (opsd). No siblings, no
group stats."""
async def score_group(self, group: list[Rollout]) -> None:
"""Group phase, the finalized cohort, before filtering: write
group-relative credit."""
async def finalize_rollout(self, rollout: Rollout) -> None:
"""Arrival phase (non-virtual): rollout-local scoring as each rollout is
tokenized."""
if rollout.samples:
await self.score_rollout(rollout)
async def finalize_group(self, rollouts: list[Rollout]) -> None:
"""Group phase (non-virtual): group-relative scoring, then stamp each
sample's wire fields (the advantage stream + loss routing). After this
the records are frozen — groups die at stamping."""
await self.score_group(rollouts)
for rollout in rollouts:
stamp_advantages(rollout)
for sample in rollout.samples:
stamp_loss_routing(sample, self.action_loss_type)
+102
View File
@@ -0,0 +1,102 @@
from __future__ import annotations
from functools import partial
from typing import TYPE_CHECKING, Callable
from prime_rl.configs.algorithm import EchoAlgoConfig
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
from prime_rl.utils.utils import import_object
if TYPE_CHECKING:
import verifiers.v1 as vf
from prime_rl.orchestrator.types import Rollout
from prime_rl.utils.client import InferencePool
class EchoAlgorithm(GRPOAlgorithm):
"""GRPO on action tokens, plus weighted CE on env-provided tokens of
later turns (tool output, user feedback), selected by message role —
tool-response bodies at the vetted default. Selected tokens feed the
``ce`` loss component at their role's ``alpha`` and stay outside the rl
mask and its denominator. An optional user filter narrows the selection
per rollout (e.g. dropping tool-output warnings)."""
def __init__(self, config: EchoAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
self.role_weights = {
role: role_config.alpha
for role in ("system", "user", "assistant", "tool")
if (role_config := getattr(config.roles, role)) is not None
}
self.filter_fn: Callable[..., list[list[bool]]] | None = None
if config.filter is not None:
self.filter_fn = partial(import_object(config.filter.import_path), **config.filter.kwargs)
async def score_rollout(self, rollout: Rollout) -> None:
# Observation weighting is rollout-local; the group-relative GRPO
# baseline is inherited unchanged as ``score_group``.
self._weight_observations(rollout)
def _weight_observations(self, rollout: Rollout) -> None:
"""Write each sample's ``ce_weights`` stream over the env-provided
observation tokens of later turns. Provenance is structural under v1:
within a branch, the non-sampled nodes that follow the first model
response (tool output, user feedback) are the env-provided
observations — each such node's tokens get its message role's weight,
narrowed by the optional user filter. The initial prompt (before the
first response) is excluded. Selected tokens have ``mask`` False, so ce
is the only component that trains them; samples where nothing is
selected ship no ce stream.
Content granularity: when a node carries the renderer's per-token
``is_content`` (``MessageNode.is_content``, parallel to ``token_ids``),
only the message-body tokens are weighted — the chat-template scaffold
(role tags, separators, tool-response wraps) is excluded. Nodes without
attribution (the default renderer, or relay turns with no token ids)
fall back to weighting the whole non-sampled span."""
trainable_branches = [branch for branch in rollout.branches if any(branch.sampled_mask)]
filter_masks = self._filter_masks(rollout, trainable_branches) if self.filter_fn is not None else None
for sample_idx, (sample, branch) in enumerate(zip(rollout.samples, trainable_branches)):
weights = [0.0] * len(sample.token_ids)
offset = 0
seen_response = False
for node in branch.nodes:
span = len(node.token_ids)
role = node.message.role
if seen_response and not node.sampled and role in self.role_weights:
weight = self.role_weights[role]
keep_mask = filter_masks[sample_idx] if filter_masks is not None else None
# Per-token content granularity when the renderer attributed it; otherwise
# the whole node span (is_content empty -> fall back to current behavior).
has_content = len(node.is_content) == span
for i in range(offset, offset + span):
if has_content and not node.is_content[i - offset]:
continue
if keep_mask is None or keep_mask[i]:
weights[i] = weight
if node.sampled:
seen_response = True
offset += span
if any(weights):
sample.ce_weights = weights
def _filter_masks(self, trace: vf.Trace, trainable_branches: list) -> list[list[bool]]:
"""Invoke the user echo filter and validate its shape: one keep-mask
per trainable branch, each spanning that branch's ``token_ids``."""
assert self.filter_fn is not None
masks = self.filter_fn(trace)
if not isinstance(masks, list) or len(masks) != len(trainable_branches):
got = len(masks) if isinstance(masks, list) else type(masks).__name__
raise ValueError(
f"echo filter must return one keep-mask per trainable branch: got {got}, expected {len(trainable_branches)}"
)
for branch_idx, (branch, mask) in enumerate(zip(trainable_branches, masks)):
expected = len(branch.token_ids)
if not isinstance(mask, list) or len(mask) != expected:
got = len(mask) if isinstance(mask, list) else type(mask).__name__
raise ValueError(
f"echo filter mask for branch {branch_idx} must span the branch's tokens: "
f"got {got}, expected {expected}"
)
return masks
+45
View File
@@ -0,0 +1,45 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from prime_rl.configs.algorithm import GRPOAlgoConfig, TokensLengthPenaltyConfig
from prime_rl.orchestrator.algo.advantage import efficiency_shaping
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.orchestrator.utils import get_tool_response_len
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
from prime_rl.utils.client import InferencePool
class GRPOAlgorithm(Algorithm):
"""Group Relative Policy Optimization: sample a group of rollouts from the
policy per example; credit = reward minus the group mean (optionally
length-shaped); action tokens feed the ``rl`` loss."""
def __init__(self, config: GRPOAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
self.length_penalty = config.length_penalty
async def score_group(self, group: list[Rollout]) -> None:
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
lp = self.length_penalty
if lp is None:
advantages = rewards - rewards.mean()
elif isinstance(lp, TokensLengthPenaltyConfig):
costs = torch.tensor(
[
lp.completion_weight * rollout.completion_len
+ lp.tool_response_weight * get_tool_response_len(rollout)
for rollout in group
],
dtype=rewards.dtype,
)
advantages = efficiency_shaping(rewards, costs)
else: # TurnsLengthPenaltyConfig
costs = torch.tensor([rollout.num_turns for rollout in group], dtype=rewards.dtype)
advantages = efficiency_shaping(rewards, costs)
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
rollout.assign_advantages(advantage)
+31
View File
@@ -0,0 +1,31 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from prime_rl.orchestrator.algo.base import Algorithm
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
class MaxRLAlgorithm(Algorithm):
"""Maximum-likelihood RL (arXiv:2602.02710): the GRPO pipeline with
mean-normalized advantages — ``(reward − group mean) / group mean`` instead
of plain centering. Normalizing by the mean instead of the standard
deviation makes the policy gradient unbiased for the order-``group_size``
truncation of the maximum-likelihood objective (low-pass-rate examples get
~1/p weight; ``group_size`` interpolates REINFORCE at 1 → exact maximum
likelihood as it grows).
Assumes non-negative (canonically binary) rewards; a group with mean reward
<= 0 carries no signal and gets zero advantages (the zero-advantage filter
drops it, matching the paper's no-success convention)."""
async def score_group(self, group: list[Rollout]) -> None:
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
mean = rewards.mean()
advantages = torch.zeros_like(rewards) if mean <= 0 else (rewards - mean) / mean
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
rollout.assign_advantages(advantage)
+47
View File
@@ -0,0 +1,47 @@
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import OPDAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.utils.client import StaticInferencePool
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
from prime_rl.transport import TrainingSample
from prime_rl.utils.client import InferencePool
class OPDAlgorithm(Algorithm):
"""On-policy distillation. Needs a teacher: the frozen reference model the
per-token reverse KL is computed against.
The policy samples its own rollouts; at ship time each sample's full
context is prefill-scored under the teacher (``ref_logprobs`` on the
wire), and the trainer evaluates the KL against the live policy. No
credit is assigned — rollouts keep ``advantages=None`` (advantage-based
filters never fire) and samples ship no advantage stream; ``group_size``
only fans out sampling."""
action_loss_type = "ref_kl"
def __init__(self, config: OPDAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
self.teacher = config.teacher
self.teacher_pool: StaticInferencePool | None = None # static teacher endpoint, connected in setup()
async def setup(self) -> None:
pool = await self.connect(self.teacher)
if not isinstance(pool, StaticInferencePool):
raise TypeError("opd teacher must be a static endpoint — prefill scoring needs fixed endpoints")
self.teacher_pool = pool
async def score_rollout(self, rollout: Rollout) -> None:
pool = self.teacher_pool
assert pool is not None, "teacher pool not connected — Algorithm.setup() must run first"
async def score_sample(sample: TrainingSample) -> None:
sample.ref_logprobs = await pool.score(list(sample.token_ids))
await asyncio.gather(*(score_sample(sample) for sample in rollout.samples))
+77
View File
@@ -0,0 +1,77 @@
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import OPSDAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm
if TYPE_CHECKING:
from renderers.base import Renderer
from prime_rl.orchestrator.types import Rollout
from prime_rl.transport import TrainingSample
from prime_rl.utils.client import InferencePool
class OPSDAlgorithm(Algorithm):
"""On-policy self-distillation (SDFT). The teacher *is* the live policy,
conditioned on an expert demonstration — no separate model, no extra
deployment.
Each sample is prefill-scored under the policy with the demonstration
prepended as a leading system message: the teacher reads
``hint_block + sample.token_ids`` and the demo-conditioned logprobs over the
sample's tokens become ``ref_logprobs`` (the trainer's ref_kl target). The
sample is scored verbatim — no re-rendering — so the join lands on the
message-closing special token (BPE-clean) and it's robust to tools /
multimodal prompts and any number of turns. No scalar advantage is
assigned."""
action_loss_type = "ref_kl"
def __init__(self, config: OPSDAlgoConfig, policy_pool: InferencePool):
super().__init__(config, policy_pool)
self.demo_key = config.demo_key
self.template = config.template
self.renderer_config = config.renderer
self.renderer: Renderer | None = None # opsd builds its own in setup()
# Self-distillation: the teacher *is* the live policy. Scoring against
# the shared policy pool tracks its current weights, model name, and
# endpoint churn for free.
self.teacher_pool = self.policy_pool
async def setup(self) -> None:
"""Build opsd's own hint-block renderer from config — it is not handed
the policy's renderer. The tokenizer is always the live policy's
(self-distillation has no separate model), so the hint tokenizes
identically to the policy's own prompts."""
from renderers.base import create_renderer, load_tokenizer
self.renderer = create_renderer(load_tokenizer(self.policy_pool.model_name), self.renderer_config)
def _demonstration(self, rollout: Rollout) -> str:
demonstration = rollout.info.get(self.demo_key)
if demonstration is None:
demonstration = getattr(rollout.task, self.demo_key, None)
if demonstration is None:
raise ValueError(
f"opsd requires '{self.demo_key}' in the trace info dict or on the task "
f"(env '{rollout.env_name}', task {rollout.task.idx})."
)
return demonstration
async def score_rollout(self, rollout: Rollout) -> None:
pool = self.teacher_pool
renderer = self.renderer
assert renderer is not None, "renderer not built — Algorithm.setup() must run first"
hint = self.template.format(demonstration=self._demonstration(rollout))
hint_block = renderer.render_ids([{"role": "system", "content": hint}], add_generation_prompt=False)
async def score_sample(sample: TrainingSample) -> None:
full_logprobs = await pool.score(hint_block + list(sample.token_ids))
# Drop the hint's own logprobs; the tail aligns full-length to
# sample.token_ids (demo-conditioned, the trainer's ref_kl target).
sample.ref_logprobs = full_logprobs[len(hint_block) :]
await asyncio.gather(*(score_sample(sample) for sample in rollout.samples))
+74
View File
@@ -0,0 +1,74 @@
"""Wire-field stamping for the per-token streams.
The training loss is a sum of three components — ``rl`` (importance-weighted
PG + KL), ``ce`` (masked NLL), and ``ref_kl`` (reverse KL to a reference model
as the PG signal) — each normalized by its own global token count in the
trainer. The algorithm decides which component the action tokens feed
and the per-token advantages the rl component consumes; these helpers write
the component weight streams and the advantage stream onto the
``TrainingSample`` wire fields at group finalization.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import ActionLossType
from prime_rl.transport import TrainingSample
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
def stamp_loss_routing(sample: TrainingSample, action_loss_type: ActionLossType) -> None:
"""Stamp the algorithm's loss routing onto one sample's component weight
streams: action tokens (the trainable completion tokens, per the loss
mask) feed the algorithm's declared component.
``rl`` is the default and ships nothing (absent streams mean rl weight
1.0 on the loss mask — the hot path); ``ce``/``ref_kl`` weight the action
tokens into that component's stream and zero the rl stream. Streams an
algorithm wrote directly (echo's observation ce weights) are merged, not
clobbered — env-provided tokens stay out of the loss ``mask``, so the
component an algorithm weights them into is the only one that trains
them.
"""
if action_loss_type == "rl":
return
seq_len = len(sample.token_ids)
sample.rl_weights = [0.0] * seq_len
action_weights = (
sample.ce_weights if action_loss_type == "ce" and sample.ce_weights is not None else [0.0] * seq_len
)
for i, trains in enumerate(sample.mask):
if trains:
action_weights[i] = 1.0
if action_loss_type == "ce":
sample.ce_weights = action_weights
else:
assert action_loss_type == "ref_kl"
sample.ref_kl_weights = action_weights
def stamp_advantages(rollout: Rollout) -> None:
"""Stamp the rollout's per-token advantage stream onto its samples' wire
fields. The stream is full-length-N — aligned to the samples' ``token_ids``
concatenated in order, 0.0 on non-trainable positions — and sliced across
them. Rollouts with no credit assigned (``advantages=None``, e.g. opd/opsd)
ship no advantage stream.
"""
advantages = rollout.advantages
if advantages is None:
return
total = sum(len(sample.token_ids) for sample in rollout.samples)
if len(advantages) != total:
raise ValueError(
f"advantage stream must align with the rollout's tokens: "
f"got {len(advantages)}, expected {total} (env '{rollout.env_name}')."
)
offset = 0
for sample in rollout.samples:
num_tokens = len(sample.token_ids)
sample.advantages = list(advantages[offset : offset + num_tokens])
offset += num_tokens
+14
View File
@@ -0,0 +1,14 @@
from __future__ import annotations
from prime_rl.orchestrator.algo.base import Algorithm
class SFTDistillAlgorithm(Algorithm):
"""Hard distillation. Needs a teacher: the frozen model that generates the
rollouts (``sampling.source``); the policy trains with CE on its tokens.
Assigns no advantage — the ``ce`` loss ignores credit, and SFT trains on
every sampled token. Reward-based filtering, if wanted, is an explicit
filter, not smuggled through an unused advantage stream."""
action_loss_type = "ce"
+29 -26
View File
@@ -4,7 +4,7 @@
A group-scoring task that runs N rollouts in one call reserves N permits.
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
- Emit-everything invariant: every dispatched rollout eventually reaches
``out_q`` exactly once as a ``TrainRollout`` / ``EvalRollout``. Failures
``out_q`` exactly once as a ``Rollout``. Failures
(env error, empty trajectory, task exception, off-policy cancel) carry
``trace.error`` set; sinks decide drop / partial-train policy.
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
@@ -15,7 +15,9 @@
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.
so they are allowed to finish even if training advances. Train rollouts
sampled from a frozen model never age — their sampler doesn't change
with policy updates.
Cancellations surface as synthetic ``Cancelled`` markers so the sink's
count-to-``group_size`` finalization still fires.
"""
@@ -114,7 +116,7 @@ class DispatcherMetrics:
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
rollouts under shared capacity, and emits ``Rollout``\\ s to
``out_q``. The watcher drives ``on_version_pending`` for off-policy
cancellation; the orchestrator triggers eval epochs."""
@@ -125,26 +127,20 @@ class RolloutDispatcher:
eval_envs: EvalEnvs | None,
train_source: TrainSource,
eval_source: EvalSource | None,
inference: InferencePool,
eval_inference: InferencePool,
policy_pool: InferencePool,
policy: Policy,
max_inflight_rollouts: int,
tasks_per_minute: float | None,
max_off_policy_steps: int,
training_mode: Literal["rl", "opd", "sft"],
use_cache_salt: bool = True,
) -> None:
self.policy = policy
self.train_envs = train_envs
self.eval_envs = eval_envs
# Train rollouts go to ``inference`` (the teacher in SFT mode);
# eval always evaluates the student, so it uses ``eval_inference``.
self.inference = inference
self.eval_inference = eval_inference
# Train rollouts go to the env sampler's pool; eval always
# evaluates the policy.
self.policy_pool = policy_pool
self.train_source = train_source
self.eval_source = eval_source
self.training_mode = training_mode
self.use_cache_salt = use_cache_salt
self.max_off_policy_steps = max_off_policy_steps
self.max_inflight = max_inflight_rollouts
@@ -174,14 +170,13 @@ class RolloutDispatcher:
self.stopped = asyncio.Event()
self.task: asyncio.Task | None = None
@property
def train_model_name(self) -> str:
"""Model name for *train* rollouts. In SFT mode train data comes from
the teacher pool, so use its model name; otherwise the live student
policy. (Eval always uses ``policy.model_name`` — the student.)"""
if self.training_mode == "sft":
return self.inference.model_name
return self.policy.model_name
def _train_pool_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
"""``(pool, model_name, is_live)`` for *train* rollouts of this env —
the env sampler's pool. (Eval always uses the policy.)"""
sampler = self.train_envs.get(env_name).sampler
if sampler.samples_from_live_policy:
return sampler.pool, self.policy.model_name, True
return sampler.pool, sampler.pool.model_name, False
@property
def inflight_train_count(self) -> int:
@@ -277,6 +272,10 @@ class RolloutDispatcher:
for meta in self.inflight.values():
if meta.kind != "train":
continue
# Frozen-sourced rollouts never go stale — their sampler doesn't
# change with policy updates.
if not self.train_envs.get(meta.env_name).sampler.samples_from_live_policy:
continue
meta.off_policy_steps += 1
if meta.off_policy_steps > self.max_off_policy_steps:
stale_groups.add(meta.group_id)
@@ -394,14 +393,15 @@ class RolloutDispatcher:
ready, no permits). Returns True after issuing one task — the caller
loops to keep scheduling.
"""
# Train rollouts use the rollout pool (teacher in SFT) via the
# renderer/token train client. Eval always evaluates the student and
# Train rollouts use the env sampler's pool via the
# renderer/token train client. Eval always evaluates the policy and
# goes through the eval client (chat-completions) — the same path the
# legacy orchestrator used, so eval scores stay comparable.
if group.kind == "eval":
pool, model_name = self.eval_inference, self.policy.model_name
pool, model_name = self.policy_pool, self.policy.model_name
live_sourced = True
else:
pool, model_name = self.inference, self.train_model_name
pool, model_name, live_sourced = self._train_pool_for(group.env_name)
# Pin a single client per group to keep prefix-cache hits
if group.pinned_client is None:
@@ -422,7 +422,10 @@ class RolloutDispatcher:
if env_collection is None:
return False
env = env_collection.get(group.env_name)
if group.kind == "eval" or self.use_cache_salt:
# Frozen-sourced train rollouts hit a frozen pool; salting per policy
# version would invalidate its prefix cache every weight update for
# no reason.
if live_sourced:
cache_salt = str(group.policy_version_at_start)
else:
cache_salt = None
+16 -10
View File
@@ -30,7 +30,8 @@ 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.algo import Algorithm, build_algorithm
from prime_rl.orchestrator.sampler import Sampler
from prime_rl.orchestrator.types import Rollout
from prime_rl.utils.logger import get_logger
@@ -202,13 +203,11 @@ class Env:
class TrainEnv(Env):
config: TrainEnvConfig
def __init__(self, config: TrainEnvConfig, max_seq_len: int):
def __init__(self, config: TrainEnvConfig, sampler: Sampler, algorithm: Algorithm):
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.
self.advantage_fn: AdvantageFn | None = (
setup_advantage_fn(config.advantage, max_seq_len=max_seq_len) if config.advantage is not None else None
)
self.sampler = sampler
self.algorithm = algorithm
self.sampling_args = sampler.sampling_args(config.sampling.to_sampling_args())
class EvalEnv(Env):
@@ -277,12 +276,19 @@ class Envs(Generic[EnvT]):
class TrainEnvs(Envs[TrainEnv]):
"""Collection of training environments."""
"""Collection of training environments, each paired with its rollout
:class:`Sampler` and runtime :class:`Algorithm`, built from the env's
resolved algorithm config."""
def __init__(self, configs: Sequence[TrainEnvConfig], max_seq_len: int):
def __init__(self, configs: Sequence[TrainEnvConfig], *, policy_pool, renderer_config=None):
self._envs: dict[str, TrainEnv] = {}
for config in configs:
env = TrainEnv(config, max_seq_len=max_seq_len)
assert config.algo is not None, "TrainEnvConfig.algo must be resolved before env construction"
env = TrainEnv(
config,
Sampler(config.algo.sampling, policy_pool, renderer_config),
build_algorithm(config.algo, policy_pool),
)
self._envs[env.name] = env
+1 -1
View File
@@ -131,7 +131,7 @@ class EvalSink:
if valid:
rewards = [r.reward for r in valid]
lens = [r.completion_len 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))
+16 -19
View File
@@ -22,7 +22,6 @@ if TYPE_CHECKING:
@dataclass
class FilterResult:
detected: bool
detection_index: int | None = None
class RolloutFilter(Protocol):
@@ -50,16 +49,15 @@ class GibberishFilter:
enforce: bool = False
def check(self, rollout: Rollout) -> FilterResult:
global_idx = 0
for node in rollout.nodes:
# token_ids / logprobs / mask are per-token aligned; check only the
# sampled completion tokens, pairing each with its own logprob.
for token_id, logprob, sampled in zip(node.token_ids, node.logprobs, node.mask):
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)
@@ -81,12 +79,12 @@ class RepetitionFilter:
enforce: bool = False
def check(self, rollout: Rollout) -> FilterResult:
consecutive = 0
global_idx = 0
for node in rollout.nodes:
# Streak only over sampled completion tokens — context/prompt tokens
# (mask=False) are not model-generated and must not feed the loop count.
for logprob, sampled in zip(node.logprobs, node.mask):
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:
@@ -94,21 +92,20 @@ class RepetitionFilter:
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)
@dataclass
class ZeroAdvantageFilter:
"""Flags rollouts whose computed advantage is zero (e.g. all rollouts in a
GRPO group earned the same reward, so the centered advantage collapses)."""
"""Flags rollouts whose advantage stream is all zero (e.g. all rollouts in
a GRPO group earned the same reward, so the centered advantage collapses)."""
name: str
enforce: bool = True
def check(self, rollout: Rollout) -> FilterResult:
if rollout.advantage is not None and rollout.advantage == 0.0:
if rollout.advantages is not None and all(a == 0.0 for a in rollout.advantages):
return FilterResult(detected=True)
return FilterResult(detected=False)
-2
View File
@@ -23,7 +23,6 @@ class MetricsBuilder:
progress: Progress,
step_time: float,
save_ckpt_time: float,
teacher_logprobs_time: float,
pre_filter_seen: int,
pre_filter_dropped: int,
pre_filter_dropped_by_name: dict[str, int],
@@ -118,7 +117,6 @@ class MetricsBuilder:
"effective_batch_size/all": effective_batch_size,
**{f"batch/{env}": r for env, r in results_df.env_name.value_counts(normalize=True).items()},
"time/step": step_time,
"time/teacher_logprobs": teacher_logprobs_time,
"time/save_ckpt": save_ckpt_time,
"filters/all/is_filtered": results_df.is_filtered.astype(float).mean(),
**{f"filters/all/{name}": filter_df[name].astype(float).mean() for name in filter_df.columns},
+46 -92
View File
@@ -3,8 +3,8 @@
``Orchestrator`` owns the shared state (policy, progress, ckpt, monitor)
and drives the pipeline. Components are single-purpose:
- ``RolloutDispatcher`` schedules rollouts; emits ``TrainRollout`` /
``EvalRollout`` on its queue.
- ``RolloutDispatcher`` schedules rollouts; emits ``Rollout`` (train/eval
discriminated by ``kind``) on its queue.
- ``TrainSink`` ingests train rollouts (tokenize → advantages → filters)
and returns a ``TrainBatch`` when the threshold is met.
- ``EvalSink`` ingests eval rollouts and returns an ``EvalBatch`` (with
@@ -60,19 +60,18 @@ from prime_rl.orchestrator.types import (
TrainBatch,
)
from prime_rl.orchestrator.utils import (
compute_teacher_logprobs,
get_weight_dir,
intercept_vf_logging,
save_rollouts,
set_default_executor,
setup_student_inference_pool,
setup_policy_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 EventLoopLagMonitor, EventLoopLagStats, safe_cancel
from prime_rl.utils.client import init_nccl_broadcast, setup_inference_pool
from prime_rl.utils.client import init_nccl_broadcast
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.monitor import setup_monitor
@@ -101,13 +100,6 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
# resumed when the watcher advances ``policy.version``.
TARGET_LAG = 1
# 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:
# Set in ``__init__``
@@ -124,7 +116,7 @@ class Orchestrator:
# Always set by ``setup()``
tokenizer: PreTrainedTokenizer
student_inference: InferencePool
policy_inference: InferencePool
monitor: Monitor
sender: TrainingBatchSender
train_envs: TrainEnvs
@@ -139,7 +131,6 @@ class Orchestrator:
# Set by ``setup()`` only when relevant config is present
renderer: Renderer | None
mm_token_type_ids_mapping: dict[int, int] | None
teacher_inference: InferencePool | None
heart: Heartbeat | None
usage_reporter: UsageReporter | None
inference_metrics: InferenceMetricsCollector | None
@@ -156,7 +147,8 @@ class Orchestrator:
# 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})")
algorithms = sorted({env.algo.type for env in config.train.env if env.algo is not None})
get_logger().info(f"Starting orchestrator (algorithm: {', '.join(algorithms)})")
if config.bench:
get_logger().warning(f"Running in benchmark mode (max_steps={config.max_steps})")
@@ -180,7 +172,6 @@ class Orchestrator:
# config is present
self.renderer = None
self.mm_token_type_ids_mapping = None
self.teacher_inference = None
self.heart = None
self.usage_reporter = None
self.inference_metrics = None
@@ -208,12 +199,14 @@ class Orchestrator:
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
self.tokenizer = setup_tokenizer(config.tokenizer)
# Student inference pool
# The one model prime-rl hosts: the live policy. Frozen model
# references are external endpoints — each env's Algorithm builds its
# own pools in ``setup()`` below.
get_logger().info(
f"Initializing student inference pool (base_url={', '.join(config.student.client.base_url)}, "
f"model={config.student.model.name})"
f"Initializing policy inference pool (base_url={', '.join(config.model.client.base_url)}, "
f"model={config.model.name})"
)
self.renderer, self.student_inference = await setup_student_inference_pool(
self.renderer, self.policy_inference = await setup_policy_inference_pool(
config=config, tokenizer=self.tokenizer
)
self.mm_token_type_ids_mapping = (
@@ -222,21 +215,6 @@ class Orchestrator:
if self.mm_token_type_ids_mapping == {}:
self.mm_token_type_ids_mapping = None
if config.teacher is not None:
get_logger().info(
f"Initializing teacher inference pool (base_url={', '.join(config.teacher.client.base_url)}, "
f"model={config.teacher.model.name})"
)
self.teacher_inference = await setup_inference_pool(
config.teacher.client,
model_name=config.teacher.model.name,
# 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})")
self.monitor = setup_monitor(
wandb_config=config.wandb,
@@ -260,10 +238,9 @@ 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, max_seq_len=config.seq_len)
if config.training_mode == "sft":
for env in self.train_envs:
env.sampling_args.pop("logprobs", None)
self.train_envs = TrainEnvs(
config.train.env, policy_pool=self.policy_inference, renderer_config=config.renderer
)
get_logger().debug(
f"Loaded {len(self.train_envs)} training environment(s) ({', '.join(self.train_envs.names)})"
)
@@ -292,20 +269,21 @@ class Orchestrator:
self.resume_step = config.ckpt.resume_step
# Resume below may bump ``policy.version`` and the LoRA model name
self.policy.model_name = self.student_inference.model_name
self.policy.model_name = self.policy_inference.model_name
get_logger().info("Waiting for student inference pool to be ready")
await self.student_inference.wait_for_ready(config.student.model.name)
get_logger().success("Student inference pool ready")
if self.teacher_inference is not None:
assert config.teacher is not None
get_logger().info("Waiting for teacher inference pool to be ready")
await self.teacher_inference.wait_for_ready(config.teacher.model.name)
get_logger().success("Teacher inference pool ready")
get_logger().info("Waiting for policy inference pool to be ready")
await self.policy_inference.wait_for_ready(config.model.name)
get_logger().success("Policy inference pool ready")
# Build + ready pools for each env's frozen sampling source and the
# algorithm's frozen reference model
await asyncio.gather(
*(env.sampler.setup() for env in self.train_envs),
*(env.algorithm.setup() for env in self.train_envs),
)
if config.wandb is not None and config.collect_inference_metrics:
self.inference_metrics = InferenceMetricsCollector(
self.student_inference.admin_clients,
self.policy_inference.admin_clients,
roles=config.inference_metrics_roles,
)
await self.inference_metrics.start()
@@ -313,7 +291,7 @@ class Orchestrator:
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
if config.weight_broadcast.type == "nccl":
await init_nccl_broadcast(
self.student_inference.admin_clients,
self.policy_inference.admin_clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
@@ -324,7 +302,7 @@ class Orchestrator:
get_logger().info(f"Initializing training batch sender ({config.rollout_transport})")
self.sender = setup_training_batch_sender(config.output_dir, config.rollout_transport)
self.lora_name = config.student.model.lora.name if config.student.model.lora else None
self.lora_name = config.model.lora.name if config.model.lora else None
if self.resume_step is not None and self.ckpt_manager is not None:
self.ckpt_manager.load(self.progress, step=self.resume_step)
@@ -334,23 +312,14 @@ class Orchestrator:
weights_path = get_weight_dir(
config.output_dir, self.progress.step, check_exists=check_exists, wait_timeout=wait_timeout
)
await self.student_inference.update_weights(weights_path, lora_name=self.lora_name, step=self.progress.step)
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=self.progress.step)
if self.lora_name is not None:
self.student_inference.update_model_name(self.lora_name)
self.policy_inference.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
self.policy.version = self.progress.step
else:
get_logger().info("Training from scratch")
# SFT train rollouts come from the teacher when configured; otherwise
# they use the existing student rollout pool.
if config.training_mode == "sft" and self.teacher_inference is not None:
rollout_inference = self.teacher_inference
use_cache_salt = False
else:
rollout_inference = self.student_inference
use_cache_salt = True
self.train_source = TrainSource(self.train_envs, seed=42)
self.eval_source: EvalSource | None = (
EvalSource(
@@ -370,14 +339,11 @@ class Orchestrator:
eval_envs=self.eval_envs,
train_source=self.train_source,
eval_source=self.eval_source,
inference=rollout_inference,
eval_inference=self.student_inference,
policy_pool=self.policy_inference,
policy=self.policy,
max_inflight_rollouts=config.max_inflight_rollouts,
tasks_per_minute=config.tasks_per_minute,
max_off_policy_steps=config.max_off_policy_steps,
training_mode=config.training_mode,
use_cache_salt=use_cache_salt,
)
self.metrics = MetricsBuilder(config)
self.train_sink = TrainSink(
@@ -394,7 +360,7 @@ class Orchestrator:
self.watcher = WeightWatcher(
config,
policy=self.policy,
inference=self.student_inference,
inference=self.policy_inference,
observers=[self.dispatcher, self],
lora_name=self.lora_name,
ckpt_step=self.progress.step,
@@ -475,7 +441,7 @@ class Orchestrator:
trim_process_memory()
async def main_loop(self) -> None:
"""Consume ``FinishedRollout``\\ s from the dispatcher and route them
"""Consume ``Rollout``\\ s from the dispatcher and route them
to the train / eval sink. Both sinks return a finalized batch (or
``None``) from ``add()``; we just dispatch on the result."""
while not self.stopped.is_set():
@@ -504,7 +470,7 @@ class Orchestrator:
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,
side-effects (ckpt, save_rollouts, reference scoring, sender.send,
metrics, heartbeat, progress, eval trigger). The sink has already
done all data-transformation work."""
config = self.config
@@ -548,25 +514,13 @@ class Orchestrator:
f"({batch.metrics.n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
)
# 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]
# Serialize the typed Trace at the I/O boundary (disk + wandb sample tables); to_record
# drops the per-node training tensors — they're for training, not the rollout record, and
# can't round-trip json (raw numpy bytes).
rollout_dicts = [r.to_record() 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")
teacher_logprobs_time = 0.0 # opd only
if config.training_mode == "opd" and self.teacher_inference is not None:
assert config.teacher is not None
t = time.perf_counter()
teacher_logprobs_list = await compute_teacher_logprobs(
clients=self.teacher_inference.train_clients,
model_name=config.teacher.model.name,
samples=batch.samples,
)
for ex, lp in zip(batch.samples, teacher_logprobs_list):
ex.teacher_logprobs = lp
teacher_logprobs_time = time.perf_counter() - t
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
self.update_dispatch_gate()
trim_process_memory()
@@ -578,7 +532,6 @@ class Orchestrator:
progress=self.progress,
step_time=step_time,
save_ckpt_time=save_ckpt_time,
teacher_logprobs_time=teacher_logprobs_time,
pre_filter_seen=self.train_sink.pre_filter_seen,
pre_filter_dropped=self.train_sink.pre_filter_dropped,
pre_filter_dropped_by_name=dict(self.train_sink.pre_filter_dropped_by_name),
@@ -588,7 +541,7 @@ class Orchestrator:
self.monitor.log_distributions(
distributions={
"rewards": [r.reward for r in batch.rollouts],
"advantages": [r.advantage for r in batch.rollouts if r.advantage is not None],
"advantages": [a for r in batch.rollouts if (a := r.scalar_advantage()) is not None],
},
step=step,
)
@@ -756,7 +709,7 @@ class Orchestrator:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no surviving rollouts, skipping log")
return
rollout_dicts = [r.model_dump(mode="json", exclude=ROLLOUT_DUMP_EXCLUDE) for r in batch.rollouts]
rollout_dicts = [r.to_record() 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,
@@ -859,11 +812,12 @@ class Orchestrator:
self.component_tasks.clear()
if self.inference_metrics is not None:
await self.inference_metrics.stop()
if self.student_inference is not None:
await self.student_inference.stop()
if self.teacher_inference is not None:
await self.teacher_inference.stop()
if getattr(self, "policy_inference", None) is not None:
await self.policy_inference.stop()
if self.train_envs is not None:
for env in self.train_envs:
for pool in (*env.sampler.connected_pools, *env.algorithm.connected_pools):
await pool.stop()
self.train_envs.shutdown()
if self.eval_envs is not None:
self.eval_envs.shutdown()
+59
View File
@@ -0,0 +1,59 @@
"""How an env's train rollouts are produced — the sample strategy.
The algorithm (``algo/``) consumes finalized rollouts and compiles them into
per-token loss-component weights; the sampler owns where those rollouts come
from. Today that is one question — which model generates them — and its
consequences (sampling logprobs, prefix-cache salting, and off-policy
staleness are all liveness questions about the source). Future sampling
strategies (replay buffers, branching) extend here, not the algorithm.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import FrozenModelConfig, SamplingConfig
from prime_rl.orchestrator.algo import connect_frozen_pool
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.utils.client import InferencePool
class Sampler:
"""One env's rollout source.
``pool`` is the pool train rollouts are generated from: the policy pool,
swapped for a connected frozen pool in :meth:`setup` when the source is an
inline frozen model. A frozen source *generates* rollouts, so its pool uses
the renderer (token-in/out) client (built from ``renderer_config``) — the
rollout must carry tokens for training."""
def __init__(
self, config: SamplingConfig, policy_pool: InferencePool, renderer_config: RendererConfig | None = None
):
assert config.source is not None, "sampling.source must be resolved by config validation"
self.config = config
self.pool: InferencePool = policy_pool
self.renderer_config = renderer_config
self.connected_pools: list[InferencePool] = [] # client pools connected in setup(); closed at shutdown
async def setup(self) -> None:
"""Connect a client pool to a frozen sampling source and wait for
readiness. Must run before dispatching."""
if isinstance(self.config.source, FrozenModelConfig):
self.pool = await connect_frozen_pool(self.config.source, renderer_config=self.renderer_config)
self.connected_pools.append(self.pool)
@property
def samples_from_live_policy(self) -> bool:
return self.config.source == "policy"
def sampling_args(self, args: dict) -> dict:
"""Source-specific sampling-arg overrides. Sampling logprobs are only
needed for importance ratios on policy-sampled tokens — frozen
endpoints may reject the knob."""
if not self.samples_from_live_policy:
args.pop("logprobs", None)
return args
+20 -17
View File
@@ -1,14 +1,17 @@
"""TrainSink: three-level rollout sink for the training side.
1. ``process_rollout`` — eager per-rollout tokenization (overlaps with
dispatcher producing more rollouts). Errored rollouts skip this.
2. ``process_group`` — filters errored rollouts, computes advantages over
survivors, runs the pre-batch filter pass.
dispatcher producing more rollouts), then the env algorithm's
``finalize_rollout`` (rollout-local scoring + any reference I/O). Errored
rollouts skip this.
2. ``process_group`` — filters errored rollouts, hands survivors to the env
algorithm's ``finalize_group`` (advantages + per-sample wire stamping),
runs the pre-batch filter pass.
3. ``process_batch`` — applies post-batch filter annotations and assembles
the trainer-bound ``TrainingSample`` list. Returns a ``TrainBatch``.
``add()`` returns ``TrainBatch | None``. I/O concerns (ship to trainer,
save_rollouts, monitor.log, teacher logprobs) live on the orchestrator.
save_rollouts, monitor.log) live on the orchestrator.
"""
from __future__ import annotations
@@ -18,7 +21,6 @@ import uuid
from collections import defaultdict
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 trace_to_samples
@@ -126,7 +128,7 @@ class TrainSink:
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):
self.process_group(rollout.group_id)
await self.process_group(rollout.group_id)
ready = (
len(self.pending_batch) >= self.batch_size
if self.batch_size is not None
@@ -150,8 +152,12 @@ class TrainSink:
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
)
rollout.samples = samples or []
# Arrival phase: rollout-local scoring (raw reward, echo observation
# weighting, opd/opsd reference logprobs) runs as soon as the rollout is
# tokenized — before its group is complete.
await self.train_envs.get(rollout.env_name).algorithm.finalize_rollout(rollout)
def process_group(self, group_id: uuid.UUID) -> None:
async def process_group(self, group_id: uuid.UUID) -> None:
"""Finalize one GRPO group: drop errored rollouts (the whole group
when ``requires_group_scoring`` and any failed), assign advantages,
run pre-batch filters, append survivors to ``pending_batch``."""
@@ -179,19 +185,16 @@ class TrainSink:
)
return
assign_advantages(survivors, env.advantage_fn)
# Advantages + per-sample wire stamping (advantage stream, loss
# routing) are the algorithm's job (finalize_group); the sink only
# owns the grouping mechanics.
await env.algorithm.finalize_group(survivors)
# 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 per token (context
# tokens are masked out, so their temperature is don't-care).
# The env 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:
sample.advantage = r.advantage
sample.reward = r.reward
sample.env_name = r.env_name
sample.training_mode = self.config.training_mode
sample.temperatures = [temperature] * len(sample.token_ids)
if self.pre_filters:
@@ -252,7 +255,7 @@ class TrainSink:
apply_filters(self.post_filters, cohort)
# Samples are pre-built by ``process_rollout``; ``process_group``
# already set advantage/reward on each sample
# already stamped the advantage stream and loss routing on each sample
samples: list[TrainingSample] = []
prefill_lens: list[int] = []
decode_lens: list[int] = []
@@ -100,8 +100,6 @@ def trace_to_samples(
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,
+38 -2
View File
@@ -71,7 +71,12 @@ class Rollout(vf.Trace[TaskT], Generic[TaskT]):
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."""
``results.jsonl`` is unchanged.
It is also the single currency the scoring hooks receive: a hook reads the trace
directly (``rollout.reward``, ``rollout.nodes``, ``rollout.num_turns``) and writes
credit through :meth:`assign_advantages` (scalar broadcast or per-token), which
spreads over the samples' trainable (mask-True) tokens."""
model_config = ConfigDict(arbitrary_types_allowed=True) # ``samples`` holds msgspec structs
@@ -81,11 +86,42 @@ class Rollout(vf.Trace[TaskT], Generic[TaskT]):
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)
# Per-token rl advantage stream, full-length-N (= len(token_ids)) per
# sample, concatenated across the rollout's samples in order; 0.0 on
# non-trainable positions. None = no credit assigned (advantage-based
# filters skip it; the wire ships no advantage stream).
advantages: list[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)
def assign_advantages(self, values: float | list[float]) -> None:
"""Write the rl advantage stream: a scalar broadcast over the
rollout's trainable (mask-True) tokens (0.0 elsewhere), or a per-token
list already aligned full-length to the samples' concatenated
``token_ids``. A rollout never assigned ships no advantage stream."""
total = sum(len(sample.token_ids) for sample in self.samples)
if isinstance(values, (int, float)):
self.advantages = [
float(values) if trainable else 0.0 for sample in self.samples for trainable in sample.mask
]
return
if len(values) != total:
raise ValueError(
f"per-token advantages must align with the rollout's tokens: "
f"got {len(values)}, expected {total} (env '{self.env_name}')."
)
self.advantages = [float(v) for v in values]
def scalar_advantage(self) -> float | None:
"""Scalar view of the per-token advantage stream for monitoring: the
mean over assigned (non-zero) positions — exact for the uniform GRPO
case, 0.0 for a zero-advantage group, None when no credit was assigned."""
if not self.advantages:
return None
nonzero = [a for a in self.advantages if a != 0.0]
return sum(nonzero) / len(nonzero) if nonzero else 0.0
@dataclass
class TrainBatchMetrics:
+24 -72
View File
@@ -2,17 +2,14 @@ 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.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, setup_logger
from prime_rl.utils.utils import (
@@ -22,20 +19,26 @@ from prime_rl.utils.utils import (
)
async def setup_student_inference_pool(*, config: OrchestratorConfig, tokenizer):
"""Build the student renderer and inference pool, returning ``(renderer, inference_pool)``.
async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
"""Build the live policy inference pool + matching renderer. Returns
``(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)."""
Training is renderer-only: the renderer object is the canonical
messages → token ids path (sft backfill, opsd scoring prefixes, echo role
attribution) and is always built. The renderer-client sampling path is
wired onto the pool; when no train env samples from the live policy the
renderer is still kept for client-side tokenization and the pool's evals
use plain chat-completions."""
from renderers.base import create_renderer
client_config = config.student.client
model_name = config.student.model.name
client_config = config.model.client
model_name = config.model.name
renderer = create_renderer(tokenizer, config.renderer)
get_logger().info("Using renderer rollout client")
get_logger().info(f"Initialized {type(renderer).__name__} for {model_name}")
if config.any_policy_sourced:
get_logger().info("Using direct renderer rollout client")
else:
get_logger().info("No policy-sourced train env — renderer kept for client-side tokenization only")
inference_pool = await setup_inference_pool(
client_config,
model_name=model_name,
@@ -90,65 +93,14 @@ def trim_process_memory() -> None:
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
async def compute_teacher_logprobs(
clients: list[vf.ClientConfig],
model_name: str,
samples: list[TrainingSample],
) -> 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 = 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
# under ``/v1``. Pass an absolute URL so the SDK's
# ``_prepare_url`` skips the base-url merge (it short-circuits
# when the path passes ``httpx.URL.is_relative_url`` as False).
# 2. Parse — vLLM's ``GenerateResponse`` is a plain
# ``pydantic.BaseModel`` and the SDK's parse layer rejects any
# ``cast_to`` that doesn't subclass ``openai.BaseModel``. Use
# ``cast_to=httpx.Response`` so the SDK still builds the request
# (preserving ``auth_headers``, retries, timeouts, idempotency
# keys) and just hands us the raw response to validate ourselves.
base = str(client.base_url).rstrip("/").removesuffix("/v1")
http_response = await client.post(
f"{base}/inference/v1/generate",
cast_to=httpx.Response,
body={
"model": model_name,
"token_ids": list(sample.token_ids),
"sampling_params": {
"max_tokens": 1,
"temperature": 1.0,
"top_p": 1.0,
"prompt_logprobs": 1,
},
},
)
response = GenerateResponse.model_validate_json(http_response.content)
# ``prompt_logprobs[i]`` is a ``{token_id: Logprob}`` dict for tokens
# the engine could score, or ``None`` for the leading token which has
# no preceding context. Flatten to ``list[float]`` with 0.0 in the
# unscored slot.
flat: list[float] = []
for entry in response.prompt_logprobs or []:
if not entry:
flat.append(0.0)
continue
first = next(iter(entry.values()))
lp = first.logprob if hasattr(first, "logprob") else first.get("logprob")
flat.append(float(lp) if lp is not None else 0.0)
return flat
return await asyncio.gather(*[_compute_single(client, sample) for client, sample in zip(cycle(clients), samples)])
def get_tool_response_len(trace: vf.Trace) -> 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."""
for key, value in (trace.metrics or {}).items():
if key.endswith("total_tool_response_tokens") and isinstance(value, (int, float)):
return int(value)
return 0
def get_weight_dir(output_dir: Path, step: int, check_exists: bool = True, wait_timeout: int | None = None) -> Path:
+116 -34
View File
@@ -13,6 +13,11 @@ ROUTED_EXPERTS_DTYPE_ITEMSIZE = {
"int32": 4,
}
# Backfill value per component weight stream when a packed sample doesn't
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
# means no component (weight 0.0).
STREAM_FILL = {"rl_weights": 1.0, "ce_weights": 0.0, "ref_kl_weights": 0.0}
def _copy_routed_experts(routed_experts: RoutedExperts) -> RoutedExperts:
return RoutedExperts(
@@ -103,9 +108,22 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
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)
if training_example.advantages is not None:
advantages = list(training_example.advantages)
else:
rl_w = training_example.rl_weights
has_rl_members = any(loss_mask) if rl_w is None else any(m and w != 0 for m, w in zip(loss_mask, rl_w))
if has_rl_members:
raise ValueError(
f"sample from env '{training_example.env_name}' has rl member tokens but no advantages — "
"the producer must stamp the advantage stream (the orchestrator broadcasts the rollout scalar)"
)
advantages = [0.0] * len(input_ids)
# Component weight streams: keep absent streams None (rl weight 1.0 on the
# loss mask, no ce/ref_kl component) so the packed batch stays as small as before.
rl_weights = list(training_example.rl_weights) if training_example.rl_weights is not None else None
ce_weights = list(training_example.ce_weights) if training_example.ce_weights is not None else None
ref_kl_weights = list(training_example.ref_kl_weights) if training_example.ref_kl_weights is not None else None
position_ids = list(range(len(input_ids)))
mm_token_type_ids = training_example.mm_token_type_ids
mm_kwargs = training_example.mm_kwargs
@@ -115,9 +133,9 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
# 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
teacher_logprobs = training_example.teacher_logprobs
# Ref logprobs already cover the full sequence (prompt + completion),
# computed via prefill in the orchestrator when the algorithm scores against a reference
ref_logprobs = training_example.ref_logprobs
routed_experts = (
_copy_routed_experts(training_example.routed_experts) if training_example.routed_experts is not None else None
)
@@ -133,10 +151,15 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
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[:cut]
if ref_logprobs is not None:
ref_logprobs = ref_logprobs[:cut]
if rl_weights is not None:
rl_weights = rl_weights[:cut]
if ce_weights is not None:
ce_weights = ce_weights[:cut]
if ref_kl_weights is not None:
ref_kl_weights = ref_kl_weights[:cut]
if routed_experts is not None:
routed_experts = _slice_routed_experts(routed_experts, cut)
if mm_token_type_ids is not None:
@@ -149,13 +172,19 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
== len(loss_mask)
== len(position_ids)
== len(inference_logprobs)
== len(rewards)
== len(temperatures)
), (
f"input_ids: {len(input_ids)}, advantages: {len(advantages)}, loss_mask: {len(loss_mask)}, position_ids: {len(position_ids)}, inference_logprobs: {len(inference_logprobs)}, rewards: {len(rewards)}, temperatures: {len(temperatures)}"
f"input_ids: {len(input_ids)}, advantages: {len(advantages)}, loss_mask: {len(loss_mask)}, position_ids: {len(position_ids)}, inference_logprobs: {len(inference_logprobs)}, temperatures: {len(temperatures)}"
)
if teacher_logprobs is not None:
assert len(teacher_logprobs) == len(input_ids), f"teacher_logprobs: {len(teacher_logprobs)}"
if ref_logprobs is not None:
assert len(ref_logprobs) == len(input_ids), f"ref_logprobs: {len(ref_logprobs)}"
for stream_name, stream in (
("rl_weights", rl_weights),
("ce_weights", ce_weights),
("ref_kl_weights", ref_kl_weights),
):
if stream is not None:
assert len(stream) == len(input_ids), f"{stream_name}: {len(stream)}"
if routed_experts is not None:
assert routed_experts.shape[0] == len(input_ids), (
@@ -176,14 +205,15 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
position_ids=position_ids,
inference_logprobs=inference_logprobs,
sequence_lengths=[len(input_ids)],
teacher_logprobs=teacher_logprobs,
ref_logprobs=ref_logprobs,
temperatures=temperatures,
rewards=rewards,
routed_experts=routed_experts,
mm_token_type_ids=mm_token_type_ids,
env_names=env_names,
mm_kwargs=mm_kwargs,
training_mode=training_example.training_mode,
rl_weights=rl_weights,
ce_weights=ce_weights,
ref_kl_weights=ref_kl_weights,
)
@@ -206,12 +236,14 @@ class _MicroBatchBin:
return self.samples[0][1]
def can_add(self, sample: MicroBatch, max_seq_len: int) -> bool:
# Loss routing is per token (component weight streams), so samples of
# different loss types pack together freely — only modality, length and
# routed-experts presence constrain packing.
first_sample = self.first_sample
return (
not _is_multimodal_sample(first_sample)
and not _is_multimodal_sample(sample)
and self.length + len(sample.input_ids) <= max_seq_len
and first_sample.training_mode == sample.training_mode
and (first_sample.routed_experts is None) == (sample.routed_experts is None)
)
@@ -243,9 +275,11 @@ class _MicroBatchBin:
def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
has_rewards = any(sample.rewards is not None for _, sample in bin_content.samples)
has_teacher_logprobs = any(sample.teacher_logprobs is not None for _, sample in bin_content.samples)
has_ref_logprobs = any(sample.ref_logprobs is not None for _, sample in bin_content.samples)
has_mm_token_type_ids = any(sample.mm_token_type_ids is not None for _, sample in bin_content.samples)
# A weight stream materializes as soon as one packed sample carries it; the
# samples that lack it get the stream's identity fill (STREAM_FILL).
has_stream = {name: any(getattr(s, name) is not None for _, s in bin_content.samples) for name in STREAM_FILL}
input_ids: list[int] = []
loss_mask: list[bool] = []
@@ -254,9 +288,9 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
position_ids: list[int] = []
temperatures: list[float] = []
env_names: list[str] = []
rewards: list[float] | None = [] if has_rewards else None
teacher_logprobs: list[float] | None = [] if has_teacher_logprobs else None
ref_logprobs: list[float] | None = [] if has_ref_logprobs else None
mm_token_type_ids: list[int] | None = [] if has_mm_token_type_ids else None
streams: dict[str, list[float] | None] = {name: ([] if has_stream[name] else None) for name in STREAM_FILL}
routed_experts: RoutedExperts | None = None
lora_num_tokens = [0] * num_loras
@@ -269,12 +303,13 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
position_ids.extend(sample.position_ids)
temperatures.extend(sample.temperatures)
env_names.extend(sample.env_names)
if rewards is not None:
rewards.extend(sample.rewards if sample.rewards is not None else [float("nan")] * sample_len)
if teacher_logprobs is not None:
teacher_logprobs.extend(
sample.teacher_logprobs if sample.teacher_logprobs is not None else [0.0] * sample_len
)
if ref_logprobs is not None:
ref_logprobs.extend(sample.ref_logprobs if sample.ref_logprobs is not None else [0.0] * sample_len)
for name, fill in STREAM_FILL.items():
stream = streams[name]
if stream is not None:
sample_stream = getattr(sample, name)
stream.extend(sample_stream if sample_stream is not None else [fill] * sample_len)
if mm_token_type_ids is not None:
mm_token_type_ids.extend(
sample.mm_token_type_ids if sample.mm_token_type_ids is not None else [0] * sample_len
@@ -300,15 +335,16 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
position_ids=position_ids,
inference_logprobs=inference_logprobs,
sequence_lengths=sequence_lengths,
teacher_logprobs=teacher_logprobs,
ref_logprobs=ref_logprobs,
temperatures=temperatures,
rewards=rewards,
lora_num_tokens=lora_num_tokens,
routed_experts=routed_experts,
mm_token_type_ids=mm_token_type_ids,
env_names=env_names,
mm_kwargs=first_sample.mm_kwargs if _is_multimodal_sample(first_sample) else None,
training_mode=first_sample.training_mode,
rl_weights=streams["rl_weights"],
ce_weights=streams["ce_weights"],
ref_kl_weights=streams["ref_kl_weights"],
)
@@ -407,16 +443,21 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
micro_batch.input_ids.extend([1] * padding_size)
micro_batch.advantages.extend([0.0] * padding_size)
if micro_batch.rewards is not None:
micro_batch.rewards.extend([float("nan")] * padding_size)
micro_batch.loss_mask.extend([False] * padding_size)
micro_batch.position_ids.extend(list(range(padding_size)))
micro_batch.sequence_lengths.append(padding_size)
micro_batch.inference_logprobs.extend([0.0] * padding_size)
# Use temperature 1.0 for padding tokens (doesn't matter since loss_mask is False)
micro_batch.temperatures.extend([1.0] * padding_size)
if micro_batch.teacher_logprobs is not None:
micro_batch.teacher_logprobs.extend([0.0] * padding_size)
if micro_batch.ref_logprobs is not None:
micro_batch.ref_logprobs.extend([0.0] * padding_size)
# Padding is loss-masked, so no component trains it; fill every stream
# with 0.0 (not the pack-boundary defaults) so a padded pure-ce batch
# still reads as rl-empty in token export, which keys off nonzero weights.
for stream_name in STREAM_FILL:
stream = getattr(micro_batch, stream_name)
if stream is not None:
stream.extend([0.0] * padding_size)
if micro_batch.lora_num_tokens is not None:
micro_batch.lora_num_tokens[-1] += (
padding_size # We send padding to the last lora so that tokens have ascending lora idx
@@ -430,11 +471,48 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
return micro_batch
def _assert_token_arrays_aligned(micro_batch: MicroBatch) -> None:
"""Every per-token array must stay position-aligned with ``input_ids``
through packing and padding — a field extended without backfill would
corrupt training silently."""
num_tokens = len(micro_batch.input_ids)
per_token_fields = (
"loss_mask",
"advantages",
"inference_logprobs",
"position_ids",
"temperatures",
"env_names",
"ref_logprobs",
"rl_weights",
"ce_weights",
"ref_kl_weights",
"mm_token_type_ids",
)
for name in per_token_fields:
values = getattr(micro_batch, name)
assert values is None or len(values) == num_tokens, (
f"{name} misaligned after packing: {len(values)} != {num_tokens} tokens"
)
assert sum(micro_batch.sequence_lengths) == num_tokens, (
f"sequence_lengths sum {sum(micro_batch.sequence_lengths)} != {num_tokens} tokens"
)
if micro_batch.routed_experts is not None:
assert micro_batch.routed_experts.shape[0] == num_tokens, (
f"routed_experts misaligned after packing: {micro_batch.routed_experts.shape[0]} != {num_tokens} tokens"
)
def _make_dummy_batch(source: MicroBatch) -> MicroBatch:
"""Create a zero-loss dummy batch from an existing batch, preserving its modality."""
dummy = copy.deepcopy(source)
dummy.advantages = [0.0] * len(dummy.input_ids)
dummy.loss_mask = [False] * len(dummy.input_ids)
# ce/ref_kl membership is weight != 0 (independent of loss_mask), so the
# streams must go too or the dummy would still train those tokens.
dummy.rl_weights = None
dummy.ce_weights = None
dummy.ref_kl_weights = None
return dummy
@@ -478,6 +556,10 @@ def prepare_batch(
mm_batches = _pad_group_for_distribution(mm_batches, num_train_workers)
text_batches = _pad_group_for_distribution(text_batches, num_train_workers)
# Alignment check after distribution padding so the dummy batches are covered too
for micro_batch in (*mm_batches, *text_batches):
_assert_token_arrays_aligned(micro_batch)
batches_per_gpu: list[list[MicroBatch]] = [[] for _ in range(num_train_workers)]
for group in (mm_batches, text_batches):
group_batches_per_gpu = _distribute_group(group, num_train_workers, bin_cost)
@@ -10,6 +10,7 @@ from transformers.configuration_utils import PretrainedConfig
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import MoeModelOutputWithPast
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeVisionModel
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, logging
@@ -17,8 +18,8 @@ from transformers.utils import TransformersKwargs, logging
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig, apply_rotary_pos_emb
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids, get_cu_seqlens_from_seq_lens
from .configuration_qwen3_5_moe import Qwen3_5MoeConfig
from .converting_qwen3_5_moe import (
@@ -27,6 +28,7 @@ from .converting_qwen3_5_moe import (
convert_tt_layer_to_hf,
convert_tt_to_hf_moe,
)
from .mrope import build_qwen3_5_mrope_position_ids
# Flash attention imports
try:
@@ -668,22 +670,113 @@ class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
# ---------------------------------------------------------------------------
# Model classes
# Rotary embedding
# ---------------------------------------------------------------------------
def _create_rotary_emb(config: Qwen3_5MoeConfig) -> RotaryEmbedding:
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type", "default"))
else:
rope_type = "default"
class Qwen3_5MoeRotaryEmbedding(nn.Module):
inv_freq: torch.Tensor
rotary_config = RotaryEmbeddingConfig(
max_position_embeddings=config.max_position_embeddings,
rope_type=rope_type,
model_config=config,
)
return RotaryEmbedding(rotary_config)
def __init__(self, config: Qwen3_5MoeConfig, device=None):
super().__init__()
self.config = config
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
rope_parameters = getattr(config, "rope_parameters", None)
if rope_parameters is None:
config.standardize_rope_params()
rope_parameters = config.rope_parameters
self.rope_type = rope_parameters.get("rope_type", rope_parameters.get("type", "default"))
self.rope_init_fn = self.compute_default_rope_parameters
if self.rope_type != "default":
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = self.rope_init_fn(config, device)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.original_inv_freq = self.inv_freq.clone()
self.mrope_section = rope_parameters.get("mrope_section")
if self.mrope_section is None:
self.mrope_section = self._scaled_default_mrope_section(self.inv_freq.numel())
if not rope_parameters.get("mrope_interleaved", True):
raise ValueError("Qwen3.5 MoE custom model expects interleaved MRoPE")
if sum(self.mrope_section) != self.inv_freq.numel():
raise ValueError(
"Qwen3.5 mrope_section must sum to rotary_dim // 2: "
f"mrope_section={self.mrope_section}, rotary_dim={self.inv_freq.numel() * 2}"
)
@staticmethod
def _scaled_default_mrope_section(num_rotary_pairs: int) -> list[int]:
default_section = [11, 11, 10]
default_total = sum(default_section)
scaled_section = [num_rotary_pairs * section // default_total for section in default_section]
remainder = num_rotary_pairs - sum(scaled_section)
remainder_order = sorted(
range(len(default_section)),
key=lambda idx: num_rotary_pairs * default_section[idx] % default_total,
reverse=True,
)
for idx in remainder_order[:remainder]:
scaled_section[idx] += 1
return scaled_section
@staticmethod
def compute_default_rope_parameters(
config: Qwen3_5MoeConfig | None = None,
device: Optional[torch.device] = None,
seq_len: int | None = None,
) -> tuple[torch.Tensor, float]:
rope_parameters = config.rope_parameters
base = rope_parameters["rope_theta"]
partial_rotary_factor = rope_parameters.get("partial_rotary_factor", 1.0)
head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
dim = int(head_dim * partial_rotary_factor)
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
)
return inv_freq, 1.0
@torch.no_grad()
@dynamic_rope_update
def forward(self, x: torch.Tensor, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
if position_ids.ndim == 2:
position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
elif position_ids.ndim != 3:
raise ValueError(f"Qwen3.5 position_ids must be 2D or 3D, got shape={tuple(position_ids.shape)}")
position_ids = position_ids.to(device=x.device)
inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
position_ids_expanded = position_ids[:, :, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False):
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)
freqs = self._apply_interleaved_mrope(freqs)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos() * self.attention_scaling
sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
def _apply_interleaved_mrope(self, freqs: torch.Tensor) -> torch.Tensor:
freqs_t = freqs[0].clone()
for dim, offset in enumerate((1, 2), start=1):
length = self.mrope_section[dim] * 3
idx = slice(offset, length, 3)
freqs_t[..., idx] = freqs[dim, ..., idx]
return freqs_t
def _create_rotary_emb(config: Qwen3_5MoeConfig) -> Qwen3_5MoeRotaryEmbedding:
return Qwen3_5MoeRotaryEmbedding(config)
# ---------------------------------------------------------------------------
# Model classes
# ---------------------------------------------------------------------------
class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
@@ -757,6 +850,7 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
routed_experts: Optional[torch.LongTensor] = None,
seq_lens: Optional[torch.LongTensor] = None,
) -> MoeModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
@@ -764,9 +858,31 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
flash_attn_enabled = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
if flash_attn_enabled:
if position_ids.ndim == 3:
if inputs_embeds.shape[0] != 1:
raise ValueError("3D Qwen3.5 MRoPE positions require batch size 1 for varlen attention")
seq_len = inputs_embeds.shape[1]
if seq_lens is None:
cu_seqlens = torch.tensor([0, seq_len], dtype=torch.int32, device=inputs_embeds.device)
max_seqlen = seq_len
else:
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(
seq_lens.to(device=inputs_embeds.device),
total_tokens=seq_len,
)
else:
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
elif position_ids.ndim == 3 and seq_lens is not None:
seq_lens = seq_lens.to(device=inputs_embeds.device)
if seq_lens.numel() > 1 and "full_attention" in self.config.layer_types:
raise ValueError("Packed Qwen3.5 MRoPE batches with full_attention layers require flash attention")
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(seq_lens, total_tokens=inputs_embeds.shape[1])
else:
max_seqlen = None
cu_seqlens = None
@@ -822,6 +938,16 @@ class Qwen3_5MoeVLMModel(nn.Module):
def set_input_embeddings(self, value):
self.language_model.embed_tokens = value
def _dummy_vision_inputs(self, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:
"""Smallest valid vision input: a single merged token (grid [1, m, m])."""
vcfg = self.config.vision_config
m = vcfg.spatial_merge_size
num_patches = m * m
patch_dim = vcfg.in_channels * vcfg.temporal_patch_size * vcfg.patch_size * vcfg.patch_size
pixel_values = torch.zeros(num_patches, patch_dim, device=device, dtype=self.visual.dtype)
grid_thw = torch.tensor([[1, m, m]], dtype=torch.long, device=device)
return pixel_values, grid_thw
def forward(
self,
input_ids: torch.LongTensor | None = None,
@@ -829,28 +955,74 @@ class Qwen3_5MoeVLMModel(nn.Module):
inputs_embeds: torch.FloatTensor | None = None,
pixel_values: torch.Tensor | None = None,
image_grid_thw: torch.LongTensor | None = None,
mm_token_type_ids: torch.LongTensor | None = None,
routed_experts: torch.LongTensor | None = None,
seq_lens: torch.LongTensor | None = None,
**kwargs,
) -> MoeModelOutputWithPast:
if inputs_embeds is None:
inputs_embeds = self.language_model.embed_tokens(input_ids)
if pixel_values is not None:
pixel_values = pixel_values.type(self.visual.dtype)
vision_output = self.visual(pixel_values, grid_thw=image_grid_thw, return_dict=True)
image_embeds = vision_output.pooler_output.to(inputs_embeds.device, inputs_embeds.dtype)
if image_grid_thw is not None and input_ids is None:
raise ValueError("input_ids are required to compute Qwen3.5 multimodal MRoPE positions")
if image_grid_thw is not None and mm_token_type_ids is None:
raise ValueError(
"Qwen3.5 multimodal forward requires mm_token_type_ids to compute MRoPE positions correctly"
)
if image_grid_thw is not None and position_ids is not None and position_ids.ndim != 3:
raise ValueError(
f"Qwen3.5 multimodal forward requires 3D MRoPE position_ids; got shape={tuple(position_ids.shape)}"
)
# Keep distributed collectives in the same order when a batch mixes text-only
# and image samples across ranks. The frozen dummy pass is discarded below.
has_images = pixel_values is not None
vision_grid_thw = image_grid_thw
if has_images:
if input_ids is None:
raise ValueError("input_ids are required when scattering Qwen3.5 image features")
if image_grid_thw is None:
raise ValueError("image_grid_thw is required when pixel_values are provided")
pixel_values = pixel_values.type(self.visual.dtype)
else:
pixel_values, vision_grid_thw = self._dummy_vision_inputs(inputs_embeds.device)
vision_output = self.visual(pixel_values, grid_thw=vision_grid_thw, return_dict=True)
image_embeds = vision_output.pooler_output.to(inputs_embeds.device, inputs_embeds.dtype)
if has_images:
image_mask = input_ids == self.config.image_token_id
image_token_count = int(image_mask.sum().item())
image_feature_count = int(image_embeds.shape[0])
if image_token_count != image_feature_count:
raise ValueError(
"Qwen VLM image token/feature mismatch before scatter: "
f"image_token_id={self.config.image_token_id}, "
f"image_tokens={image_token_count}, image_features={image_feature_count}, "
f"input_ids_shape={tuple(input_ids.shape)}, "
f"pixel_values_shape={tuple(pixel_values.shape)}, "
f"image_grid_thw_shape={tuple(image_grid_thw.shape) if image_grid_thw is not None else None}"
)
image_mask = image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
if image_grid_thw is not None:
position_ids = build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=self.config.vision_config.spatial_merge_size,
seq_lens=seq_lens,
)
else:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
return self.language_model(
inputs_embeds=inputs_embeds,
position_ids=position_ids,
routed_experts=routed_experts,
seq_lens=seq_lens,
)
@@ -997,12 +1169,15 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
routed_experts: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.Tensor] = None,
image_grid_thw: Optional[torch.LongTensor] = None,
mm_token_type_ids: Optional[torch.LongTensor] = None,
seq_lens: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
assert use_cache is None, "use_cache is not supported for custom qwen3_5_moe for now"
assert past_key_values is None, "past_key_values is not supported for custom qwen3_5_moe for now"
if position_ids is None:
has_vlm_image_inputs = self._is_vlm and image_grid_thw is not None
if position_ids is None and not has_vlm_image_inputs:
if inputs_embeds is not None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
elif input_ids is not None:
@@ -1015,7 +1190,9 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
inputs_embeds=inputs_embeds,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
routed_experts=routed_experts,
seq_lens=seq_lens,
)
else:
outputs = self.model(
@@ -1023,6 +1200,7 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
position_ids=position_ids,
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
seq_lens=seq_lens,
)
hidden_states = outputs.last_hidden_state
@@ -0,0 +1,133 @@
from __future__ import annotations
import itertools
import torch
def get_qwen3_5_vision_position_ids(
*,
start_position: int,
grid_thw: torch.Tensor,
spatial_merge_size: int,
temp_merge_size: int = 1,
time_interval: int = 1,
device: torch.device | None = None,
) -> torch.LongTensor:
llm_grid_t = int(grid_thw[0].item()) // temp_merge_size
llm_grid_h = int(grid_thw[1].item()) // spatial_merge_size
llm_grid_w = int(grid_thw[2].item()) // spatial_merge_size
position_temporal = torch.arange(llm_grid_t, device=device) * time_interval
position_height = torch.arange(llm_grid_h, device=device) + start_position
position_width = torch.arange(llm_grid_w, device=device) + start_position
position_width = position_width.repeat(llm_grid_h * llm_grid_t)
position_height = position_height.repeat_interleave(llm_grid_w).repeat(llm_grid_t)
position_temporal = position_temporal.repeat_interleave(llm_grid_h * llm_grid_w) + start_position
return torch.stack([position_temporal, position_height, position_width], dim=0)
def build_qwen3_5_mrope_position_ids(
*,
input_ids: torch.LongTensor,
mm_token_type_ids: torch.LongTensor,
image_grid_thw: torch.LongTensor | None,
spatial_merge_size: int,
seq_lens: torch.Tensor | None = None,
) -> torch.LongTensor:
if input_ids.ndim != 2:
raise ValueError(f"input_ids must be 2D, got shape={tuple(input_ids.shape)}")
if mm_token_type_ids.shape != input_ids.shape:
raise ValueError(
"mm_token_type_ids must match input_ids shape: "
f"mm_token_type_ids={tuple(mm_token_type_ids.shape)}, input_ids={tuple(input_ids.shape)}"
)
if input_ids.shape[0] != 1:
raise ValueError("Packed Qwen3.5 MRoPE builder currently supports batch size 1")
total_seq_len = input_ids.shape[1]
if seq_lens is None:
seq_lens = torch.tensor([total_seq_len], dtype=torch.long, device=input_ids.device)
else:
seq_lens = seq_lens.to(device=input_ids.device, dtype=torch.long)
if seq_lens.ndim != 1:
raise ValueError(f"seq_lens must be 1D, got shape={tuple(seq_lens.shape)}")
if bool((seq_lens <= 0).any().item()):
raise ValueError(f"seq_lens must be positive, got {seq_lens.tolist()}")
if int(seq_lens.sum().item()) != total_seq_len:
raise ValueError(f"seq_lens sum must equal sequence length: {seq_lens.tolist()} vs {total_seq_len}")
image_grids = iter(image_grid_thw) if image_grid_thw is not None else None
all_positions = torch.empty(3, 1, total_seq_len, dtype=input_ids.dtype, device=input_ids.device)
offset = 0
for seq_len_tensor in seq_lens:
seq_len = int(seq_len_tensor.item())
token_types = mm_token_type_ids[0, offset : offset + seq_len]
current_pos = 0
segment_positions = []
for modality_type, group in itertools.groupby(enumerate(token_types.tolist()), lambda item: item[1]):
group = list(group)
group_len = group[-1][0] - group[0][0] + 1
if modality_type == 0:
segment_positions.append(
torch.arange(group_len, device=input_ids.device).view(1, -1).expand(3, -1) + current_pos
)
current_pos += group_len
continue
if modality_type == 2:
raise ValueError("Qwen3.5 video MRoPE is not supported by the custom trainer path yet")
if modality_type != 1:
raise ValueError(f"Unsupported Qwen3.5 multimodal token type: {modality_type}")
if image_grids is None:
raise ValueError("image_grid_thw is required when mm_token_type_ids contains image tokens")
remaining = group_len
while remaining > 0:
try:
grid_thw = next(image_grids)
except StopIteration as exc:
raise ValueError("Not enough image_grid_thw rows for image token groups") from exc
vision_positions = get_qwen3_5_vision_position_ids(
start_position=current_pos,
grid_thw=grid_thw,
spatial_merge_size=spatial_merge_size,
device=input_ids.device,
)
image_len = vision_positions.shape[1]
if image_len > remaining:
raise ValueError(
"Image token group length does not match image_grid_thw-derived token count: "
f"group_len={group_len}, grid_thw={grid_thw.tolist()}, "
f"derived={image_len}, spatial_merge_size={spatial_merge_size}"
)
segment_positions.append(vision_positions)
current_pos += max(int(grid_thw[1].item()), int(grid_thw[2].item())) // spatial_merge_size
remaining -= image_len
if not segment_positions:
raise ValueError("Cannot build MRoPE positions for an empty sequence segment")
segment_position_ids = torch.cat(segment_positions, dim=1)
if segment_position_ids.shape[1] != seq_len:
raise ValueError(
f"Built MRoPE length does not match segment length: {segment_position_ids.shape[1]} vs {seq_len}"
)
all_positions[:, 0, offset : offset + seq_len] = segment_position_ids
offset += seq_len
if image_grids is not None:
try:
extra_grid = next(image_grids)
except StopIteration:
pass
else:
raise ValueError(f"Unused image_grid_thw row while building MRoPE positions: {extra_grid.tolist()}")
return all_positions
+51
View File
@@ -270,7 +270,58 @@ class ParallelDims:
return get_logger()
def _is_moe_model(config: ModelConfig) -> bool:
"""Return True if the model has MoE layers, by loading its HuggingFace config."""
from transformers import AutoConfig
model_config = AutoConfig.from_pretrained(config.name, trust_remote_code=config.trust_remote_code)
return hasattr(model_config, "num_experts") or hasattr(model_config, "n_routed_experts")
def resolve_ep(config: ModelConfig) -> None:
"""Resolve ``ep="auto"`` in-place to a concrete integer.
For MoE models, resolves to ``min(fsdp_island_size, 8)`` where
``fsdp_island_size = world_size // dp_replicate``. For non-MoE
models, resolves to 1 (no-op).
"""
if config.ep != "auto":
return
# EP requires the custom implementation; skip auto-resolution for HF impl
if config.impl not in ("custom", "auto"):
config.ep = 1
get_logger().info(f"EP auto: impl='{config.impl}' does not support EP, resolving ep=1")
return
world_size = dist.get_world_size()
if not _is_moe_model(config):
config.ep = 1
get_logger().info("EP auto: model is not MoE, resolving ep=1")
return
dp_replicate = config.dp_replicate
fsdp_island_size = world_size // dp_replicate # pp is always 1
resolved_ep = min(fsdp_island_size, 8)
config.ep = resolved_ep
get_logger().info(f"EP auto: world_size={world_size}, dp_replicate={dp_replicate} -> resolved ep={resolved_ep}")
if config.ep_comm_backend != "torch" and config.ep <= 1:
raise ValueError(
f"model.ep_comm_backend='{config.ep_comm_backend}' requires ep > 1, "
f"but auto-resolved ep=1 (world_size={world_size}). "
"Set ep explicitly or use ep_comm_backend='torch'."
)
def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> ParallelDims:
assert isinstance(config.ep, int), (
f"config.ep must be resolved to an int before get_parallel_dims; got {config.ep!r}. "
"Call resolve_ep(config) first."
)
# Initialize parallel dimensions
parallel_dims = ParallelDims(
dp_replicate=config.dp_replicate,
@@ -77,7 +77,7 @@ class FileSystemWeightBroadcast(WeightBroadcast):
self.logger.debug(f"Saving weights for run {idx} to {save_dir}")
save_state_dict(state_dict, save_dir, self.save_format, self.save_sharded, adapter=adapter_only)
if adapter_only:
orch_lora = self.multi_run_manager.config[idx].student.model.lora
orch_lora = self.multi_run_manager.config[idx].model.lora
save_lora_config(
model,
save_dir,
+25 -17
View File
@@ -26,9 +26,8 @@ class TensorMicroBatch(TypedDict):
input_ids: Int[Tensor, "batch seq"]
position_ids: Int[Tensor, "batch seq"]
advantages: Float[Tensor, "batch seq"]
rewards: Float[Tensor, "batch seq"] | None
inference_logprobs: Float[Tensor, "batch seq"]
teacher_logprobs: Float[Tensor, "batch seq"] | None
ref_logprobs: Float[Tensor, "batch seq"] | None
loss_mask: Bool[Tensor, "batch seq"]
temperatures: Float[Tensor, "batch seq"] # Per-token temperatures
env_names: list[str]
@@ -49,9 +48,11 @@ class TensorMicroBatch(TypedDict):
# mm_token_type_ids: token type per token [batch seq], int64 (0=text, 1=image, 2=video)
mm_token_type_ids: Int[Tensor, "batch seq"] | None
# Selects loss dispatch (rl/opd → default loss with mode-specific taus,
# sft → sft loss). All samples in a micro batch share the same mode.
training_mode: str
# Per-token component weight streams. ``None`` means absent: no ce/ref_kl
# component, rl weight 1.0 on every loss-masked token.
rl_weights: Float[Tensor, "batch seq"] | None
ce_weights: Float[Tensor, "batch seq"] | None
ref_kl_weights: Float[Tensor, "batch seq"] | None
# Packer-derived metadata used for run-local debug exports.
run_id: str | None
@@ -122,9 +123,8 @@ class FakeDataLoader:
"input_ids": input_ids.unsqueeze(0),
"position_ids": position_ids.unsqueeze(0),
"advantages": advantages.unsqueeze(0),
"rewards": None,
"inference_logprobs": inference_logprobs.unsqueeze(0),
"teacher_logprobs": None,
"ref_logprobs": None,
"temperatures": torch.ones(input_ids.shape[0]).unsqueeze(0),
"env_names": ["fake"] * input_ids.shape[0],
"sequence_lengths": sequence_lengths,
@@ -133,7 +133,9 @@ class FakeDataLoader:
"routed_experts": None,
"mm_kwargs": None,
"mm_token_type_ids": None,
"training_mode": "rl",
"rl_weights": None,
"ce_weights": None,
"ref_kl_weights": None,
"run_id": None,
"run_step": None,
}
@@ -153,9 +155,8 @@ class FakeDataLoader:
),
"position_ids": torch.cat([torch.arange(self.seq_len)]).unsqueeze(0),
"advantages": torch.randn(self.seq_len, generator=generator).unsqueeze(0),
"rewards": None,
"inference_logprobs": torch.randn(self.seq_len, generator=generator).unsqueeze(0),
"teacher_logprobs": None,
"ref_logprobs": None,
"temperatures": torch.ones(self.seq_len).unsqueeze(0),
"env_names": ["fake"] * self.seq_len,
"sequence_lengths": [self.seq_len],
@@ -164,7 +165,9 @@ class FakeDataLoader:
"routed_experts": None,
"mm_kwargs": None,
"mm_token_type_ids": None,
"training_mode": "rl",
"rl_weights": None,
"ce_weights": None,
"ref_kl_weights": None,
"run_id": None,
"run_step": None,
}
@@ -247,12 +250,9 @@ class DataLoader:
input_ids=torch.tensor(micro_batch.input_ids, dtype=torch.long).unsqueeze(0),
position_ids=torch.tensor(micro_batch.position_ids, dtype=torch.long).unsqueeze(0),
advantages=torch.tensor(micro_batch.advantages, dtype=torch.float).unsqueeze(0),
rewards=torch.tensor(micro_batch.rewards, dtype=torch.float).unsqueeze(0)
if micro_batch.rewards is not None
else None,
inference_logprobs=torch.tensor(micro_batch.inference_logprobs, dtype=torch.float).unsqueeze(0),
teacher_logprobs=torch.tensor(micro_batch.teacher_logprobs, dtype=torch.float).unsqueeze(0)
if micro_batch.teacher_logprobs is not None
ref_logprobs=torch.tensor(micro_batch.ref_logprobs, dtype=torch.float).unsqueeze(0)
if micro_batch.ref_logprobs is not None
else None,
loss_mask=torch.tensor(micro_batch.loss_mask, dtype=torch.bool).unsqueeze(0),
temperatures=torch.tensor(micro_batch.temperatures, dtype=torch.float).unsqueeze(0),
@@ -264,7 +264,15 @@ class DataLoader:
if micro_batch.mm_token_type_ids is not None
else None,
routed_experts=routed_experts,
training_mode=micro_batch.training_mode,
rl_weights=torch.tensor(micro_batch.rl_weights, dtype=torch.float).unsqueeze(0)
if micro_batch.rl_weights is not None
else None,
ce_weights=torch.tensor(micro_batch.ce_weights, dtype=torch.float).unsqueeze(0)
if micro_batch.ce_weights is not None
else None,
ref_kl_weights=torch.tensor(micro_batch.ref_kl_weights, dtype=torch.float).unsqueeze(0)
if micro_batch.ref_kl_weights is not None
else None,
run_id=micro_batch.run_id,
run_step=micro_batch.run_step,
)
+138 -93
View File
@@ -1,4 +1,4 @@
from dataclasses import dataclass
from dataclasses import dataclass, field
from typing import Any, Callable
import torch
@@ -12,13 +12,20 @@ from prime_rl.utils.utils import import_object
@dataclass
class LossInputs:
"""Inputs for computing loss on a single sample."""
"""Inputs for computing loss on a single sample.
``loss_mask`` already selects the tokens that belong to the receiving
component — the component loss functions never re-derive eligibility.
``loss_weights`` is the component's per-token weight stream (None means
1.0 everywhere).
"""
trainer_logprobs: Float[Tensor, " seq"]
inference_logprobs: Float[Tensor, " seq"]
teacher_logprobs: Float[Tensor, " seq"] | None
ref_logprobs: Float[Tensor, " seq"] | None
advantages: Float[Tensor, " seq"]
loss_mask: Bool[Tensor, " seq"]
loss_weights: Float[Tensor, " seq"] | None = field(default=None)
@dataclass
@@ -150,7 +157,10 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
advantages = loss_config.adv_tau * advantages
pg_loss = keep_mask * advantages * importance_ratio
kl_loss = loss_mask * log_importance_ratio**2
loss = (-pg_loss + loss_config.kl_tau * kl_loss).sum()
per_token_loss = -pg_loss + loss_config.kl_tau * kl_loss
if inputs.loss_weights is not None:
per_token_loss = per_token_loss * inputs.loss_weights
loss = per_token_loss.sum()
metrics = {
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
@@ -166,6 +176,9 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
"""IPO loss type: a symmetric trust region (mask tokens whose probability
moved more than ``ipo_threshold`` in absolute terms), policy gradient via
the importance ratio, and a squared-log-ratio KL regularizer."""
trainer_logprobs = inputs.trainer_logprobs
inference_logprobs = inputs.inference_logprobs
advantages = inputs.advantages
@@ -183,7 +196,10 @@ def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
advantages = loss_config.adv_tau * advantages
pg_loss = keep_mask * advantages * importance_ratio
kl_loss = loss_mask * log_importance_ratio**2
loss = (-pg_loss + loss_config.kl_tau * kl_loss).sum()
per_token_loss = -pg_loss + loss_config.kl_tau * kl_loss
if inputs.loss_weights is not None:
per_token_loss = per_token_loss * inputs.loss_weights
loss = per_token_loss.sum()
metrics = {
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
@@ -194,86 +210,74 @@ def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
return LossOutputs(loss=loss, metrics=metrics)
def opd_loss_fn(inputs: LossInputs) -> LossOutputs:
def ref_kl_loss_fn(inputs: LossInputs) -> LossOutputs:
"""
On-policy distillation loss: the default DPPO+KL math with the tau knobs
hardcoded to drop the reward signal and use the teacher KL as the
per-token policy-gradient signal.
Ref-KL loss type (on-policy distillation): the reverse KL to the reference
model is the per-token policy-gradient signal, with the importance ratio
correcting trainer/inference mismatch and staleness. A one-sided trust
region drops tokens whose trainer probability fell more than 0.2 below the
inference probability; a squared-log-ratio term regularizes drift. Scalar
advantages are not read — ref_kl algorithms ship none.
"""
trainer_logprobs = inputs.trainer_logprobs
inference_logprobs = inputs.inference_logprobs
teacher_logprobs = inputs.teacher_logprobs
advantages = inputs.advantages
ref_logprobs = inputs.ref_logprobs
loss_mask = inputs.loss_mask
if teacher_logprobs is None:
raise ValueError("opd_loss_fn requires teacher_logprobs - configure a teacher for opd mode.")
if ref_logprobs is None:
raise ValueError("ref_kl loss type requires ref_logprobs — use the 'opd' or 'opsd' algorithm.")
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
trainer_logprobs, inference_logprobs
)
probs_diff = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
dppo_invalid_mask_high = probs_diff > 0.2
dppo_invalid_mask_low = probs_diff < -0.2
positive_advantages = advantages > 0
negative_advantages = advantages < 0
dppo_invalid_mask = torch.where(positive_advantages, dppo_invalid_mask_high, dppo_invalid_mask_low)
is_masked = dppo_invalid_mask
is_masked_high = positive_advantages & dppo_invalid_mask_high
is_masked_low = negative_advantages & dppo_invalid_mask_low
is_masked = probs_diff < -0.2
drop_mask = loss_mask & is_masked
keep_mask = loss_mask & ~is_masked
teacher_kl = teacher_logprobs - trainer_logprobs
advantages = 0.0 * advantages + 1.0 * teacher_kl.detach()
ref_kl = ref_logprobs - trainer_logprobs
pg_loss = keep_mask * advantages * importance_ratio
pg_loss = keep_mask * ref_kl.detach() * importance_ratio
kl_loss = loss_mask * log_importance_ratio**2
loss = (-pg_loss + 1e-3 * kl_loss).sum()
per_token_loss = -pg_loss + 1e-3 * kl_loss
if inputs.loss_weights is not None:
per_token_loss = per_token_loss * inputs.loss_weights
loss = per_token_loss.sum()
# Namespaced: the rl loss fn emits same-named trust-region metrics with a
# different definition, and mixed batches run both fns in one step.
metrics = {
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked),
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
"is_masked": _safe_mean(is_masked, loss_mask),
"is_masked_low": _safe_mean(is_masked_low, loss_mask),
"is_masked_high": _safe_mean(is_masked_high, loss_mask),
"masked_advantage_positive": _safe_mean(positive_advantages, drop_mask),
"masked_advantage_negative": _safe_mean(negative_advantages, drop_mask),
"teacher_kl": _safe_mean(teacher_kl, loss_mask),
"ref_kl/masked_mismatch_kl": _safe_mean(mismatch_kl, drop_mask),
"ref_kl/unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
"ref_kl/is_masked": _safe_mean(is_masked, loss_mask),
"ref_kl": _safe_mean(ref_kl, loss_mask),
}
return LossOutputs(loss=loss, metrics=metrics)
def sft_loss_fn(inputs: LossInputs) -> LossOutputs:
"""SFT-style masked negative log-likelihood over trainable tokens."""
def ce_loss_fn(inputs: LossInputs) -> LossOutputs:
"""Cross-entropy loss type: masked negative log-likelihood (SFT / ECHO
observation prediction)."""
trainer_logprobs = inputs.trainer_logprobs
loss_mask = inputs.loss_mask
loss = -(trainer_logprobs[loss_mask]).sum()
nll = -trainer_logprobs
if inputs.loss_weights is not None:
nll = nll * inputs.loss_weights
loss = nll[loss_mask].sum()
metrics = {
"nll": _safe_mean(-trainer_logprobs, loss_mask),
}
return LossOutputs(loss=loss, metrics=metrics)
def setup_loss_fns(loss_config: LossConfig) -> dict[str, LossFn]:
"""Build the per-training-mode loss fn dispatch table.
Always returns all three modes - the trainer is mode-agnostic and routes
per batch from ``TrainingSample.training_mode``:
- ``"sft"`` → ``sft_loss_fn`` (masked NLL on teacher tokens)
- ``"opd"`` → ``opd_loss_fn`` (teacher KL as gradient signal, hardcoded
DPPO + KL knobs)
- ``"rl"`` → ``default_loss_fn(loss_config)`` for ``DefaultLossConfig``,
``ipo_loss_fn(loss_config)`` for ``IPOLossConfig``, or the imported
function for ``CustomLossConfig``.
``trainer.loss`` only affects the rl path - opd and sft are independent.
"""
def setup_rl_loss_fn(loss_config: LossConfig) -> LossFn:
"""Build the loss fn for the rl component from ``trainer.loss``:
``default_loss_fn`` (``DefaultLossConfig``), ``ipo_loss_fn``
(``IPOLossConfig``), or the imported function (``CustomLossConfig``).
The ce / ref_kl loss types are fixed and unaffected by ``trainer.loss``."""
if isinstance(loss_config, CustomLossConfig):
custom_fn = import_object(loss_config.import_path)
kwargs = loss_config.kwargs
@@ -289,78 +293,119 @@ def setup_loss_fns(loss_config: LossConfig) -> dict[str, LossFn]:
def rl_fn(inputs: LossInputs) -> LossOutputs:
return default_loss_fn(inputs, loss_config)
return {"sft": sft_loss_fn, "opd": opd_loss_fn, "rl": rl_fn}
return rl_fn
def compute_loss(
trainer_logprobs: list[Float[Tensor, " seq_i"]],
inference_logprobs: list[Float[Tensor, " seq_i"]],
teacher_logprobs: list[Float[Tensor, " seq_i"]] | None,
ref_logprobs: list[Float[Tensor, " seq_i"]] | None,
advantages: list[Float[Tensor, " seq_i"]],
loss_mask: list[Bool[Tensor, " seq_i"]],
loss_fns: dict[str, LossFn],
loss_scale: int,
training_mode: str = "rl",
rl_weights: list[Float[Tensor, " seq_i"]] | None,
ce_weights: list[Float[Tensor, " seq_i"]] | None,
ref_kl_weights: list[Float[Tensor, " seq_i"]] | None,
rl_loss_fn: LossFn,
rl_scale: int,
ce_scale: int,
ref_kl_scale: int,
) -> tuple[Float[Tensor, ""], dict[str, Any]]:
"""
Compute loss for packed sequences (batch size = 1, multiple sequences packed along sequence dimension).
Loss dispatch is batch-driven: ``training_mode`` selects the loss fn from
``loss_fns`` (built by ``setup_loss_fns``). sft → sft_loss_fn, opd →
opd_loss_fn, rl → the configured default/custom loss.
The loss is a sum of three components, each running over its own per-token
weight stream and normalized by its own global token count:
- rl → ``rl_loss_fn`` (built by ``setup_rl_loss_fn``) on
``loss_mask & (rl_weights != 0)``; an absent stream means weight 1.0 on
the full loss mask (the hot path — no extra device syncs).
- ce → ``ce_loss_fn`` (masked NLL) on ``ce_weights != 0``.
- ref_kl → ``ref_kl_loss_fn`` on ``ref_kl_weights != 0``.
A weight scales its component's per-token loss; 0.0 removes the token from
the component's mask and denominator. Per-component normalization keeps the
components from diluting each other: a token only enters the denominator of
the components it belongs to.
Args:
trainer_logprobs: Log probabilities for each sequence
inference_logprobs: Reference log probabilities for each sequence
teacher_logprobs: Teacher log probabilities for each sequence, or None
inference_logprobs: Sampling-policy log probabilities for each sequence
ref_logprobs: Reference-model log probabilities for each sequence, or None
advantages: Advantages for each sequence
loss_mask: Loss mask for each sequence
loss_fns: Per-mode loss fn dispatch table from setup_loss_fns()
loss_scale: Scale factor to normalize the loss
training_mode: Selects which loss fn to apply
rl_weights: Per-token rl weights for each sequence, or None (1.0 on the loss mask)
ce_weights: Per-token ce weights for each sequence, or None (no ce component)
ref_kl_weights: Per-token ref_kl weights for each sequence, or None (no ref_kl component)
rl_loss_fn: Loss fn for the rl component from setup_rl_loss_fn()
rl_scale: Global rl-token count normalizing the rl component
ce_scale: Global ce-token count normalizing the ce component
ref_kl_scale: Global ref_kl-token count normalizing the ref_kl component
Returns:
Tuple of (scaled_loss, aggregated_metrics)
"""
try:
effective_loss_fn = loss_fns[training_mode]
except KeyError:
raise ValueError(
f"No loss fn available for training_mode={training_mode!r} "
f"(available: {sorted(loss_fns)}). Check trainer.loss.type."
)
total_loss = 0.0
all_metrics: dict[str, list[Tensor]] = {}
if teacher_logprobs is None:
teacher_logprobs = [None] * len(trainer_logprobs)
n = len(trainer_logprobs)
if ref_logprobs is None:
ref_logprobs = [None] * n
if rl_weights is None:
rl_weights = [None] * n
if ce_weights is None:
ce_weights = [None] * n
if ref_kl_weights is None:
ref_kl_weights = [None] * n
for t_logp, i_logp, teach_logp, adv, mask in zip(
def run_loss_fn(loss_fn: LossFn, inputs: LossInputs) -> Tensor:
result = loss_fn(inputs)
for k, v in result.metrics.items():
all_metrics.setdefault(k, []).append(v)
return result.loss
# Graph anchor: a micro batch whose components are all empty (e.g. a fully
# truncated distillation sample, whose stamped streams survive as all-zero
# prefixes) must still return a backward-able loss so every rank runs
# backward and FSDP collectives stay in sync.
rl_loss = trainer_logprobs[0].sum() * 0.0
ce_loss = 0.0
ref_kl_loss = 0.0
for t_logp, i_logp, ref_logp, adv, mask, rl_w, ce_w, ref_kl_w in zip(
trainer_logprobs,
inference_logprobs,
teacher_logprobs,
ref_logprobs,
advantages,
loss_mask,
rl_weights,
ce_weights,
ref_kl_weights,
):
inputs = LossInputs(
trainer_logprobs=t_logp,
inference_logprobs=i_logp,
teacher_logprobs=teach_logp,
advantages=adv,
loss_mask=mask,
)
result = effective_loss_fn(inputs)
def make_inputs(component_mask: Bool[Tensor, " seq"], weights: Float[Tensor, " seq"] | None) -> LossInputs:
return LossInputs(
trainer_logprobs=t_logp,
inference_logprobs=i_logp,
ref_logprobs=ref_logp,
advantages=adv,
loss_mask=component_mask,
loss_weights=weights,
)
total_loss = total_loss + result.loss
if rl_w is None:
rl_loss = rl_loss + run_loss_fn(rl_loss_fn, make_inputs(mask, None))
else:
rl_mask = mask & (rl_w != 0)
if bool(rl_mask.any()):
rl_loss = rl_loss + run_loss_fn(rl_loss_fn, make_inputs(rl_mask, rl_w))
if ce_w is not None:
ce_mask = ce_w != 0
if bool(ce_mask.any()):
ce_loss = ce_loss + run_loss_fn(ce_loss_fn, make_inputs(ce_mask, ce_w))
if ref_kl_w is not None:
ref_kl_mask = ref_kl_w != 0
if bool(ref_kl_mask.any()):
ref_kl_loss = ref_kl_loss + run_loss_fn(ref_kl_loss_fn, make_inputs(ref_kl_mask, ref_kl_w))
for k, v in result.metrics.items():
if k not in all_metrics:
all_metrics[k] = []
all_metrics[k].append(v)
scaled_loss = total_loss / loss_scale
scaled_loss = rl_loss / rl_scale + ce_loss / ce_scale + ref_kl_loss / ref_kl_scale
aggregated: dict[str, Any] = {}
for k, v in all_metrics.items():
+2 -2
View File
@@ -178,10 +178,10 @@ class MultiPacker(BasePacker):
False,
f"Run wrote a sample with length {sample_length} which exceeds max sequence length {self.seq_len}",
)
if sample.teacher_logprobs is not None and len(sample.teacher_logprobs) != sample_length:
if sample.ref_logprobs is not None and len(sample.ref_logprobs) != sample_length:
return (
False,
f"Run wrote a sample with teacher logprobs length != sample length ({len(sample.teacher_logprobs)} != {sample_length})",
f"Run wrote a sample with ref logprobs length != sample length ({len(sample.ref_logprobs)} != {sample_length})",
)
return True, None
+13 -3
View File
@@ -70,7 +70,6 @@ class TokenExporter:
"export_sequence_idx": self._sequences_by_file.get(file_key, 0),
"run_id": run_id,
"env_name": _first_non_empty(columns["env_names"][start:end]),
"training_mode": str(micro_batch["training_mode"]),
**_slice_columns(columns, start, end),
},
run_id,
@@ -152,7 +151,6 @@ def _export_columns(
"position_ids": _tensor_to_ints(micro_batch["position_ids"]),
"loss_mask": _tensor_to_bools(micro_batch["loss_mask"]),
"advantages": _tensor_to_floats(micro_batch["advantages"]),
"rewards": _optional_tensor_to_floats(micro_batch.get("rewards"), seq_len),
"inference_logprobs": _tensor_to_floats(micro_batch["inference_logprobs"]),
"trainer_logprobs": _tensor_to_floats(trainer_logprobs),
"entropy": _tensor_to_floats(model_output["entropy"]),
@@ -163,6 +161,11 @@ def _export_columns(
"is_masked": _optional_tensor_to_bools(export_tensors["is_masked"], seq_len),
"is_masked_high": _optional_tensor_to_bools(export_tensors["is_masked_high"], seq_len),
"is_masked_low": _optional_tensor_to_bools(export_tensors["is_masked_low"], seq_len),
# Component weight streams; ``None`` columns mean the defaults (rl 1.0
# on the loss mask, no ce/ref_kl component).
"rl_weights": _optional_tensor_to_floats(micro_batch.get("rl_weights"), seq_len),
"ce_weights": _optional_tensor_to_floats(micro_batch.get("ce_weights"), seq_len),
"ref_kl_weights": _optional_tensor_to_floats(micro_batch.get("ref_kl_weights"), seq_len),
"env_names": list(micro_batch["env_names"]),
}
@@ -179,7 +182,14 @@ def _compute_export_tensors(
"is_masked_high": None,
"is_masked_low": None,
}
if micro_batch["training_mode"] == "sft":
# Ratio-based fields are meaningless when no token has sampling logprobs
# (e.g. pure CE batches distilling frozen-model tokens): no rl member
# (stream present but all-zero) and no ref_kl member.
rl_weights = micro_batch.get("rl_weights")
ref_kl_weights = micro_batch.get("ref_kl_weights")
no_rl = rl_weights is not None and not bool((rl_weights != 0).any())
no_ref_kl = ref_kl_weights is None or not bool((ref_kl_weights != 0).any())
if no_rl and no_ref_kl:
return fields
inference_logprobs = micro_batch["inference_logprobs"].to(trainer_logprobs.device)
+62 -22
View File
@@ -31,7 +31,7 @@ from prime_rl.trainer.rl.loss import (
compute_loss,
compute_importance_ratio_and_mismatch_kl,
selective_log_softmax,
setup_loss_fns,
setup_rl_loss_fn,
shift_tensor_left,
shift_tensor_right,
)
@@ -43,7 +43,7 @@ from prime_rl.trainer.model import (
is_tt_moe_model,
get_load_balance_stats,
)
from prime_rl.trainer.parallel_dims import get_parallel_dims
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
from prime_rl.trainer.perf import get_perf_counter
from prime_rl.trainer.utils import (
build_bin_cost,
@@ -121,6 +121,9 @@ def train(config: TrainerConfig):
config.output_dir, config.max_concurrent_runs, torch.device("cuda", world.local_rank), config.model.lora
)
# Resolve ep="auto" to a concrete integer before creating parallel dims
resolve_ep(config.model)
# Initialize parallel dimensions
parallel_dims = get_parallel_dims(config.model)
@@ -149,9 +152,9 @@ def train(config: TrainerConfig):
logger.info(f"Initializing tokenizer ({config.tokenizer})")
tokenizer = setup_tokenizer(config.tokenizer)
# Set up the loss function
# Set up the loss function for the RL loss type (ce / ref_kl are fixed)
logger.info(f"Setting up loss function ({config.loss})")
loss_fns = setup_loss_fns(config.loss)
rl_loss_fn = setup_rl_loss_fn(config.loss)
# Set up the optimizer
logger.info(f"Initializing optimizer ({config.optim})")
@@ -351,15 +354,29 @@ def train(config: TrainerConfig):
forward_backward_start_time = time.perf_counter()
seq_len = micro_batches[0]["input_ids"].shape[1]
# Normalize by the global (dp_cp) number of unmasked tokens in the batch, so every rank
# Normalize each loss component by its own global (dp_cp) token count, so every rank
# divides by the same denominator. With a per-rank denominator, ranks with fewer loss
# tokens implicitly upweight their per-token gradient contribution after FSDP averaging.
# FSDP's per-rank divide is undone after the microbatch loop via fsdp_gradient_divide_factor.
local_loss_scale = sum(micro_batch["loss_mask"].sum().item() for micro_batch in micro_batches)
global_loss_scale = torch.tensor(local_loss_scale, dtype=torch.int64, device="cuda")
# FSDP's per-rank divide is undone after the microbatch loop via
# fsdp_gradient_divide_factor. One batched collective keeps every rank issuing the same
# op regardless of which components its samples carry.
local_rl_scale = 0
local_ce_scale = 0
local_ref_kl_scale = 0
for micro_batch in micro_batches:
mask = micro_batch["loss_mask"]
rl_w = micro_batch["rl_weights"]
local_rl_scale += int((mask & (rl_w != 0)).sum()) if rl_w is not None else int(mask.sum())
if micro_batch["ce_weights"] is not None:
local_ce_scale += int((micro_batch["ce_weights"] != 0).sum())
if micro_batch["ref_kl_weights"] is not None:
local_ref_kl_scale += int((micro_batch["ref_kl_weights"] != 0).sum())
global_scales = torch.tensor(
[local_rl_scale, local_ce_scale, local_ref_kl_scale], dtype=torch.int64, device="cuda"
)
dp_cp_group = parallel_dims.get_mesh("dp_cp").get_group()
dist.all_reduce(global_loss_scale, op=dist.ReduceOp.SUM, group=dp_cp_group)
loss_scale = max(global_loss_scale.item(), 1)
dist.all_reduce(global_scales, op=dist.ReduceOp.SUM, group=dp_cp_group)
rl_scale, ce_scale, ref_kl_scale = (max(scale, 1) for scale in global_scales.tolist())
logger.debug(f"Starting forward and backward pass ({batch_size=})")
tensors = Tensors() # Used to accumulate tensor statistics across micro-batches and ranks for logging
@@ -374,8 +391,11 @@ def train(config: TrainerConfig):
advantages = micro_batch["advantages"].to("cuda")
loss_mask = micro_batch["loss_mask"].to("cuda")
inference_logprobs = micro_batch["inference_logprobs"].to("cuda")
teacher_logprobs = (
micro_batch["teacher_logprobs"].to("cuda") if micro_batch["teacher_logprobs"] is not None else None
ref_logprobs = micro_batch["ref_logprobs"].to("cuda") if micro_batch["ref_logprobs"] is not None else None
rl_weights = micro_batch["rl_weights"].to("cuda") if micro_batch["rl_weights"] is not None else None
ce_weights = micro_batch["ce_weights"].to("cuda") if micro_batch["ce_weights"] is not None else None
ref_kl_weights = (
micro_batch["ref_kl_weights"].to("cuda") if micro_batch["ref_kl_weights"] is not None else None
)
routed_experts = (
micro_batch["routed_experts"].to("cuda") if micro_batch["routed_experts"] is not None else None
@@ -477,14 +497,16 @@ def train(config: TrainerConfig):
loss, loss_tensors = compute_loss(
trainer_logprobs=out["logprobs"].squeeze().split(sequence_lengths),
inference_logprobs=inference_logprobs.squeeze().split(sequence_lengths),
teacher_logprobs=teacher_logprobs.squeeze().split(sequence_lengths)
if teacher_logprobs is not None
else None,
ref_logprobs=ref_logprobs.squeeze().split(sequence_lengths) if ref_logprobs is not None else None,
advantages=advantages.squeeze().split(sequence_lengths),
loss_mask=loss_mask.squeeze().split(sequence_lengths),
loss_fns=loss_fns,
loss_scale=loss_scale,
training_mode=micro_batch["training_mode"],
rl_weights=rl_weights.squeeze().split(sequence_lengths) if rl_weights is not None else None,
ce_weights=ce_weights.squeeze().split(sequence_lengths) if ce_weights is not None else None,
ref_kl_weights=ref_kl_weights.squeeze().split(sequence_lengths) if ref_kl_weights is not None else None,
rl_loss_fn=rl_loss_fn,
rl_scale=rl_scale,
ce_scale=ce_scale,
ref_kl_scale=ref_kl_scale,
)
# Backward pass
@@ -505,12 +527,30 @@ def train(config: TrainerConfig):
for env_name, indices in env_to_indices.items():
tensors[f"entropy/{env_name}"].append(entropy[indices])
if micro_batch["training_mode"] != "sft":
# Mismatch KL is only meaningful where sampling logprobs exist —
# keep rl/ref_kl member tokens (policy-sampled), exclude tokens
# whose action component is ce (frozen-model tokens).
if rl_weights is None and ref_kl_weights is None:
mismatch_mask = loss_mask
has_mismatch_tokens = True
else:
sampled_mask = (rl_weights != 0) if rl_weights is not None else loss_mask
if ref_kl_weights is not None:
sampled_mask = sampled_mask | (ref_kl_weights != 0)
mismatch_mask = loss_mask & sampled_mask
has_mismatch_tokens = bool(mismatch_mask.any())
if has_mismatch_tokens:
with torch.no_grad():
_, _, mismatch_kl = compute_importance_ratio_and_mismatch_kl(out["logprobs"], inference_logprobs)
mismatch_kl = mismatch_kl[loss_mask].detach().to("cpu")
mismatch_kl = mismatch_kl[mismatch_mask].detach().to("cpu")
tensors["mismatch_kl/all"].append(mismatch_kl)
for env_name, indices in env_to_indices.items():
mismatch_env_names = [
env_name for env_name, keep in zip(env_names, mismatch_mask.flatten().tolist()) if keep
]
mismatch_env_to_indices: dict[str, list[int]] = {}
for idx, env_name in enumerate(mismatch_env_names):
mismatch_env_to_indices.setdefault(env_name, []).append(idx)
for env_name, indices in mismatch_env_to_indices.items():
tensors[f"mismatch_kl/{env_name}"].append(mismatch_kl[indices])
token_exporter.export(
@@ -534,7 +574,7 @@ def train(config: TrainerConfig):
# Debug log with *local, micro step* stats
micro_step_message = f"Micro Step {micro_step}/{len(micro_batches)} | Loss {tensors['loss'][-1].mean().item():.4f} | Entropy {tensors['entropy/all'][-1].mean().item():.4f}"
if micro_batch["training_mode"] != "sft":
if has_mismatch_tokens:
micro_step_message += f" | Mismatch KL {tensors['mismatch_kl/all'][-1].mean().item():.4f}"
if "max_vio" in tensors:
micro_step_message += f" | Max Vio {tensors['max_vio'][-1].mean().item():.4f}"
+9 -11
View File
@@ -515,24 +515,22 @@ def setup_multi_run_manager(
trainer_lora = lora_config
def validate_lora_rank(orch_config: "OrchestratorConfig") -> tuple[bool, str]:
if orch_config.student.model.lora is None:
return False, "student.model.lora is required when trainer is configured with LoRA"
if orch_config.model.lora is None:
return False, "orchestrator.model.lora is required when trainer is configured with LoRA"
# Default to trainer's rank/alpha if not specified
if orch_config.student.model.lora.rank is None:
orch_config.student.model.lora.rank = trainer_lora.rank
if orch_config.student.model.lora.alpha is None:
orch_config.student.model.lora.alpha = trainer_lora.alpha
if orch_config.student.model.lora.rank > trainer_lora.rank:
if orch_config.model.lora.rank is None:
orch_config.model.lora.rank = trainer_lora.rank
if orch_config.model.lora.alpha is None:
orch_config.model.lora.alpha = trainer_lora.alpha
if orch_config.model.lora.rank > trainer_lora.rank:
return (
False,
f"student.model.lora.rank ({orch_config.student.model.lora.rank}) exceeds trainer max rank ({trainer_lora.rank})",
f"orchestrator.model.lora.rank ({orch_config.model.lora.rank}) exceeds trainer max rank ({trainer_lora.rank})",
)
return True, ""
def on_run_discovered(idx: int, run_id: str, orch_config: "OrchestratorConfig") -> None:
_MULTI_RUN_MANAGER.scaling_factors[idx] = (
orch_config.student.model.lora.alpha / orch_config.student.model.lora.rank
)
_MULTI_RUN_MANAGER.scaling_factors[idx] = orch_config.model.lora.alpha / orch_config.model.lora.rank
_MULTI_RUN_MANAGER.register_config_validation_hook(validate_lora_rank)
_MULTI_RUN_MANAGER.register_discovered_hook(on_run_discovered)
+4 -1
View File
@@ -32,7 +32,7 @@ from prime_rl.trainer.model import (
setup_tokenizer,
setup_model,
)
from prime_rl.trainer.parallel_dims import get_parallel_dims
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
from prime_rl.trainer.perf import get_perf_counter
from prime_rl.trainer.sft.data import load_sft_dataset, setup_dataloader, setup_dataset
from prime_rl.trainer.utils import (
@@ -94,6 +94,9 @@ def train(config: SFTConfig):
if config.model.lora is not None:
setup_multi_run_manager(config.output_dir, 1, torch.device("cuda", world.local_rank), config.model.lora)
# Resolve ep="auto" to a concrete integer before creating parallel dims
resolve_ep(config.model)
# Initialize parallel dimensions
parallel_dims = get_parallel_dims(config.model, config.data.seq_len)
+3
View File
@@ -606,6 +606,9 @@ def filter_rl_trainer_tensor_stats_for_wandb(metrics: dict[str, float | int]) ->
"mismatch_kl/",
"masked_mismatch_kl/",
"unmasked_mismatch_kl/",
"ref_kl/is_masked/",
"ref_kl/masked_mismatch_kl/",
"ref_kl/unmasked_mismatch_kl/",
)
out: dict[str, float | int] = {}
for k, v in metrics.items():
+26 -15
View File
@@ -1,9 +1,5 @@
from typing import Literal
import msgspec
TrainingMode = Literal["rl", "opd", "sft"]
# Encoded tensor: {dtype: "float32", shape: [...], data: <bytes>}.
# Mirrors verifiers.utils.serve_utils.msgpack_encoder so the same wire
@@ -36,9 +32,7 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
logprobs: list[float]
temperatures: list[float]
env_name: str
teacher_logprobs: list[float] | None = None
advantage: float | None = None
reward: float | None = None
ref_logprobs: list[float] | None = None # reference-model logprobs (ref_kl component)
# Generic multimodal kwargs: flat dict keyed by the kwarg names the
# model's forward expects (e.g. {"pixel_values": ..., "image_grid_thw":
@@ -55,9 +49,24 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
# mm_token_type_ids: token type ids per token [batch seq], int64 (0=text, 1=image, 2=video)
mm_token_type_ids: list[int] | None = None
# Loss dispatch is batch-driven: rl/opd use default_loss_fn (with mode-specific
# taus), sft uses sft_loss_fn. Stamped by the orchestrator from training_mode.
training_mode: TrainingMode = "rl"
# Per-token component weight streams (full prompt+completion length),
# stamped by the orchestrator from the env's algorithm. The training loss
# is a sum of three components, each normalized by its own global token
# count: rl (importance-weighted PG + KL), ce (masked NLL), and ref_kl
# (reverse KL to a reference model as the PG signal). A weight scales that
# component's per-token loss; 0.0 leaves the token out of the component
# (mask and denominator). ``None`` means absent: no ce/ref_kl component,
# and an rl weight of 1.0 on every trainable token — so the plain GRPO
# wire stays as small as before.
rl_weights: list[float] | None = None
ce_weights: list[float] | None = None
ref_kl_weights: list[float] | None = None
# Per-token advantages (full prompt+completion length), the fourth stream:
# the orchestrator broadcasts the rollout's scalar over the completion for
# scalar algorithms. ``None`` means no rl credit assigned — legal only for
# samples without live rl member tokens (the trainer raises otherwise).
advantages: list[float] | None = None
class TrainingBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
@@ -80,7 +89,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
sequence_lengths: list[int]
temperatures: list[float] # Per-token temperatures used during generation
env_names: list[str]
teacher_logprobs: list[float] | None = None
ref_logprobs: list[float] | None = None
lora_num_tokens: list[int] | None = None
routed_experts: RoutedExperts | None = None
@@ -89,10 +98,12 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
# mm_token_type_ids: token type ids per token [batch seq], int64 (0=text, 1=image, 2=video)
mm_token_type_ids: list[int] | None = None
# Loss dispatch is batch-driven (rl/opd → default loss with mode-specific taus,
# sft → sft loss). All samples packed into a micro batch share the same mode.
training_mode: TrainingMode = "rl"
rewards: list[float] | None = None
# Per-token component weight streams (see TrainingSample). ``None`` means
# absent: no ce/ref_kl component, rl weight 1.0 everywhere — packing
# materializes a stream as soon as one packed sample carries it.
rl_weights: list[float] | None = None
ce_weights: list[float] | None = None
ref_kl_weights: list[float] | None = None
# Packer-derived metadata used for run-local token exports.
run_id: str | None = None
-8
View File
@@ -92,17 +92,11 @@ def render_messages(
tools: list[dict[str, Any]] | None = None,
chat_template_kwargs: dict[str, Any] | None = None,
add_generation_prompt: bool = False,
processor=None,
) -> list[int]:
kwargs = dict(chat_template_kwargs or {})
kwargs["add_generation_prompt"] = add_generation_prompt
if tools is not None:
kwargs["tools"] = tools
if processor is not None:
kwargs["tokenize"] = True
kwargs["return_dict"] = True
result = processor.apply_chat_template(messages, **kwargs)
return list(result["input_ids"][0])
kwargs["return_dict"] = False
return list(tokenizer.apply_chat_template(messages, **kwargs))
@@ -115,7 +109,6 @@ def build_incremental_token_mask(
tools: list[dict[str, Any]] | None = None,
chat_template_kwargs: dict[str, Any] | None = None,
collapse_consecutive_tool_messages: bool = False,
processor=None,
) -> tuple[list[int], list[bool]]:
token_mask: list[bool] = []
prev_ids: list[int] = []
@@ -133,7 +126,6 @@ def build_incremental_token_mask(
tools=tools,
chat_template_kwargs=chat_template_kwargs,
add_generation_prompt=should_add_generation_prompt(messages, idx),
processor=processor,
)
if prev_ids != cur_ids[:prev_len]:
+78 -6
View File
@@ -10,7 +10,7 @@ from typing import Protocol, runtime_checkable
import httpx
import verifiers.v1 as vf
from httpx import AsyncClient
from openai import NotFoundError
from openai import AsyncOpenAI, NotFoundError
from renderers import RendererConfig
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
from verifiers.v1.clients.config import EvalClientConfig, TrainClientConfig
@@ -73,8 +73,8 @@ class InferencePool(Protocol):
"""Update weights on all inference servers."""
...
def get_metrics(self) -> dict[str, float]:
"""Get pool metrics."""
async def score(self, token_ids: list[int]) -> list[float]:
"""Prefill-score ``token_ids`` under the pool's model — one logprob per token."""
...
async def stop(self) -> None:
@@ -82,6 +82,39 @@ class InferencePool(Protocol):
...
class PrefillScorer:
"""Prefill-scores token ids against a pool's *current* endpoints. Resolves one
client per endpoint, cached by endpoint identity — so it fills once for a
static pool and tolerates churn for an elastic one (a departed endpoint is
simply never selected again; its client is closed at stop). Round-robins over
the live endpoints."""
def __init__(self) -> None:
self._clients: dict = {} # client_identity -> AsyncOpenAI, one per endpoint
self._rr = 0
async def score(self, configs: list[vf.ClientConfig], model: str, token_ids: list[int]) -> list[float]:
if not configs:
raise RuntimeError("no inference endpoints available to prefill-score")
cfg = configs[self._rr % len(configs)]
self._rr += 1
key = client_identity(cfg)
openai = self._clients.get(key)
if openai is None:
# Build the OpenAI client straight from the config fields — works for any
# ClientConfig type; resolve_client would hand back an EvalClient (no `.openai`)
# for these chat-completions teacher configs.
openai = self._clients[key] = AsyncOpenAI(
base_url=cfg.base_url,
api_key=os.environ.get(cfg.api_key_var) or "EMPTY",
default_headers=cfg.headers or None,
)
return await prefill_logprobs(openai, model, token_ids)
async def aclose(self) -> None:
await asyncio.gather(*(c.close() for c in self._clients.values()))
class StaticInferencePool:
"""Static inference pool with fixed client list."""
@@ -107,6 +140,7 @@ class StaticInferencePool:
self._skip_model_check = client_config.skip_model_check
self._wait_for_ready_timeout = client_config.wait_for_ready_timeout
self._eval_cycle = cycle(self._eval_clients)
self._scorer = PrefillScorer()
self.model_name = model_name
@property
@@ -141,11 +175,13 @@ class StaticInferencePool:
async def update_weights(self, weight_dir: Path | None, lora_name: str | None = None, step: int = 0) -> None:
await update_weights(self._admin_clients, weight_dir, lora_name=lora_name, step=step)
def get_metrics(self) -> dict[str, float]:
return {}
async def score(self, token_ids: list[int]) -> list[float]:
"""Prefill-score ``token_ids`` under this pool's model (one logprob per
token, 0.0 for the leading token). Delegates to the shared scorer."""
return await self._scorer.score(self.train_clients, self.model_name, token_ids)
async def stop(self) -> None:
pass
await self._scorer.aclose()
async def setup_inference_pool(
@@ -528,3 +564,39 @@ async def init_nccl_broadcast(
for client_num, admin_client in enumerate(admin_clients)
]
)
async def prefill_logprobs(openai: AsyncOpenAI, model: str, token_ids: list[int]) -> list[float]:
"""Prefill-score ``token_ids`` under ``model`` via ``/inference/v1/generate``
+ ``prompt_logprobs`` (the prime-rl server-side extension in
``inference/vllm/serving_tokens.py``). Returns one logprob per token (0.0 for
the leading token, which has no preceding context)."""
from vllm.entrypoints.serve.disagg.protocol import GenerateResponse
# `/inference/v1/generate` is mounted at server root, not under `/v1`: pass an
# absolute URL so the SDK skips the base-url merge. vLLM's `GenerateResponse`
# isn't an `openai.BaseModel`, so the SDK parse layer rejects it as `cast_to`;
# `cast_to=httpx.Response` lets the SDK still build the request (auth, retries,
# timeouts) and hand back the raw response for us to validate.
base = str(openai.base_url).rstrip("/").removesuffix("/v1")
http_response = await openai.post(
f"{base}/inference/v1/generate",
cast_to=httpx.Response,
body={
"model": model,
"token_ids": token_ids,
"sampling_params": {"max_tokens": 1, "temperature": 1.0, "top_p": 1.0, "prompt_logprobs": 1},
},
)
response = GenerateResponse.model_validate_json(http_response.content)
# `prompt_logprobs[i]` is a `{token_id: Logprob}` dict, or `None` for the
# leading token (no preceding context). Flatten to `list[float]`.
flat: list[float] = []
for entry in response.prompt_logprobs or []:
if not entry:
flat.append(0.0)
continue
first = next(iter(entry.values()))
lp = first.logprob if hasattr(first, "logprob") else first.get("logprob")
flat.append(float(lp) if lp is not None else 0.0)
return flat
+13 -8
View File
@@ -22,7 +22,14 @@ from httpx import AsyncClient
from renderers import RendererConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.client import ClientIdentity, client_identity, load_lora_adapter, setup_admin_clients, setup_clients
from prime_rl.utils.client import (
ClientIdentity,
PrefillScorer,
client_identity,
load_lora_adapter,
setup_admin_clients,
setup_clients,
)
from prime_rl.utils.logger import get_logger
# --- Shared discovery functions ---
@@ -138,6 +145,7 @@ class ElasticInferencePool:
self._sync_task: asyncio.Task | None = None
self._started = False
self._scorer = PrefillScorer()
@classmethod
async def from_config(
@@ -234,6 +242,9 @@ class ElasticInferencePool:
await asyncio.sleep(self.sync_interval)
return min(self.train_clients, key=lambda c: load[client_identity(c)])
async def score(self, token_ids: list[int]) -> list[float]:
return await self._scorer.score(self.train_clients, self.model_name, token_ids)
@property
def admin_clients(self) -> list[AsyncClient]:
return list(self._admin_clients.values())
@@ -467,6 +478,7 @@ class ElasticInferencePool:
for ip in list(self._servers.keys()):
await self._remove_server(ip)
await self._scorer.aclose()
self._train_clients = []
self._eval_clients = []
self._client_urls = []
@@ -499,10 +511,3 @@ class ElasticInferencePool:
if lora_name is None:
raise ValueError("Elastic inference pool requires LoRA training (lora_name must be set)")
await self.sync_weights(weight_dir, lora_name, step)
def get_metrics(self) -> dict[str, float]:
return {
"elastic/num_servers": self.num_servers,
"elastic/num_ready_servers": self.num_ready_servers,
"elastic/desired_step": self._desired.step,
}
-62
View File
@@ -1,62 +0,0 @@
"""Message utilities — normalize, deserialize tool calls, strip content."""
import json
from typing import Any
def normalize_messages(messages: Any, default_role: str) -> list[dict[str, Any]]:
if messages is None:
return []
if isinstance(messages, str):
return [{"role": default_role, "content": messages}]
if isinstance(messages, dict):
return [dict(messages)]
if isinstance(messages, list):
normalized: list[dict[str, Any]] = []
for message in messages:
if isinstance(message, str):
normalized.append({"role": default_role, "content": message})
elif isinstance(message, dict):
normalized.append(dict(message))
else:
raise TypeError(f"Unsupported message type: {type(message)}")
return normalized
raise TypeError(f"Unsupported messages container type: {type(messages)}")
def deserialize_tool_calls(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
def _deserialize_tool_call(tool_call: dict[str, Any]) -> dict[str, Any]:
function = tool_call.get("function", {})
arguments = function.get("arguments")
if isinstance(arguments, str):
arguments = json.loads(arguments)
return {
**tool_call,
"function": {**function, "arguments": arguments},
}
deserialized_messages: list[dict[str, Any]] = []
for message in messages:
if "tool_calls" not in message:
deserialized_messages.append(dict(message))
continue
tool_calls = message.get("tool_calls") or []
deserialized_messages.append(
{
**message,
"tool_calls": [_deserialize_tool_call(tc) for tc in tool_calls],
}
)
return deserialized_messages
def strip_message_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
def _strip(message: dict[str, Any]) -> dict[str, Any]:
content = message.get("content")
if isinstance(content, str):
return {**message, "content": content.strip()}
return message
return [_strip(message) for message in messages]
+3 -3
View File
@@ -193,7 +193,7 @@ class PrimeMonitor(Monitor):
frontend_url = prime_config.frontend_url
payload: dict[str, Any] = {
"base_model": run_config.student.model.name if run_config else "unknown",
"base_model": run_config.model.name if run_config else "unknown",
"max_steps": (run_config.max_steps if run_config else None) or 0,
}
if run_config:
@@ -348,7 +348,7 @@ class PrimeMonitor(Monitor):
{
"messages": [m.model_dump(mode="json") for m in branch.messages],
"reward": rollout.reward,
"advantage": rollout.advantage,
"advantage": rollout.scalar_advantage(),
"num_input_tokens": branch.prompt_len,
"num_output_tokens": branch.completion_len,
}
@@ -370,7 +370,7 @@ class PrimeMonitor(Monitor):
"task": rollout.task.model_dump_json(),
"info": json.dumps(rollout.info),
"reward": rollout.reward,
"advantage": rollout.advantage,
"advantage": rollout.scalar_advantage(),
"metrics": json.dumps(rollout.metrics),
"timing": rollout.timing.model_dump_json(),
"num_input_tokens": branches[-1].prompt_len,

Some files were not shown because too many files have changed in this diff Show More