Compare commits

...
Author SHA1 Message Date
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
halleriteandGitHub d3765e289d chore(deps): bump verifiers to 0.1.15.dev388 (#2870)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-24 22:52:46 +02:00
minh hoangandGitHub 9bf203c678 Fix Docker editable package version resolution (#2866)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-24 11:52:10 -07:00
46bcf628f6 chore: remove outdated math configs (#2865)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: remove outdated config dirs

Prune four stale, unused config directories. None are referenced by
docs, skills, CI, or scripts, and each is a one-off experiment or
feature demo whose last substantive edit predates the recent config
sweeps:

- wordle: legacy v0-bridge demo, last real edit 2025-08-30
- deepscaler: old multi-stage experiment (README points at a
  configs/deepscaler/eval.toml that no longer exists)
- glm5_disagg_inference: one-off disaggregated-inference demo
- elastic: alphabet-sort elastic/DNS-discovery demo

All four still parse against the current schema; removal is about
disuse, not breakage.

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

* chore: remove outdated acereason_math configs

Prune the stale acereason_math experiment configs (stage1/stage2, last
real edit 2025-12-23). They reference the aime24-v1 eval taskset that is
no longer available, so they fail to load against the current schema.

The live nightly run (configs/ci/nightly/acereason_math.toml) is
unaffected; drop its now-dangling comment reference to the deleted dir.

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

* chore: keep wordle, elastic and glm5_disagg_inference configs

Narrow this PR to only the deepscaler and acereason_math configs.

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

* chore: remove acereason_math from nightly suite

Drop the nightly acereason-math config and its test. The nightly
workflow auto-discovers tests/nightly/test_*.py, so removing the test
file drops it from the matrix.

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-23 20:45:19 -07:00
a3151e3711 chore: repoint v1 tasksets to research-environments (#2864)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore(deps): repoint scaleswe/swebench-verified/terminal-bench-2 v1 tasksets to research-environments

The three container-backed v1 SWE tasksets moved out of verifiers into
research-environments. Repoint their [tool.uv.sources] paths and bump both
submodules to match.

- deps/verifiers: drop the three envs
- deps/research-environments: add the three envs + advance to current main
- uv lock

Taskset ids are unchanged, so run configs that reference them by id need no changes.

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

* chore(deps): bump verifiers + research-environments submodules to current heads

Picks up vf#1851 (swebench-verified ensures uv on PATH before scoring), now ported
into the research-environments copy of swebench_verified_v1.

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

* chore(deps): repoint 6 more v1 tasksets to research-environments

Following their move out of verifiers, repoint math-env-v1, aime24-v1, r2e-gym-v1,
swelego-v1, wikispeedia-v1, and general-agent-v1 from deps/verifiers to
deps/research-environments, and bump both submodules to the updated heads. The
moved envs now pin verifiers>=0.1.15.dev381 (satisfied by the editable verifiers).

- uv lock

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

* chore(deps): bump research-environments (drop moved eval configs + scaleswe fix)

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

* chore(deps): swap v0 aime for v1 tasksets + reference tau2-bench-v1

Following the aime/wikispeedia v0->v1 replacement in research-environments:
- drop aime2024, aime2025 (v0); reference aime24-v1, aime25-v1, aime26-v1
- add tau2-bench-v1
- bump deps/research-environments + uv lock

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

* chore(deps): repin verifiers + research-environments to merged main

verifiers#1853 (remove the moved v1 tasksets) and research-environments#527 (add them)
have merged; repin both submodules to the merged main commits. uv.lock unchanged
(already consistent — `uv lock --check` passes).

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

* fix(configs): point aime eval envs at the v1 tasksets

The v0 aime2024/aime2025 packages were dropped from the `envs` extra + sources, so
`uv sync --extra envs` no longer registers them and eval sections using the legacy
ids fail at runtime. Switch those eval entries to the v1 tasksets (aime24-v1 /
aime25-v1; default `subprocess` harness), keeping the display names for metric
continuity.

- configs/acereason_math/{stage1,stage2}.toml
- configs/debug/hendrycks_sanity/rl.toml
- configs/math_group/rl.toml

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-23 20:33:26 -07:00
45 changed files with 1370 additions and 1438 deletions
+85 -3
View File
@@ -77,20 +77,85 @@ COPY deps/ /app/deps/
COPY configs /app/configs
COPY examples /app/examples
COPY benchmarks/scripts /app/benchmarks/scripts
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
# Use submodule git metadata from the build context when present. Docker copies
# only the submodule .git pointer files into /app/deps, so we temporarily link
# /app/.git/modules to the read-only context before resolving versions.
# Opt-in extras for disaggregated P/D inference (deep-ep, deep-gemm, quack).
# Default off — they're heavy source builds only the disagg-MoE path needs.
# Enable via `--build-arg INCLUDE_DISAGG_EXTRAS=1`.
ARG INCLUDE_DISAGG_EXTRAS=0
ARG VERIFIERS_PRETEND_VERSION
ARG RENDERERS_PRETEND_VERSION
RUN --mount=type=cache,target=/app/.cache/uv \
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --extra modelexpress --group mamba-ssm --locked --no-dev
--mount=type=bind,source=.,target=/build-context,readonly \
if [ -d /build-context/.git/modules ]; then mkdir -p /app/.git && ln -s /build-context/.git/modules /app/.git/modules; fi \
&& \
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
&& \
if [ -L /app/.git/modules ]; then rm /app/.git/modules && rmdir /app/.git 2>/dev/null || true; fi \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" /app/deps/verifiers/pyproject.toml \
&& \
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
&& \
EXTRA_DISAGG_FLAG=""; if [ "$INCLUDE_DISAGG_EXTRAS" = "1" ]; then EXTRA_DISAGG_FLAG="--extra disagg"; fi \
&& \
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --extra modelexpress $EXTRA_DISAGG_FLAG --group mamba-ssm --locked --no-dev
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
# (#2883); rebuilding against our UCX is the documented fix. Only needed for
# the disaggregated P/D path — default off so training-only / single-node
# inference builds are unaffected. Enable via `--build-arg INCLUDE_NIXL_FROM_SOURCE=1`.
ARG INCLUDE_NIXL_FROM_SOURCE=0
ARG NIXL_VERSION=0.10.1
RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
VIRTUAL_ENV=/app/.venv uv pip install pip \
&& git clone --depth 1 --branch ${NIXL_VERSION} https://github.com/ai-dynamo/nixl.git /tmp/nixl \
&& cd /tmp/nixl \
&& PKG_CONFIG_PATH=/opt/ucx/lib/pkgconfig \
LD_LIBRARY_PATH=/opt/ucx/lib:/opt/ucx/lib/ucx \
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/app/deps \
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu12-*.whl \
&& rm -rf /tmp/nixl /app/deps/nixl_cu12-*.whl; \
fi
# arm64: build flash-attn from source, fix namespace conflicts, apply workarounds
ARG TARGETARCH
COPY scripts/docker-arm64-post-install.sh /app/scripts/docker-arm64-post-install.sh
RUN if [ "$TARGETARCH" = "arm64" ]; then /app/scripts/docker-arm64-post-install.sh; fi
FROM python:3.12-slim
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
# COPY ships only the trimmed result (~1.5 GB) instead of the full ~6.6 GB. Drops the math
# runtime libs (cublas/cusparse/cufft/cusolver/curand/npp/nvjpeg) and big static .a
# archives since nvcc JIT (TileLang/FlashInfer build their own kernels) and torch
# (uses pinned nvidia-* wheels) needs them. Keeps nvcc/nvvm/ptxas + headers +
# libcudart/libnvrtc/libcudadevrt for JIT compile+link.
FROM builder AS cuda-trim
RUN find /usr/local/cuda-12.8/targets/*/lib \
\( -name 'libcublas*' -o -name 'libcusparse*' -o -name 'libcufft*' \
-o -name 'libcusolver*' -o -name 'libcurand*' -o -name 'libnpp*' \
-o -name 'libnvjpeg*' -o -name 'libnvblas*' \) -delete \
&& find /usr/local/cuda-12.8 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
# CUDA 13 runtime libs source
FROM nvidia/cuda:13.0.1-runtime-ubuntu24.04 AS cuda13
RUN mkdir -p /cu13 && cp -d $(find /usr/local \
-name 'libcudart.so.13*' -o -name 'libnvrtc.so.13*' -o -name 'libnvrtc-builtins.so.13*') /cu13/
# Runtime image
FROM nvidia/cuda:12.8.1-base-ubuntu24.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y \
--no-install-recommends \
--force-yes \
python3.12 \
python3.12-venv \
python3.12-dev \
build-essential \
wget \
clang \
@@ -111,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
-53
View File
@@ -1,53 +0,0 @@
max_steps = 500
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[ckpt]
interval = 100
[wandb]
project = "acereason-math"
name = "stage1"
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 8192
[[orchestrator.train.env]]
id = "math-env"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
id = "math500"
group_size = 1
[[orchestrator.eval.env]]
id = "aime2024"
group_size = 32
[[orchestrator.eval.env]]
id = "aime2025"
group_size = 32
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
-54
View File
@@ -1,54 +0,0 @@
max_steps = 1000
seq_len = 16384
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[ckpt]
interval = 100
resume_step = 500
[wandb]
project = "acereason-math"
name = "stage2"
[orchestrator]
batch_size = 2048
group_size = 16
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 16384
[[orchestrator.train.env]]
id = "math-env"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
id = "math500"
group_size = 1
[[orchestrator.eval.env]]
id = "aime2024"
group_size = 32
[[orchestrator.eval.env]]
id = "aime2025"
group_size = 32
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
-36
View File
@@ -1,36 +0,0 @@
# Run on 8xH200
# Similar to configs/acereason_math/stage1.toml, but
# - 300 instead of 500 steps
# - No checkpointing
# - No evals
max_steps = 300
seq_len = 8192
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 8192
[[orchestrator.train.env]]
id = "math-env"
name = "acereason-math"
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
[trainer]
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
@@ -21,8 +21,9 @@ group_size = 16
max_completion_tokens = 64
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
name = "color-codeword"
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
harness = { id = "default", runtime = { type = "subprocess" } }
[trainer]
+1 -1
View File
@@ -22,8 +22,8 @@ name = "hendrycks-math"
interval = 50
[[orchestrator.eval.env]]
id = "aime2024"
name = "aime2024"
taskset = { id = "aime24-v1" }
group_size = 16
[trainer.model.ac]
+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.
-167
View File
@@ -1,167 +0,0 @@
# DeepScaler
This is a reproduction of the [DeepScaleR](https://pretty-radio-b75.notion.site/DeepScaleR-Surpassing-O1-Preview-with-a-1-5B-Model-by-Scaling-RL-19681902c1468005bed8ca303013a4e2) experiments. They use RL to train from `Deepseek-R1-Distill-Qwen-1.5B` to 43.1% on AIME2024, surpassing OpenAI’s o1-preview with just 1.5B parameters.
## Setup
Install the environment using the `prime` CLI.
```bash
prime env install primeintellect/deepscaler
```
Verify that the environment is installed correctly.
```bash
uv run python -c "import deepscaler"
```
## Training
A key insight from the paper is that they train in **stages of increasing context length**. In stages 1, 2 and 3, they train with context lengths of 8192, 16384 and 24576 tokens, respectively. We match their training setup here.
### Stage 1
```bash
bash scripts/tmux.sh -s stage1 -o outputs/stage1
```
```bash
# Run this in the `Trainer` pane
uv run rl @ configs/deepscaler/stage1.toml \
--output-dir outputs/stage1
```
### Stage 2
```bash
bash scripts/tmux.sh -s stage2 -o outputs/stage2
```
```bash
mkdir -p outputs/stage2/checkpoints
ln -s outputs/stage1/checkpoints/step_500 outputs/stage2/checkpoints/step_500
mkdir -p outputs/stage2/weights
ln -s outputs/stage1/weights/step_500 outputs/stage2/weights/step_500
```
```bash
# Run this in the `Trainer` pane
uv run rl @ configs/deepscaler/stage2.toml \
--output-dir outputs/stage2
```
### Stage 3
```bash
bash scripts/tmux.sh -s stage3 -o outputs/stage3
```
```bash
mkdir -p outputs/stage3/checkpoints
ln -s outputs/stage2/checkpoints/step_1000 outputs/stage3/checkpoints/step_1000
mkdir -p outputs/stage3/weights
ln -s outputs/stage2/weights/step_1000 outputs/stage3/weights/step_1000
```
```bash
# Run this in the `Trainer` pane
uv run rl @ configs/deepscaler/stage3.toml \
--output-dir outputs/stage3
```
## Evals
They evaluate on a series of math benchmarks, including Math500, AIME24, AMC23, Minerva Math and Olympiad Math. We will focus on `math500` and `aime2024` for the reproduction, as these are already implemented as evaluation environments on the Environment Hub and also the most prominent benchmarks. We uploaded the weight checkpoints to HF as `DeepSeek-R1-Distill-Qwen-1.5B-DeepScaleR-XXX` and evaluate the base model and each checkpoint.
![Evals](eval.png)
| Model | AIME 2024 | MATH 500 |
|-------|-----------|----------|
| DeepSeek-R1-Distill-Qwen-1.5B | 27.3% (16389±10200) | 81.4% (5450±7327) |
| DeepScaleR-100 | 30.8% (14510±9591) | 83.4% (4694±6311) |
| DeepScaleR-200 | 28.3% (11929±8630) | 83.2% (3610±4774) |
| DeepScaleR-300 | 30.6% (9898±7050) | 84.2% (3270±4027) |
| DeepScaleR-400 | 30.6% (9726±7077) | 83.6% (3283±4024) |
| DeepScaleR-500 | 33.1% (9686±6563) | 84.0% (3081±3438) |
| DeepScaleR-600 | 32.7% (9726±6222) | 86.6% (3205±3167) |
| DeepScaleR-700 | 32.5% (10162±5887) | 87.8% (3569±3953) |
| DeepScaleR-800 | 33.8% (10666±6032) | 85.4% (3835±3727) |
| DeepScaleR-900 | 28.3% (13375±6546) | 80.8% (5480±5887) |
| O1-Preview | 40.0% (N/A) | 81.4% (N/A) |
Start the inference server
```bash
bash scripts/tmux.sh
```
```bash
# Run this in the `Inference` pane
uv run inference --model.name ... --max-model-len 32768
```
*Note: The model checkpoints are uploaded to `mikasenghaas/DeepSeek-R1-Distill-Qwen-1.5B-DeepScaleR-XXX`.*
```bash
uv run eval @ configs/deepscaler/eval.toml --model.name ...
```
<details>
<summary>Raw results</summary>
<pre><code>
Base Model
Evaluated math500 in 1547.25s (Avg@1=0.8140, Pass@1: 0.8140, Completion Length: 5450.29 (±7327.93, ∈[266.00, 32734.00]), Truncated: 3.8%)
Evaluated aime2024 in 1546.06s (Avg@16=0.2729, Pass@8: 0.6130, Completion Length: 16389.57 (±10200.73, ∈[1643.00, 32699.00]), Truncated: 15.2%)
Step 100 (Stage 1)
Evaluated math500 in 1280.38s (Avg@1=0.8340, Pass@1: 0.8340, Completion Length: 4694.13 (±6311.37, ∈[225.00, 32729.00]), Truncated: 2.2%)
Evaluated aime2024 in 1279.09s (Avg@16=0.3083, Pass@8: 0.6363, Completion Length: 14510.24 (±9591.44, ∈[1606.00, 32696.00]), Truncated: 10.4%)
Step 200 (Stage 1)
Evaluated math500 in 942.63s (Avg@1=0.8320, Pass@1: 0.8320, Completion Length: 3610.20 (±4774.83, ∈[404.00, 32649.00]), Truncated: 0.8%)
Evaluated aime2024 in 942.34s (Avg@16=0.2833, Pass@8: 0.6043, Completion Length: 11929.71 (±8630.59, ∈[1770.00, 32701.00]), Truncated: 6.7%)
Step 300 (Stage 1)
Evaluated math500 in 737.77s (Avg@1=0.8420, Pass@1: 0.8420, Completion Length: 3270.25 (±4027.97, ∈[415.00, 32732.00]), Truncated: 0.4%)
Evaluated aime2024 in 736.54s (Avg@16=0.3063, Pass@8: 0.6350, Completion Length: 9898.05 (±7050.03, ∈[1606.00, 32696.00]), Truncated: 3.5%)
Step 400 (Stage 1)
Evaluated math500 in 727.78s (Avg@1=0.8360, Pass@1: 0.8360, Completion Length: 3283.45 (±4024.46, ∈[282.00, 32721.00]), Truncated: 0.4%)
Evaluated aime2024 in 726.83s (Avg@16=0.3063, Pass@8: 0.6567, Completion Length: 9726.12 (±7077.99, ∈[1266.00, 32686.00]), Truncated: 3.3%)
Step 500 (Stage 1)
Evaluated math500 in 660.66s (Avg@1=0.8540, Pass@1: 0.8540, Completion Length: 2961.01 (±3426.75, ∈[543.00, 32695.00]), Truncated: 0.6%)
Evaluated aime2024 in 658.95s (Avg@16=0.3000, Pass@8: 0.6460, Completion Length: 9121.69 (±6423.23, ∈[1323.00, 32687.00]), Truncated: 3.1%)
Step 500 (Stage 2)
Evaluated math500 in 370.32s (Avg@1=0.8400, Pass@1: 0.8400, Completion Length: 3081.88 (±3438.49, ∈[614.00, 32709.00]), Truncated: 0.4%)
Evaluated aime2024 in 368.68s (Avg@16=0.3312, Pass@8: 0.6287, Completion Length: 9686.62 (±6563.93, ∈[1140.00, 32686.00]), Truncated: 2.5%)
Step 600 (Stage 2)
Evaluated math500 in 334.98s (Avg@1=0.8660, Pass@1: 0.8660, Completion Length: 3205.39 (±3167.25, ∈[554.00, 22164.00]), Truncated: 0.0%)
Evaluated aime2024 in 354.83s (Avg@16=0.3271, Pass@8: 0.6353, Completion Length: 9726.84 (±6222.77, ∈[1162.00, 32683.00]), Truncated: 1.9%)
Step 700 (Stage 2)
Evaluated math500 in 377.43s (Avg@1=0.8780, Pass@1: 0.8780, Completion Length: 3569.39 (±3953.57, ∈[618.00, 32611.00]), Truncated: 0.4%)
Evaluated aime2024 in 375.57s (Avg@16=0.3250, Pass@8: 0.6550, Completion Length: 10162.39 (±5887.47, ∈[1428.00, 32672.00]), Truncated: 1.5%)
Step 800 (Stage 2)
Evaluated math500 in 400.01s (Avg@1=0.8540, Pass@1: 0.8540, Completion Length: 3835.00 (±3727.86, ∈[563.00, 23701.00]), Truncated: 0.0%)
Evaluated aime2024 in 398.19s (Avg@16=0.3375, Pass@8: 0.6860, Completion Length: 10666.42 (±6032.30, ∈[1898.00, 32686.00]), Truncated: 1.0%)
Step 850 (Stage 2)
Evaluated math500 in 445.40s (Avg@1=0.8640, Pass@1: 0.8640, Completion Length: 4216.45 (±4022.84, ∈[611.00, 23277.00]), Truncated: 0.0%)
Evaluated aime2024 in 446.29s (Avg@16=0.3250, Pass@8: 0.6350, Completion Length: 11313.77 (±5997.51, ∈[1695.00, 32686.00]), Truncated: 1.9%)
Step 900 (Stage 2)
Evaluated math500 in 564.56s (Avg@1=0.8080, Pass@1: 0.8080, Completion Length: 5480.47 (±5887.06, ∈[662.00, 32729.00]), Truncated: 1.8%)
SUCCESS Evaluated aime2024 in 562.67s (Avg@16=0.2833, Pass@8: 0.6003, Completion Length: 13375.38 (±6546.80, ∈[1706.00, 32687.00]), Truncated: 4.0%)
Step 950 (Stage 3)
Evaluated math500 in 755.59s (Avg@1=0.7200, Pass@1: 0.7200, Completion Length: 8146.41 (±7986.20, ∈[748.00, 32736.00]), Truncated: 4.6%)
Evaluated aime2024 in 751.49s (Avg@16=0.1833, Pass@8: 0.4207, Completion Length: 16031.10 (±6904.70, ∈[2366.00, 32699.00]), Truncated: 4.8%)
</code>
</pre>
</details>
<br/>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

-39
View File
@@ -1,39 +0,0 @@
max_steps = 500
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[wandb]
project = "deepscaler"
name = "stage1"
[ckpt]
interval = 100
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 8192
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
-40
View File
@@ -1,40 +0,0 @@
max_steps = 1000
seq_len = 16384
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[wandb]
project = "deepscaler"
name = "stage2"
[ckpt]
interval = 100
resume_step = 500
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 16384
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
-40
View File
@@ -1,40 +0,0 @@
max_steps = 1500
seq_len = 24576
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[wandb]
project = "deepscaler"
name = "stage3"
[ckpt]
interval = 100
resume_step = 1000
[orchestrator]
batch_size = 1024
group_size = 8
[orchestrator.train.sampling]
temperature = 0.6
max_completion_tokens = 24576
[[orchestrator.train.env]]
id = "math-env"
name = "deepscaler"
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
[trainer.model.ac]
[inference.parallel]
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
-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]]
id = "aime2024"
name = "aime2024"
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
+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.dev357",
"verifiers>=0.1.15.dev388",
]
[build-system]
@@ -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
+41 -57
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.dev357",
"verifiers>=0.1.15.dev400",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -66,44 +66,29 @@ flash-attn-cute = [
"flash-attn-4",
]
envs = [
"aime2024",
"aime2025",
"alphabet-sort",
"code-env",
"color-codeword",
"deepdive",
"general-agent",
"gpqa",
"hle",
"ifeval",
"livecodebench",
"logic-env",
"math-env",
"math-python",
"math500",
"mini-swe-agent-plus",
"mmlu-pro",
"opencode-cp",
"opencode-deepdive",
"opencode-math",
"opencode-science",
"opencode-swe",
"reverse-text",
"rlm-swe",
"rlm-search",
"rlm-uuid-ctf",
"science-env",
"simpleqa-verified",
"tau2-bench",
"uuid-ctf-v1",
"wiki-search",
"wordle",
"reverse-text-v1",
"gsm8k-v1",
"math-env-v1",
"aime24-v1",
"aime25-v1",
"aime26-v1",
"alphabet-sort-v1",
"scaleswe-v1",
"color-codeword-v1",
"deepdive-v1",
"gpqa-v1",
"livecodebench-v1",
"r2e-gym-v1",
"terminal-bench-2-v1",
"code-golf-v1",
@@ -115,6 +100,13 @@ envs = [
"wordle-v1",
"general-agent-v1",
"swebench-verified-v1",
"tau2-bench-v1",
"math500-v1",
"mmlu-pro-v1",
"ifeval-v1",
"simpleqa-verified-v1",
"i3-code-v1",
"i3-science-v1",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64'",
@@ -174,7 +166,7 @@ override-dependencies = [
"transformers==5.6.2",
"torch>=2.9.0",
"openenv-core",
"verifiers>=0.1.15.dev357",
"verifiers>=0.1.15.dev400",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
@@ -222,59 +214,51 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
# prime-rl depends on the one `verifiers` package (v0 + v1 + the legacy bridge + the built-in v1
# harnesses/tasksets, now bundled in verifiers.v1). v0 envs resolve from
# deps/{verifiers,research-environments}/environments; v1 tasksets (`-v1`) and the `compact`
# example live under deps/verifiers/environments.
# example live under deps/{verifiers,research-environments}/environments.
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
aime2024 = { path = "deps/research-environments/environments/aime2024", editable = true }
aime2025 = { path = "deps/research-environments/environments/aime2025", editable = true }
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
code-env = { path = "deps/research-environments/environments/code_env", editable = true }
color-codeword = { path = "deps/research-environments/environments/color_codeword", editable = true }
deepdive = { path = "deps/research-environments/environments/deepdive", editable = true }
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
gpqa = { path = "deps/research-environments/environments/gpqa", editable = true }
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 }
rlm-uuid-ctf = { path = "deps/research-environments/environments/rlm_uuid_ctf", 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 }
uuid-ctf-v1 = { path = "deps/research-environments/environments/uuid_ctf_v1", editable = true }
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
gsm8k-v1 = { path = "deps/verifiers/environments/gsm8k_v1", editable = true }
math-env-v1 = { path = "deps/verifiers/environments/math_env_v1", editable = true }
aime24-v1 = { path = "deps/verifiers/environments/aime24_v1", editable = true }
math-env-v1 = { path = "deps/research-environments/environments/math_env_v1", editable = true }
aime24-v1 = { path = "deps/research-environments/environments/aime24_v1", editable = true }
aime25-v1 = { path = "deps/research-environments/environments/aime25_v1", editable = true }
aime26-v1 = { path = "deps/research-environments/environments/aime26_v1", editable = true }
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
scaleswe-v1 = { path = "deps/verifiers/environments/scaleswe_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 }
r2e-gym-v1 = { path = "deps/verifiers/environments/r2e_gym_v1", editable = true }
terminal-bench-2-v1 = { path = "deps/verifiers/environments/terminal_bench_2_v1", editable = true }
deepdive-v1 = { path = "deps/research-environments/environments/deepdive_v1", editable = true }
gpqa-v1 = { path = "deps/research-environments/environments/gpqa_v1", editable = true }
livecodebench-v1 = { path = "deps/research-environments/environments/livecodebench_v1", editable = true }
r2e-gym-v1 = { path = "deps/research-environments/environments/r2e_gym_v1", editable = true }
terminal-bench-2-v1 = { path = "deps/research-environments/environments/terminal_bench_2_v1", editable = true }
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_v1", editable = true }
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
swelego-v1 = { path = "deps/verifiers/environments/swelego_v1", editable = true }
swelego-v1 = { path = "deps/research-environments/environments/swelego_v1", editable = true }
wiki-search-v1 = { path = "deps/verifiers/environments/wiki_search_v1", editable = true }
wikispeedia-v1 = { path = "deps/verifiers/environments/wikispeedia_v1", editable = true }
wikispeedia-v1 = { path = "deps/research-environments/environments/wikispeedia_v1", editable = true }
wordle-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
general-agent-v1 = { path = "deps/verifiers/environments/general_agent_v1", editable = true }
swebench-verified-v1 = { path = "deps/verifiers/environments/swebench_verified_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" }
@@ -283,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" }
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env bash
set -euo pipefail
mode="env"
if [ "${1:-}" = "--shell" ] || [ "${1:-}" = "--github-output" ]; then
mode="${1#--}"
shift
fi
root="${1:-.}"
root="$(cd "$root" && pwd)"
dependency_floor_version() {
local package="$1"
find "$root" \
\( -path "$root/.git" -o -path "$root/.venv" \) -prune -o \
-type f -name pyproject.toml -print |
while IFS= read -r pyproject; do
sed -nE "s/.*[\"']${package}(\\[[^]]+\\])?>=([^\"',; ]+).*/\\2/p" "$pyproject"
done |
sort -V |
tail -n 1
}
next_patch_dev_version() {
local tag="$1"
local distance="$2"
local version="${tag#v}"
local major minor patch
if [ "$distance" = "0" ]; then
printf '%s\n' "$version"
return 0
fi
if [[ "$version" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
major="${BASH_REMATCH[1]}"
minor="${BASH_REMATCH[2]}"
patch="${BASH_REMATCH[3]}"
printf '%s.%s.%s.dev%s\n' "$major" "$minor" "$((patch + 1))" "$distance"
return 0
fi
return 1
}
describe_distance() {
sed -E 's/.*-([0-9]+)-g[0-9a-f]+$/\1/' <<< "$1"
}
describe_tag() {
sed -E 's/-[0-9]+-g[0-9a-f]+$//' <<< "$1"
}
verifiers_git_version() {
local dir="$root/deps/verifiers"
local desc tag distance
[ -d "$dir" ] || return 1
desc="$(git -C "$dir" describe --tags --long --match 'v[0-9]*.[0-9]*.[0-9]*' --exclude '*dev*' 2>/dev/null)" || return 1
tag="$(describe_tag "$desc")"
distance="$(describe_distance "$desc")"
next_patch_dev_version "$tag" "$distance"
}
renderers_git_version() {
local dir="$root/deps/renderers"
local desc tag distance version
[ -d "$dir" ] || return 1
desc="$(git -C "$dir" describe --tags --long --match 'renderers-v*' 2>/dev/null)" || return 1
tag="$(describe_tag "$desc")"
distance="$(describe_distance "$desc")"
version="${tag#renderers-v}"
if [ "$distance" = "0" ]; then
printf '%s\n' "$version"
return 0
fi
next_patch_dev_version "v$version" "$distance"
}
resolve_version() {
local package="$1"
local env_name="$2"
local git_func="$3"
local version
version="${!env_name:-}"
if [ -n "$version" ]; then
printf '%s\n' "$version"
return 0
fi
if version="$("$git_func")" && [ -n "$version" ]; then
printf '%s\n' "$version"
return 0
fi
version="$(dependency_floor_version "$package")"
if [ -n "$version" ]; then
printf '%s\n' "$version"
return 0
fi
printf 'Could not infer a pretend version for %s under %s\n' "$package" "$root" >&2
return 1
}
verifiers_version="$(resolve_version verifiers VERIFIERS_PRETEND_VERSION verifiers_git_version)"
renderers_version="$(resolve_version renderers RENDERERS_PRETEND_VERSION renderers_git_version)"
printf 'Resolved verifiers pretend version: %s\n' "$verifiers_version" >&2
printf 'Resolved renderers pretend version: %s\n' "$renderers_version" >&2
case "$mode" in
shell)
printf "export VERIFIERS_PRETEND_VERSION='%s'\n" "$verifiers_version"
printf "export RENDERERS_PRETEND_VERSION='%s'\n" "$renderers_version"
;;
github-output)
printf 'verifiers=%s\n' "$verifiers_version"
printf 'renderers=%s\n' "$renderers_version"
;;
env)
printf 'VERIFIERS_PRETEND_VERSION=%s\n' "$verifiers_version"
printf 'RENDERERS_PRETEND_VERSION=%s\n' "$renderers_version"
;;
*)
printf 'Unknown output mode: %s\n' "$mode" >&2
exit 2
;;
esac
+1 -1
View File
@@ -53,7 +53,7 @@ if [ -n "$PRIME_RL_REF" ]; then
cp -a /app/.venv "$DEST/.venv"
fi
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
# Mirror the image's extras (Dockerfile.cuda:82) — explicit instead
# Mirror the image's uv sync extras — explicit instead
# of --all-extras so we don't pull in `disagg` / `quack` and trigger
# heavy source builds (deep-ep, deep-gemm, quack-kernels) at pod
# startup. --inexact keeps the seeded venv's pre-built wheels
+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] = {}
+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))
+13 -16
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,8 +92,7 @@ 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)
@@ -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
-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]:
-7
View File
@@ -73,10 +73,6 @@ class InferencePool(Protocol):
"""Update weights on all inference servers."""
...
def get_metrics(self) -> dict[str, float]:
"""Get pool metrics."""
...
async def stop(self) -> None:
"""Stop the inference pool."""
...
@@ -141,9 +137,6 @@ 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 stop(self) -> None:
pass
-7
View File
@@ -499,10 +499,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]
+17
View File
@@ -33,3 +33,20 @@ def get_cu_seqlens_from_position_ids(position_ids: torch.Tensor) -> tuple[torch.
cu_seqlens[1:] = seqlens.cumsum(dim=0, dtype=torch.int32)
return cu_seqlens, seqlens.max().item()
def get_cu_seqlens_from_seq_lens(seq_lens: torch.Tensor, total_tokens: int | None = None) -> tuple[torch.Tensor, int]:
if seq_lens.ndim != 1:
raise ValueError(f"seq_lens must be 1D, got shape={tuple(seq_lens.shape)}")
if seq_lens.numel() == 0:
raise ValueError("seq_lens must not be empty")
if bool((seq_lens <= 0).any().item()):
raise ValueError(f"seq_lens must be positive, got {seq_lens.tolist()}")
if total_tokens is not None and int(seq_lens.sum().item()) != total_tokens:
raise ValueError(f"seq_lens sum must equal sequence length: {seq_lens.tolist()} vs {total_tokens}")
seq_lens = seq_lens.to(dtype=torch.int32)
cu_seqlens = torch.empty(seq_lens.numel() + 1, dtype=torch.int32, device=seq_lens.device)
cu_seqlens[0] = 0
cu_seqlens[1:] = seq_lens.cumsum(dim=0, dtype=torch.int32)
return cu_seqlens, int(seq_lens.max().item())
-62
View File
@@ -1,62 +0,0 @@
from pathlib import Path
from typing import Callable
import pytest
from tests.conftest import ProcessResult
from tests.utils import check_mismatch_kl_in_range, check_no_error, check_reward_goes_up, strip_escape_codes
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
"""Fixture for W&B name for RL CI integration tests."""
return f"acereason-math-{branch_name}"
@pytest.fixture(scope="module")
def rl_process(
run_process: Callable[..., ProcessResult],
output_dir: Path,
wandb_project: str,
wandb_name: str,
) -> ProcessResult:
cmd = [
"uv",
"run",
"rl",
"@",
"configs/ci/nightly/acereason_math.toml",
"--wandb.project",
wandb_project,
"--wandb.name",
wandb_name,
"--output-dir",
output_dir.as_posix(),
]
return run_process(cmd)
MISMATCH_KL_MIN = 0.0
MISMATCH_KL_MAX = 0.0015
@pytest.fixture(scope="module")
def test_no_error(rl_process: ProcessResult, output_dir: Path):
"""Tests that the RL process does not fail."""
check_no_error(rl_process, output_dir)
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
"""Tests that the reward goes up in the RL process"""
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
check_reward_goes_up(orchestrator_stdout)
def test_mismatch_kl_in_band(rl_process: ProcessResult, test_no_error, output_dir: Path):
"""Tests that mismatch KL stays within the expected band."""
with open(output_dir / "logs" / "trainer.log", "r") as f:
trainer_stdout = strip_escape_codes(f.read()).splitlines()
check_mismatch_kl_in_range(trainer_stdout, min_threshold=MISMATCH_KL_MIN, max_threshold=MISMATCH_KL_MAX)
+32 -4
View File
@@ -25,6 +25,21 @@ def _assistant_node(token_ids: list[int], logprobs: list[float]) -> vf.MessageNo
)
def _scaffold_assistant_node(
completion_ids: list[int], completion_logprobs: list[float], *, scaffold: int = 2
) -> vf.MessageNode:
"""A realistic v1 assistant node: a leading generation-prompt scaffold (mask=False, not
model-sampled) then the sampled completion. ``logprobs`` cover only the completion suffix
(vLLM returns logprobs for generated tokens only) — the exact layout where per-node
``zip(token_ids, logprobs, mask)`` mispairs and the branch streams normalize."""
return vf.MessageNode(
message=vf.AssistantMessage(content="x"),
token_ids=[1] * scaffold + completion_ids,
mask=[False] * scaffold + [True] * len(completion_ids),
logprobs=completion_logprobs,
)
def _make_rollout(
completion_ids: list[int],
completion_logprobs: list[float],
@@ -74,7 +89,6 @@ def test_gibberish_detects_rare_low_prob_token():
)
)
assert result.detected is True
assert result.detection_index == 1
def test_gibberish_ignores_normal_tokens():
@@ -87,7 +101,6 @@ def test_gibberish_ignores_normal_tokens():
)
)
assert result.detected is False
assert result.detection_index is None
def test_gibberish_ignores_high_prob_rare_token():
@@ -113,7 +126,23 @@ def test_gibberish_works_across_trajectory_steps():
)
)
assert result.detected is True
assert result.detection_index == 2
def test_gibberish_aligns_logprobs_under_generation_prompt_scaffold():
"""Regression: the assistant node carries a generation-prompt scaffold (mask=False) and
suffix-only logprobs, and the gibberish token is the LAST completion token. The old
per-node ``zip(token_ids, logprobs, mask)`` truncated at len(logprobs) and never examined
it; reading the aligned branch streams detects it."""
gibberish_filter = _make_gibberish_filter()
rollout = Rollout[vf.Task](
task=vf.Task(idx=0, prompt=""),
nodes=[_scaffold_assistant_node([50, 80, 120_000], [-1.0, -0.5, gibberish_filter.logprob_threshold - 1.0])],
rewards={"reward": 1.0},
)
result = gibberish_filter.check(rollout)
assert result.detected is True
# --- RepetitionFilter tests ---
@@ -129,7 +158,6 @@ def test_repetition_triggers_after_window():
)
)
assert result.detected is True
assert result.detection_index == 4
def test_repetition_no_trigger_below_window():
@@ -0,0 +1,186 @@
import pytest
import torch
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeTextRotaryEmbedding as HFQwen3_5MoeRotaryEmbedding,
)
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeRotaryEmbedding
from prime_rl.trainer.models.qwen3_5_moe.mrope import build_qwen3_5_mrope_position_ids
def _tiny_config() -> Qwen3_5MoeConfig:
return Qwen3_5MoeConfig(
vocab_size=128,
hidden_size=128,
num_attention_heads=2,
num_key_value_heads=1,
head_dim=64,
num_hidden_layers=1,
rope_parameters={
"rope_type": "default",
"rope_theta": 10000000,
"partial_rotary_factor": 0.25,
"mrope_section": [3, 3, 2],
"mrope_interleaved": True,
},
)
def test_qwen35_mrope_text_only_positions():
input_ids = torch.tensor([[10, 11, 12, 13]])
mm_token_type_ids = torch.zeros_like(input_ids)
position_ids = build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=None,
spatial_merge_size=2,
)
expected = torch.arange(4).view(1, 1, -1).expand(3, 1, -1)
torch.testing.assert_close(position_ids, expected)
def test_qwen35_mrope_single_image_with_surrounding_text():
input_ids = torch.tensor([[10, 11, 99, 99, 99, 99, 12]])
mm_token_type_ids = torch.tensor([[0, 0, 1, 1, 1, 1, 0]])
image_grid_thw = torch.tensor([[1, 4, 4]])
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=2,
)
expected = torch.tensor(
[
[[0, 1, 2, 2, 2, 2, 4]],
[[0, 1, 2, 2, 3, 3, 4]],
[[0, 1, 2, 3, 2, 3, 4]],
]
)
torch.testing.assert_close(position_ids, expected)
def test_qwen35_mrope_adjacent_images_consume_multiple_grids():
input_ids = torch.tensor([[10, 99, 99, 99, 99, 99, 99, 99, 99, 11]])
mm_token_type_ids = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 0]])
image_grid_thw = torch.tensor([[1, 4, 4], [1, 4, 4]])
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=2,
)
expected = torch.tensor(
[
[[0, 1, 1, 1, 1, 3, 3, 3, 3, 5]],
[[0, 1, 1, 2, 2, 3, 3, 4, 4, 5]],
[[0, 1, 2, 1, 2, 3, 4, 3, 4, 5]],
]
)
torch.testing.assert_close(position_ids, expected)
def test_qwen35_mrope_packed_segments_reset_independently():
input_ids = torch.tensor([[10, 99, 99, 99, 99, 11, 99, 99, 99, 99]])
mm_token_type_ids = torch.tensor([[0, 1, 1, 1, 1, 0, 1, 1, 1, 1]])
image_grid_thw = torch.tensor([[1, 4, 4], [1, 4, 4]])
seq_lens = torch.tensor([5, 5])
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=2,
seq_lens=seq_lens,
)
expected_segment = torch.tensor(
[
[0, 1, 1, 1, 1],
[0, 1, 1, 2, 2],
[0, 1, 2, 1, 2],
]
)
torch.testing.assert_close(position_ids[:, 0, :5], expected_segment)
torch.testing.assert_close(position_ids[:, 0, 5:], expected_segment)
def test_qwen35_mrope_packed_matches_standalone_segments():
segment_input_ids = torch.tensor([[10, 99, 99, 99, 99, 11]])
segment_token_types = torch.tensor([[0, 1, 1, 1, 1, 0]])
image_grid_thw = torch.tensor([[1, 4, 4]])
standalone = build_qwen3_5_mrope_position_ids(
input_ids=segment_input_ids,
mm_token_type_ids=segment_token_types,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
)
packed = build_qwen3_5_mrope_position_ids(
input_ids=torch.cat([segment_input_ids, segment_input_ids], dim=1),
mm_token_type_ids=torch.cat([segment_token_types, segment_token_types], dim=1),
image_grid_thw=torch.cat([image_grid_thw, image_grid_thw], dim=0),
spatial_merge_size=2,
seq_lens=torch.tensor([segment_input_ids.shape[1], segment_input_ids.shape[1]]),
)
torch.testing.assert_close(packed[:, :, : segment_input_ids.shape[1]], standalone)
torch.testing.assert_close(packed[:, :, segment_input_ids.shape[1] :], standalone)
def test_qwen35_mrope_rejects_image_length_grid_mismatch():
input_ids = torch.tensor([[10, 99, 99]])
mm_token_type_ids = torch.tensor([[0, 1, 1]])
image_grid_thw = torch.tensor([[1, 4, 4]])
with pytest.raises(ValueError, match="Image token group length"):
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=2,
)
def test_qwen35_mrope_rejects_video_tokens():
input_ids = torch.tensor([[10, 99]])
mm_token_type_ids = torch.tensor([[0, 2]])
with pytest.raises(ValueError, match="video MRoPE"):
build_qwen3_5_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=None,
spatial_merge_size=2,
)
def test_qwen35_rotary_matches_hf_for_2d_and_3d_positions():
config = _tiny_config()
prime_rotary = Qwen3_5MoeRotaryEmbedding(config)
hf_rotary = HFQwen3_5MoeRotaryEmbedding(config)
hidden_states = torch.randn(1, 6, config.hidden_size)
text_positions = torch.arange(6).unsqueeze(0)
prime_cos, prime_sin = prime_rotary(hidden_states, text_positions)
hf_cos, hf_sin = hf_rotary(hidden_states, text_positions)
torch.testing.assert_close(prime_cos, hf_cos)
torch.testing.assert_close(prime_sin, hf_sin)
mrope_positions = torch.stack(
[
torch.tensor([[0, 1, 2, 2, 2, 4]]),
torch.tensor([[0, 1, 2, 2, 3, 4]]),
torch.tensor([[0, 1, 2, 3, 2, 4]]),
]
)
prime_cos, prime_sin = prime_rotary(hidden_states, mrope_positions)
hf_cos, hf_sin = hf_rotary(hidden_states, mrope_positions)
torch.testing.assert_close(prime_cos, hf_cos)
torch.testing.assert_close(prime_sin, hf_sin)
@@ -35,6 +35,7 @@ def _tiny_vlm_config():
tc.linear_num_key_heads = 4
tc.linear_num_value_heads = 8
tc.use_cache = False
tc.rope_parameters["mrope_section"] = [3, 3, 2]
vc = config.vision_config
vc.depth = 2
@@ -62,6 +63,12 @@ def _make_image_inputs(config, device="cuda", dtype=torch.float32):
return pixel_values, image_grid_thw, num_image_tokens
def _make_mm_token_type_ids(input_ids, image_token_id):
mm_token_type_ids = torch.zeros_like(input_ids)
mm_token_type_ids[input_ids == image_token_id] = 1
return mm_token_type_ids
def test_vlm_forward():
"""Custom VLM produces logits for both text-only and multimodal inputs."""
config = _tiny_vlm_config()
@@ -82,8 +89,14 @@ def test_vlm_forward():
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids_mm = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
mm_token_type_ids = _make_mm_token_type_ids(input_ids_mm, config.image_token_id)
out_mm = model(input_ids=input_ids_mm, pixel_values=pixel_values, image_grid_thw=image_grid_thw)
out_mm = model(
input_ids=input_ids_mm,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
)
assert out_mm["logits"].shape == (1, input_ids_mm.shape[1], vocab)
@@ -98,8 +111,14 @@ def test_vlm_backward():
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
mm_token_type_ids = _make_mm_token_type_ids(input_ids, config.image_token_id)
out = model(input_ids=input_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw)
out = model(
input_ids=input_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
)
out["logits"].sum().backward()
assert model.model.language_model.embed_tokens.weight.grad is not None
@@ -170,6 +189,42 @@ def test_vlm_weight_roundtrip():
assert torch.equal(roundtripped[original_vision_key], original_vision_weight)
def test_vlm_forward_requires_mm_token_type_ids():
"""Image MRoPE needs renderer-supplied modality token types."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.float32):
model = Qwen3_5MoeForCausalLM(config)
inject_prime_lm_head(model)
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
input_ids = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
with pytest.raises(ValueError, match="mm_token_type_ids"):
model(input_ids=input_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw)
def test_vlm_forward_rejects_2d_positions_with_images():
"""Trainer 1D/2D packed positions are not valid image MRoPE coordinates."""
config = _tiny_vlm_config()
with torch.device("cuda"), default_dtype(torch.float32):
model = Qwen3_5MoeForCausalLM(config)
inject_prime_lm_head(model)
pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config)
input_ids = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
mm_token_type_ids = _make_mm_token_type_ids(input_ids, config.image_token_id)
position_ids = torch.arange(n_img_tokens, device="cuda").unsqueeze(0)
with pytest.raises(ValueError, match="3D MRoPE position_ids"):
model(
input_ids=input_ids,
position_ids=position_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
)
def test_vlm_router_replay():
"""routed_experts bypasses router computation in VLM multimodal forward."""
config = _tiny_vlm_config()
@@ -182,6 +237,7 @@ def test_vlm_router_replay():
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
mm_token_type_ids = _make_mm_token_type_ids(input_ids, config.image_token_id)
seq_len = input_ids.shape[1]
num_layers = config.text_config.num_hidden_layers
@@ -189,7 +245,11 @@ def test_vlm_router_replay():
routed_experts = torch.randint(0, config.text_config.num_experts, (1, seq_len, num_layers, topk), device="cuda")
out = model(
input_ids=input_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw, routed_experts=routed_experts
input_ids=input_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
routed_experts=routed_experts,
)
assert out["logits"].shape == (1, seq_len, vocab)
+14 -1
View File
@@ -1,7 +1,7 @@
import pytest
import torch
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids, get_cu_seqlens_from_seq_lens
@pytest.mark.parametrize(
@@ -23,3 +23,16 @@ def test_get_cu_seqlens_from_position_ids_is_local_relative(
assert cu_seqlens.dtype == torch.int32
assert cu_seqlens.tolist() == expected_cu_seqlens
assert max_seqlen == expected_max_seqlen
def test_get_cu_seqlens_from_seq_lens():
cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens(torch.tensor([4, 3, 2]), total_tokens=9)
assert cu_seqlens.dtype == torch.int32
assert cu_seqlens.tolist() == [0, 4, 7, 9]
assert max_seqlen == 4
def test_get_cu_seqlens_from_seq_lens_rejects_wrong_total():
with pytest.raises(ValueError, match="sum must equal"):
get_cu_seqlens_from_seq_lens(torch.tensor([4, 3]), total_tokens=9)
Generated
+318 -405
View File
File diff suppressed because it is too large Load Diff