Compare commits

...
Author SHA1 Message Date
5f0dcc8a1b chore: upgrade vllm from 0.17.0rc0 to 0.17.0 stable (#1980)
Release / Push CUDA image to Docker (push) Canceled after 0s
Use the stable PyPI release instead of pre-built wheels from wheels.vllm.ai.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 18:27:51 -08:00
rasdaniandGitHub 8ea7bd4834 fix: wire verifiers max_seq_len correctly (#1983)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-08 00:19:09 +01:00
302ef6d084 fix: only pass --weight_broadcast.host to orchestrator when nccl broadcast is configured (#1979)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-07 15:07:42 -08:00
JannikStandGitHub 89a5343780 fix arm64 flash-attn-cute: revert to 2b5db43 for sm100 pipeline fix (#1982)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix arm64 flash-attn-cute: use 2b5db43 rev with sm100 pipeline fix

* also update fix-flash-attn-cute.sh to 2b5db43
2026-03-07 23:23:26 +01:00
22f0ae7640 fix: reduce orchestrator memory usage for VLM rollouts (#1964)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: reduce orchestrator memory usage for VLM rollouts

The orchestrator's RSS grew unboundedly when processing VLM rollouts
with images (e.g. 1.2 GB → 25+ GB over 10 steps, spiking to 38 GB).
Three root causes:

1. Base64 image data in rollout prompts stayed alive through the entire
   step pipeline (preprocessing, training batch, wandb logging). Now
   stripped immediately after image extraction in _extract_images_from_examples.

2. Intermediate objects (PIL images, torch tensors, chunk results) in
   _preprocess_images_batched were held simultaneously. Now freed eagerly
   with del/clear() after each conversion step.

3. Python's GC and glibc malloc arenas retained freed memory across steps.
   Now explicitly gc.collect() + malloc_trim(0) at end of each step.

Result: baseline 3-5 GB (stable), spikes 5-9 GB (bounded).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: extract strip_base64_images into a standalone function

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: delete chunks before clearing images to actually free PIL objects

chunks holds shallow-copy references to the same PIL images, so
images.clear() alone doesn't free them during peak memory usage.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Update src/prime_rl/orchestrator/trajectories.py

Signed-off-by: hallerite <git@hallerite.com>

---------

Signed-off-by: hallerite <git@hallerite.com>
Co-authored-by: root <root@vivid-capybara-of-dignity.datacrunch.io>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: hallerite <git@hallerite.com>
2026-03-06 18:06:09 -08:00
JannikStandGitHub f0746566e9 fix arm64 flash-attn: run uv pip from /tmp to avoid pyproject.toml build vars (#1975)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-07 02:10:43 +01:00
JannikStandGitHub 99c02bba6c fix arm64 flash-attn build: override FLASH_ATTENTION_SKIP_CUDA_BUILD (#1974)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix arm64 flash-attn build: override FLASH_ATTENTION_SKIP_CUDA_BUILD

* also set FLASH_ATTENTION_FORCE_BUILD to bypass cached wheel download
2026-03-07 00:12:09 +01:00
JannikStandGitHub ebb5a1cac2 add --no-cache to force flash-attn source build on arm64 (#1973)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-06 21:43:45 +01:00
JannikStandGitHub d19ce7919f force flash-attn source build on arm64 with --no-binary (#1972)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-06 21:02:18 +01:00
JannikStandGitHub e2175c11ae add aarch64 vllm wheel and restrict uv environments to linux x86_64/aarch64 (#1970)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-06 10:53:20 +01:00
JannikStandGitHub d4bfa08977 Add arm64 support to Dockerfile and deps (#1933)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Add arm64 support to Dockerfile and deps

- Swap builder base to multi-arch nvidia/cuda:12.8.1 image
- Add platform_machine markers to x86_64-only wheel deps

* Fix tzdata interactive prompt in arm64 build

* Fix tzdata interactive prompt in Docker build

* add arm64 flash-attn source build and expose max_num_seqs on inference CLI

* only target sm_100 for arm64 flash-attn build

* remove max_num_seqs, belongs in a separate PR

* also build flash-attn-3 from source for arm64, supports sm_100

* use pip for flash-attn-3, uv cant resolve torch match-runtime from git

* use pip for flash-attn-3: uv rejects match-runtime without static metadata

* link uv issue in dockerfile comment

* use venv pip for flash-attn-3, pip not on PATH in builder

* use uv run pip for flash-attn-3

* install pip into venv before using it for flash-attn-3

* fix arm64 flash-attn build: export env vars, add ninja

* fix: install python ninja package, export all env vars properly

* remove flash-attn-3 from arm64 build, fa4 (flash-attn-cute) is used instead

* Fix missing cutlass.utils.ampere_helpers on arm64 (#1948)

* Fix missing cutlass.utils.ampere_helpers on arm64

flash-attn.cute imports cutlass.utils.ampere_helpers but
nvidia-cutlass-dsl 4.4.1 doesn't ship that module. Copy it
from flashinfer's vendored cutlass which has the file.

* Expand Dockerfile comment explaining cutlass ampere_helpers workaround

* Reinstall flash-attn-cute after flash-attn on arm64 to fix namespace conflict (#1949)

* Pin flash-attn-cute to locked commit, upstream renamed package to flash-attn-4 (#1950)

* Upgrade flash-attn-cute for cutlass-dsl 4.4.1 backward pass fix (#1952)

* Upgrade flash-attn-cute to 7ed0898 for cutlass-dsl 4.4.1 compatibility

* Pin fix-flash-attn-cute.sh to same commit as pyproject.toml

* Pin flash-attn-cute to 2b5db43 for cutlass-dsl 4.4.1 compat and sm100 backward fix

* refactor: extract arm64 post-install logic into script

* skip arm64 script entirely on x86, trim comments

* update uv.lock

* revert pydantic-config to branch=main

* pin flash-attn==2.8.3 in arm64 post-install

* pin flash-attn-cute to e2743ab5, regenerate uv.lock

* align flash-attn-cute rev in scripts with pyproject.toml (e2743ab5)
2026-03-06 09:56:16 +01:00
599cea81c1 fix vllm 17 nihglty (#1969)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix vllm 17 nihglty

* fix vllm 0.17 compat: conditionally pass log_error_stack

---------

Co-authored-by: Jannik Straube <info@jannik-straube.de>
2026-03-06 00:25:05 -08:00
c344a8a3c6 fix: modality-aware batch distribution to prevent FSDP deadlocks (#1959)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: modality-aware batch distribution to prevent FSDP deadlocks

When training multimodal models with FSDP, ranks must execute the same
operations at each step. If one rank processes a multimodal batch
(triggering the vision encoder all-gather) while another processes
text-only, training hangs. Fix by separating micro batches by modality,
padding each group independently, and distributing in strided order so
all ranks see the same modality at each step index.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* ruff format

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: root <root@vivid-capybara-of-dignity.datacrunch.io>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 03:04:33 +01:00
892c895b83 fix: disable timeout on admin httpx clients (#1955)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: disable timeout on admin httpx clients

Admin operations (weight updates, LoRA loading, NCCL broadcast) can block
for an unbounded amount of time — especially under load where vLLM servers
are slow to enter NCCL receive mode. The previous 1200s read timeout was
causing orchestrator crashes on heavy prod runs.

Also adds retry logic to _update_weights for 5xx responses, matching the
existing behaviour of load_lora_adapter.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* remove retry

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-05 10:57:46 -08:00
94984b9790 feat: add Qwen3.5 support (#1946)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: add Qwen3.5 support

Bump vLLM to >=0.16.1.dev (nightly) which includes Qwen3.5 model support.
This requires torch 2.10 (resolved from the existing >=2.9.0 pin), an
updated flash-attn wheel built against torch 2.10, and version overrides
for nvidia-cutlass-dsl and quack-kernels.

Bump transformers pin to 5c1c72b which includes a rope validation fix
for Qwen3.5 (https://github.com/huggingface/transformers/pull/44272).

Add a trainer monkey-patch for a transformers bug where Qwen3.5 passes
3D MRoPE position_ids to decoder layers instead of 2D text_position_ids,
which breaks flash attention and causes NaN gradients. The upstream fix
is pending: https://github.com/huggingface/transformers/pull/44399

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* apply patch for Qwen3.5 MoE model variants

* remove duplicated nvidia-cutlass-dsl override

* fix: patch Qwen3.5 MoE weight conversion mapping for broadcasting

* ruff

* change wheel

* fix vllm v0.16.1.dev (#1954)

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
2026-03-05 11:34:43 +01:00
Christian RandGitHub 15fc324d1b perf: parallelize VLM image preprocessing across threads (#1951)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-04 22:57:53 -08:00
868ba03d9b fix: use qwen3_coder tool parser for Qwen3.5 models (#1953)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: use qwen3_coder tool parser for Qwen3.5 models

Qwen3.5 uses a different tool call format than Qwen3. Qwen3 uses
hermes-style JSON, but Qwen3.5 uses an XML-like format with
<function=name><parameter=arg> tags. Map all Qwen3.5 variants to
the qwen3_coder parser so tool calls are parsed correctly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix for tool parser test

---------

Co-authored-by: root <root@vivid-capybara-of-dignity.datacrunch.io>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Johannes Hagemann <johannes@primeintellect.ai>
2026-03-04 21:36:31 -08:00
halleriteandGitHub aa33d910a4 update deep-gemm (#1944)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-04 12:57:07 -08:00
ac7ac62115 chore: update pydantic-config for JSON dict CLI support (#1943)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore: update pydantic-config for JSON dict CLI support

Update pydantic-config to latest main which adds support for passing
dict[str, Any] fields as JSON via CLI:
  --inference.vllm-extra '{"custom_arg": "value"}'

Also switch source from pinned rev to branch = "main".

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: update pydantic-config lock to include JSON dict fix

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 12:33:16 -08:00
JannikStandGitHub 99058e9e37 bump nvidia-cutlass-dsl to 4.4.1 for flash-attn-cute ampere_helpers (#1945)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-04 05:54:10 +01:00
halleriteandGitHub fe32efbee1 perf: deduplicate VLM image bytes in orchestrator cache (#1935)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-03 13:49:21 -08:00
6a97762b5c fix: use space-separated list args for tyro CLI compatibility (#1942)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: use space-separated list args for tyro CLI compatibility

tyro parses list[str] fields as space-separated values, not
comma-separated. Update the multi-node SLURM template and integration
test to match. Also fix snake_case --weight_broadcast.host to
kebab-case --weight-broadcast.host.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* revert unnecessary kebab-case change for weight_broadcast.host

Both snake_case and kebab-case are accepted by tyro, so keep the
original snake_case to minimize diff.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 13:33:19 -08:00
8451067db7 fix env server task cancellation (#1939)
Release / Push CUDA image to Docker (push) Canceled after 0s
* bump vf (bb73f78, feature branch)

* fix: drop stale groups concurrently to avoid inflated cancellation count

The sequential drop_group loop allowed _fill_inflight_requests to add
new tasks to not-yet-dropped stale groups during yields, causing the
cancelled count to exceed max_inflight_rollouts. Using asyncio.gather
ensures all drops snapshot inflight_requests before any of them yield.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* bump vf (45fae8d, main)

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-03 12:03:21 -08:00
ea161dd743 fix: validate prompt length in TITO endpoint before computing max_tokens (#1938)
Release / Push CUDA image to Docker (push) Canceled after 0s
In multi-turn TITO rollouts, prompt_token_ids are injected after
render_chat_request, bypassing vLLM's built-in context length
validation. When the prompt exceeds max_model_len, get_max_tokens
returns a negative value, causing a BadRequestError ("max_tokens must
be at least 1") that isn't recognized as an overlong prompt by the
verifiers client — aborting the rollout instead of truncating it.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-03 11:07:29 -08:00
Christian RandGitHub 9104df43c6 Serialize VLM pixel_values as raw bytes for 8-10x faster preprocessing (#1923)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-03 09:51:29 -08:00
Mika SenghaasandGitHub 02bdca2e41 change default rl algo to ipo (#1930)
Release / Push CUDA image to Docker (push) Canceled after 0s
* first impl for dppo+kl

* fix ratio_type ref

* sum the loss

* set kl_tau=1e-3 by default

* fix

* change to ipo + remove type ignore

* update changelog

* fix

* update names
2026-03-03 02:55:39 -08:00
27 changed files with 1546 additions and 1401 deletions
+2 -1
View File
@@ -96,4 +96,5 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`[slurm]` (inference)**: Added SLURM configuration to `InferenceConfig`. When present, `uv run inference` generates and submits an sbatch script instead of running locally. Each SLURM node runs an independent vLLM replica (no cross-node parallelism) (2026-02-26)
- **`[deployment]` (inference)**: Added deployment configuration. `type = "single_node"` (default) with `gpus_per_node`. `type = "multi_node"` with `num_nodes` and `gpus_per_node` — requires `[slurm]` (2026-02-26)
- **`inference.output_dir`**: Added directory for SLURM logs and generated scripts (default: `"outputs"`) (2026-02-26)
- **`inference.dry_run`**: Added flag (default: `False`). When set, validates config, writes resolved config to `output_dir/configs/`, and exits without starting inference or submitting SLURM jobs (2026-02-26)
- **`inference.dry_run`**: Added flag (default: `False`). When set, validates config, writes resolved config to `output_dir/configs/`, and exits without starting inference or submitting SLURM jobs (2026-02-26)
- **`trainer.loss` (default loss)**: Made IPO (DPPO-Binary TV variant ([arxiv](https://arxiv.org/pdf/2602.04879)) + Kimi-K2.5 KL ([Kimi-K2.5](https://arxiv.org/pdf/2602.02276))) the default loss. Removed `ratio_type`, `token_mask_low`, `token_mask_high`, `sequence_clip_high`, `geo_mask_low`, `geo_mask_high`, `sequence_mask_low`, `sequence_mask_high`. Added `ipo_mask_low` (default: 0.2) and `ipo_mask_high` (default: 0.2) for token-level probability-difference masking. Changed `kl_tau` default from `0.0` to `1e-3`. (2026-03-02)
+18 -3
View File
@@ -1,7 +1,7 @@
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
# Build stage
FROM pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel AS builder
# Build stage - multi-arch base (supports amd64 + arm64)
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu22.04 AS builder
LABEL maintainer="prime intellect"
LABEL repository="prime-rl"
@@ -12,12 +12,22 @@ RUN echo "LC_ALL=en_US.UTF-8" >> /etc/environment
ENV CUDA_HOME=/usr/local/cuda
ENV PATH=$PATH:/usr/local/cuda/bin
# Install packages
# Install packages (including Python 3.12 and ninja for fast CUDA kernel compilation)
ARG DEBIAN_FRONTEND=noninteractive
ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=Etc/UTC
RUN apt-get update && apt-get install -y --no-install-recommends --force-yes \
build-essential \
curl \
sudo \
git \
ninja-build \
software-properties-common \
&& add-apt-repository ppa:deadsnakes/ppa \
&& apt-get update \
&& apt-get install -y --no-install-recommends python3.12 python3.12-dev python3.12-venv \
&& ln -sf /usr/bin/python3.12 /usr/bin/python3 \
&& ln -sf /usr/bin/python3.12 /usr/bin/python \
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# Download the latest installer
@@ -45,6 +55,11 @@ COPY benchmarks/scripts /app/benchmarks/scripts
RUN --mount=type=cache,target=/app/.cache/uv \
uv sync --all-extras --locked --no-dev
# 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
RUN apt-get update && apt-get install -y \
+16 -9
View File
@@ -19,7 +19,7 @@ dependencies = [
"torch>=2.9.0",
"torchdata>=0.11.0",
"transformers",
"vllm>=0.16.0",
"vllm>=0.17.0",
"wandb>=0.24.2",
"ring-flash-attn>=0.1.8",
"prime>=0.5.37",
@@ -50,18 +50,18 @@ prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
[project.optional-dependencies]
flash-attn = [
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.6.8/flash_attn-2.8.3+cu128torch2.9-cp312-cp312-linux_x86_64.whl",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3+cu128torch2.10-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
]
flash-attn-3 = [
"flash_attn_3 @ https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl",
"flash_attn_3 @ https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl ; platform_machine == 'x86_64'",
]
flash-attn-cute = [
"flash-attn-cute",
]
[dependency-groups]
fp8-inference = [
"deep-gemm @ https://github.com/hallerite/DeepGEMM/releases/download/v2.3.0/deep_gemm-2.3.0+35c4bc8-cp312-cp312-linux_x86_64.whl",
"deep-gemm @ https://github.com/hallerite/DeepGEMM/releases/download/v2.3.0-torch2.9/deep_gemm-2.3.0+35c4bc8-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
]
dev = [
"ipykernel>=6.29.5",
@@ -75,22 +75,28 @@ dev = [
[tool.uv]
preview = true
no-build-isolation-package = ["flash-attn"]
environments = [
"sys_platform == 'linux' and platform_machine == 'x86_64'",
"sys_platform == 'linux' and platform_machine == 'aarch64'",
]
# Override torch's pinned cuDNN to fix Conv3d performance regression (torch 2.9 + cuDNN 9.8-9.14)
# See: https://github.com/pytorch/pytorch/issues/166122
override-dependencies = [
"nvidia-cudnn-cu12>=9.15",
"nvidia-cutlass-dsl>=4.4.1",
"transformers>=5.1.0.dev0",
"quack-kernels>=0.2.7",
]
[tool.uv.sources]
torch = { index = "pytorch-cu128" }
math-env = { index = "primeintellect" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "b35d0c7" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "45fae8d" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "609e3d5" }
flash-attn-cute = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "main" }
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", rev = "6990941" }
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "5c1c72b" }
flash-attn-cute = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "e2743ab5" }
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", branch = "main" }
reverse-text = { index = "primeintellect" }
[tool.uv.extra-build-dependencies]
@@ -106,9 +112,10 @@ url = "https://hub.primeintellect.ai/primeintellect/simple/"
[[tool.uv.index]]
name = "pytorch-cu128"
url = "https://download.pytorch.org/whl/test/cu128"
url = "https://download.pytorch.org/whl/cu128"
explicit = true
[tool.ruff.lint]
select = ["F", "I"]
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
+23
View File
@@ -0,0 +1,23 @@
#!/bin/bash
# arm64 post-install fixups for Docker builds.
set -e
echo "=== building flash-attn from source (sm_100 / GB200) ==="
# Run from /tmp so uv doesn't read pyproject.toml's [tool.uv.extra-build-variables]
# which sets FLASH_ATTENTION_SKIP_CUDA_BUILD=TRUE and prevents CUDA kernel compilation.
export TORCH_CUDA_ARCH_LIST="10.0"
export MAX_JOBS=4
export FLASH_ATTENTION_FORCE_BUILD=TRUE
export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
(cd /tmp && uv pip install --python /app/.venv/bin/python \
"flash-attn==2.8.3" --no-build-isolation --no-binary flash-attn --no-cache)
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
uv pip install --reinstall --no-deps \
"flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
# TODO: remove once flash-attn gates the ampere_helpers import or cutlass-dsl re-adds it.
echo "=== copying ampere_helpers.py from flashinfer vendor ==="
SITE_PACKAGES=".venv/lib/python3.12/site-packages"
cp "$SITE_PACKAGES/flashinfer/data/cutlass/python/CuTeDSL/cutlass/utils/ampere_helpers.py" \
"$SITE_PACKAGES/nvidia_cutlass_dsl/python_packages/cutlass/utils/ampere_helpers.py"
+1 -1
View File
@@ -11,7 +11,7 @@
set -e
echo "Reinstalling flash-attn-cute to fix namespace conflict with flash-attn..."
uv pip install --reinstall --no-deps "flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@main#subdirectory=flash_attn/cute"
uv pip install --reinstall --no-deps "flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
# Verify installation
LINES=$(wc -l < "$(python -c 'import flash_attn.cute.interface as m; print(m.__file__)')")
+1 -1
View File
@@ -939,7 +939,7 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def resolve_extra_env_kwargs(self):
train_extra_env_kwargs = dict(
seq_len=self.seq_len,
max_seq_len=self.seq_len,
score_rollouts=self.verification.enabled,
)
for env in self.env:
+4 -49
View File
@@ -530,68 +530,23 @@ class CheckpointConfig(BaseConfig):
] = False
# -- RL trainer-specific configs --
class DefaultLossConfig(BaseModel):
"""Config for the default loss."""
type: Literal["default"] = "default"
ratio_type: Annotated[Literal["token", "sequence"], Field(description="Type of importance ratio to use.")] = "token"
token_mask_high: Annotated[
float, Field(ge=0, description="The high threshold for token importance ratio to mask.")
] = 8.0
token_mask_low: Annotated[
float, Field(ge=0, description="The low threshold for token importance ratio to mask.")
] = 0.125
sequence_clip_high: Annotated[
float, Field(ge=0, description="The high threshold for sequence importance ratio to clip.")
] = 10.0
geo_mask_high: Annotated[float, Field(ge=0, description="The high threshold for geo importance ratio to mask.")] = (
10.0
)
geo_mask_low: Annotated[float, Field(ge=0, description="The low threshold for geo importance ratio to mask.")] = 0.1
sequence_mask_low: Annotated[
float,
Field(
ge=0,
description="If set, masks entire sequences when any generated token has an importance ratio below this value.",
),
] = 0.0
sequence_mask_high: Annotated[
float,
Field(
ge=0,
description="If set, masks entire sequences when any generated token has an importance ratio above this value.",
),
] = 100.0
ipo_mask_low: Annotated[float, Field(ge=0, description="The low threshold for masking tokens.")] = 0.2
ipo_mask_high: Annotated[float, Field(ge=0, description="The high threshold for masking tokens.")] = 0.2
adv_tau: Annotated[float, Field(ge=0, description="The tau for advantages.")] = 1.0
teacher_tau: Annotated[float, Field(ge=0, description="The tau for teacher logprobs.")] = 0.0
kl_tau: Annotated[float, Field(ge=0, description="The tau for KL divergence.")] = 0.0
@model_validator(mode="after")
def validate_mask_bounds(self):
if self.token_mask_low >= self.token_mask_high:
raise ValueError(
f"token_mask_low ({self.token_mask_low}) must be less than token_mask_high ({self.token_mask_high})"
)
if self.geo_mask_low >= self.geo_mask_high:
raise ValueError(
f"geo_mask_low ({self.geo_mask_low}) must be less than geo_mask_high ({self.geo_mask_high})"
)
if self.sequence_mask_low >= self.sequence_mask_high:
raise ValueError(
f"sequence_mask_low ({self.sequence_mask_low}) must be less than sequence_mask_high ({self.sequence_mask_high})"
)
return self
kl_tau: Annotated[float, Field(ge=0, description="The tau for KL divergence.")] = 1e-3
class CustomLossConfig(BaseModel):
"""Config for a custom external loss function."""
type: Literal["custom"] = "custom"
import_path: Annotated[str, Field(description="Import path to the loss function (e.g., 'my_module.my_loss')")]
kwargs: Annotated[dict[str, Any], Field(default_factory=dict, description="Kwargs to pass to the loss function")]
+1
View File
@@ -406,6 +406,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
inference_tp=config.inference.parallel.tp,
inference_enable_expert_parallel=config.inference.enable_expert_parallel,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
)
script_path.parent.mkdir(parents=True, exist_ok=True)
+29 -8
View File
@@ -98,9 +98,25 @@ MODEL_TOOL_CALL_PARSER: dict[str, str] = {
"Qwen/Qwen3-Coder-Next": "hermes",
"Qwen/Qwen3-Coder-Next-Base": "hermes",
"Qwen/Qwen3-Coder-Next-FP8": "hermes",
# Qwen3.5
"Qwen/Qwen3.5-397B-A17B": "hermes",
"Qwen/Qwen3.5-397B-A17B-FP8": "hermes",
# Qwen3.5 dense (uses qwen3_coder tool format, not hermes)
"Qwen/Qwen3.5-0.8B": "qwen3_coder",
"Qwen/Qwen3.5-0.8B-Base": "qwen3_coder",
"Qwen/Qwen3.5-2B": "qwen3_coder",
"Qwen/Qwen3.5-2B-Base": "qwen3_coder",
"Qwen/Qwen3.5-4B": "qwen3_coder",
"Qwen/Qwen3.5-4B-Base": "qwen3_coder",
"Qwen/Qwen3.5-9B": "qwen3_coder",
"Qwen/Qwen3.5-9B-Base": "qwen3_coder",
"Qwen/Qwen3.5-27B": "qwen3_coder",
"Qwen/Qwen3.5-27B-FP8": "qwen3_coder",
# Qwen3.5 MoE (uses qwen3_coder tool format, not hermes)
"Qwen/Qwen3.5-35B-A3B": "qwen3_coder",
"Qwen/Qwen3.5-35B-A3B-Base": "qwen3_coder",
"Qwen/Qwen3.5-35B-A3B-FP8": "qwen3_coder",
"Qwen/Qwen3.5-122B-A10B": "qwen3_coder",
"Qwen/Qwen3.5-122B-A10B-FP8": "qwen3_coder",
"Qwen/Qwen3.5-397B-A17B": "qwen3_coder",
"Qwen/Qwen3.5-397B-A17B-FP8": "qwen3_coder",
}
@@ -255,10 +271,7 @@ async def custom_init_app_state(
resolved_chat_template = load_chat_template(args.chat_template)
serving_chat = OpenAIServingChatWithTokens(
engine_client,
state.openai_serving_models,
args.response_role,
chat_kwargs = dict(
request_logger=request_logger,
chat_template=resolved_chat_template,
chat_template_content_format=args.chat_template_content_format,
@@ -271,7 +284,15 @@ async def custom_init_app_state(
enable_prompt_tokens_details=args.enable_prompt_tokens_details,
enable_force_include_usage=args.enable_force_include_usage,
enable_log_outputs=args.enable_log_outputs,
log_error_stack=args.log_error_stack,
)
if hasattr(args, "log_error_stack"):
chat_kwargs["log_error_stack"] = args.log_error_stack
serving_chat = OpenAIServingChatWithTokens(
engine_client,
state.openai_serving_models,
args.response_role,
**chat_kwargs,
)
state.openai_serving_chat = serving_chat if "generate" in supported_tasks else None
state.openai_serving_chat_with_tokens = serving_chat if "generate" in supported_tasks else None
@@ -10,11 +10,11 @@ from vllm.entrypoints.openai.chat_completion.serving import OpenAIServingChat
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, RequestResponseMetadata
from vllm.entrypoints.openai.engine.serving import GenerationError
from vllm.entrypoints.utils import get_max_tokens
from vllm.exceptions import VLLMValidationError
from vllm.logger import init_logger
from vllm.outputs import RequestOutput
from vllm.reasoning import ReasoningParser
from vllm.sampling_params import BeamSearchParams, SamplingParams
from vllm.v1.sample.logits_processor import validate_logits_processors_parameters
logger = init_logger(__name__)
@@ -96,8 +96,11 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
raw_request: Optional[Request] = None,
) -> Union[AsyncGenerator[str, None], ChatCompletionResponse, ErrorResponse]:
"""
Copy of OpenAIServingChat.create_chat_completion, adapted to use prompt
ids directly via ChatCompletionRequestWithTokens.
Chat Completion API similar to OpenAI's API.
See https://platform.openai.com/docs/api-reference/chat/create
for the API specification. This API mimics the OpenAI
Chat Completion API.
"""
# Streaming response
tokenizer = self.renderer.tokenizer
@@ -123,8 +126,9 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
conversation, engine_prompts = result
# We override prompt tokens directly.
# VLM conversations use MITO (message-based) instead of TITO, so
# multi_modal_data is not expected here. Override prompt tokens directly.
# multi_modal_data is not expected here.
engine_prompts[0]["prompt_token_ids"] = request.tokens # type: ignore
request_id = f"chatcmpl-{self._base_request_id(raw_request, request.request_id)}"
@@ -145,20 +149,33 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
data_parallel_rank = self._get_data_parallel_rank(raw_request)
# Schedule the request and get the result generator.
max_model_len = self.model_config.max_model_len
generators: list[AsyncGenerator[RequestOutput, None]] = []
try:
for i, engine_prompt in enumerate(engine_prompts):
prompt_text = self._extract_prompt_text(engine_prompt)
prompt_token_ids = self._extract_prompt_components(engine_prompt).token_ids
# If we are creating sub requests for multiple prompts, ensure that they
# have unique request ids.
sub_request_id = request_id if len(engine_prompts) == 1 else f"{request_id}_{i}"
prompt_len = self._extract_prompt_len(engine_prompt)
if prompt_len >= max_model_len:
raise VLLMValidationError(
f"This model's maximum context length is "
f"{max_model_len} tokens. However, your request has "
f"{prompt_len} input tokens. Please reduce the length of "
"the input messages.",
parameter="input_tokens",
value=prompt_len,
)
max_tokens = get_max_tokens(
self.max_model_len,
max_model_len,
request.max_completion_tokens if request.max_completion_tokens is not None else request.max_tokens,
self._extract_prompt_len(engine_prompt),
self.default_sampling_params,
self.override_max_tokens,
)
sampling_params: SamplingParams | BeamSearchParams
@@ -167,13 +184,8 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
else:
sampling_params = request.to_sampling_params(
max_tokens,
self.model_config.logits_processor_pattern,
self.default_sampling_params,
)
validate_logits_processors_parameters(
self.logits_processors,
sampling_params,
)
self._log_inputs(
sub_request_id,
@@ -193,35 +205,19 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
trace_headers=trace_headers,
)
else:
tok_params = request.build_tok_params(self.model_config)
tokenization_kwargs = tok_params.get_encode_kwargs()
reasoning_ended = (
reasoning_parser.is_reasoning_end(prompt_token_ids or []) if reasoning_parser else None
)
engine_request = self.input_processor.process_inputs(
sub_request_id,
generator = self.engine_client.generate(
engine_prompt,
sampling_params,
lora_request=lora_request,
tokenization_kwargs=tokenization_kwargs,
trace_headers=trace_headers,
priority=request.priority,
data_parallel_rank=data_parallel_rank,
)
reasoning_ended = None
if reasoning_parser:
reasoning_ended = reasoning_parser.is_reasoning_end(
engine_request.prompt_token_ids or [] # type: ignore[attr-defined]
)
engine_request.reasoning_ended = reasoning_ended
generator = self.engine_client.generate(
engine_request,
sampling_params,
sub_request_id,
lora_request=lora_request,
trace_headers=trace_headers,
priority=request.priority,
prompt_text=prompt_text,
tokenization_kwargs=tokenization_kwargs,
data_parallel_rank=data_parallel_rank,
reasoning_ended=reasoning_ended,
)
generators.append(generator)
+8 -1
View File
@@ -1,4 +1,5 @@
import asyncio
import gc
import multiprocessing as mp
import random
import time
@@ -512,7 +513,8 @@ async def orchestrate(config: OrchestratorConfig):
if is_vlm:
vlm_cache = build_vlm_image_cache(train_rollouts, processor)
logger.info(
f"VLM timing: extract={vlm_cache.extract_time:.2f}s, preprocess={vlm_cache.preprocess_time:.2f}s"
f"VLM timing: extract={vlm_cache.extract_time:.2f}s, preprocess={vlm_cache.preprocess_time:.2f}s "
f"({vlm_cache.num_unique_images} unique images from {vlm_cache.num_unique_examples} examples)"
)
else:
vlm_cache = None
@@ -788,6 +790,11 @@ async def orchestrate(config: OrchestratorConfig):
progress.step += 1
is_first_step = False
# Free large per-step objects to prevent memory accumulation
del train_rollouts, train_examples, training_batch, vlm_cache
del results_df, metrics_df, val_results_df
gc.collect()
event_loop_lag_monitor.reset()
# Send heartbeat if configured
+3 -3
View File
@@ -282,9 +282,9 @@ class Scheduler:
for task, info in list(self.inflight_requests.items())
if info.group_id is None or info.group_id not in stale_group_ids
]
removed = 0
for gid in stale_group_ids:
removed += await self.drop_group(gid)
counts = await asyncio.gather(*(self.drop_group(gid) for gid in stale_group_ids))
removed = sum(counts)
for task in tasks_to_increment:
info = self.inflight_requests.get(task)
if info is None:
+243 -79
View File
@@ -1,7 +1,9 @@
import base64
import time
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
import torch
import verifiers as vf
from PIL import Image
@@ -72,13 +74,7 @@ def interleave_rollout(
# this field should be guaranteed because we set temperature in get_sampling_args
temperature = output["sampling_args"]["temperature"]
def get_images(step_idx: int) -> tuple[list | None, list | None]:
if vlm_cache is None:
return None, None
key = output["example_id"] if cache_key is None else cache_key
return vlm_cache.get_for_step(key, step_idx)
def make_sample(step: vf.TrajectoryStep, step_idx: int) -> TrainingSample:
def make_sample(step: vf.TrajectoryStep) -> TrainingSample:
"""Create a new TrainingSample from a trajectory step."""
tokens = step["tokens"]
assert tokens is not None
@@ -87,7 +83,6 @@ def interleave_rollout(
else:
completion_mask = [bool(i) for i in tokens["completion_mask"]]
completion_ids = list(tokens["completion_ids"])
pixel_values, image_grid_thw = get_images(step_idx)
routed_experts = _align_routed_experts(
tokens.get("routed_experts"),
@@ -103,12 +98,10 @@ def interleave_rollout(
completion_temperatures=[temperature] * len(completion_ids),
teacher_logprobs=None,
advantage=None,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
routed_experts=routed_experts,
)
def extend_sample(sample: TrainingSample, step: vf.TrajectoryStep, prefix_len: int, step_idx: int) -> None:
def extend_sample(sample: TrainingSample, step: vf.TrajectoryStep, prefix_len: int) -> None:
"""Extend an existing sample with a new trajectory step (extension property holds)."""
tokens = step["tokens"]
assert tokens is not None
@@ -130,11 +123,6 @@ def interleave_rollout(
sample.completion_logprobs.extend(tokens["completion_logprobs"])
sample.completion_temperatures.extend([temperature] * len(completion_ids))
# Update cumulative images to include any new images from this step
pixel_values, image_grid_thw = get_images(step_idx)
sample.pixel_values = pixel_values
sample.image_grid_thw = image_grid_thw
if tokens.get("routed_experts") is not None and sample.routed_experts is not None:
step_routed = tokens["routed_experts"]
# The previous step's last routing entry was zero-padded by _align_routed_experts
@@ -147,13 +135,12 @@ def interleave_rollout(
expected_len = len(sample.prompt_ids) + len(sample.completion_ids)
sample.routed_experts = _align_routed_experts(sample.routed_experts, expected_len)
# Track multiple active (prefix, sample) pairs to handle interleaved agents
# Each entry is [prefix_tokens, sample] where prefix_tokens is the accumulated token sequence
# Track [prefix_tokens, sample, last_step_idx] per active sample
active_samples: list[list] = []
first_tokens = trajectory[0]["tokens"]
first_prefix = first_tokens["prompt_ids"] + first_tokens["completion_ids"]
active_samples.append([first_prefix, make_sample(trajectory[0], step_idx=0)])
active_samples.append([first_prefix, make_sample(trajectory[0]), 0])
for step_idx, step in enumerate(trajectory[1:], start=1):
tokens = step["tokens"]
@@ -161,17 +148,17 @@ def interleave_rollout(
# Check if this step extends ANY active prefix
matched_idx = None
for idx, (prefix_tokens, _) in enumerate(active_samples):
for idx, (prefix_tokens, _, _) in enumerate(active_samples):
if step_prompt_ids[: len(prefix_tokens)] == prefix_tokens:
matched_idx = idx
break
if matched_idx is not None:
# Extension holds - merge into matched sample
prefix_tokens, sample = active_samples[matched_idx]
extend_sample(sample, step, len(prefix_tokens), step_idx=step_idx)
# Update prefix for this sample
prefix_tokens, sample, _ = active_samples[matched_idx]
extend_sample(sample, step, len(prefix_tokens))
active_samples[matched_idx][0] = tokens["prompt_ids"] + tokens["completion_ids"]
active_samples[matched_idx][2] = step_idx
else:
# No prefix matches - start a new sample
logger.debug(
@@ -179,9 +166,18 @@ def interleave_rollout(
f"Starting new sample (active_prefixes={len(active_samples)}, step_prompt_len={len(step_prompt_ids)})."
)
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
active_samples.append([new_prefix, make_sample(step, step_idx=step_idx)])
active_samples.append([new_prefix, make_sample(step), step_idx])
return [sample for _, sample in active_samples]
# Attach images once per sample using only the last merged step
if vlm_cache is not None:
key = output["example_id"] if cache_key is None else cache_key
for _, sample, last_step_idx in active_samples:
pv, shape, grids = vlm_cache.get_for_step(key, last_step_idx)
sample.pixel_values = pv
sample.pixel_values_shape = shape
sample.image_grid_thw = grids
return [sample for _, sample, _ in active_samples]
# =============================================================================
@@ -209,15 +205,61 @@ def _extract_images_from_messages(messages: list) -> list[tuple[Image.Image, str
return images
def _collect_b64_keys_from_messages(messages: list) -> list[str]:
"""Extract base64 keys from OpenAI-style chat messages without decoding."""
keys = []
if not messages or not isinstance(messages, list):
return keys
for msg in messages:
content = msg.get("content", [])
if isinstance(content, list):
for item in content:
if item.get("type") == "image_url":
url = item.get("image_url", {}).get("url", "")
if url.startswith("data:image"):
keys.append(url.split(",", 1)[1])
return keys
def _decode_b64_image(b64_data: str) -> Image.Image:
"""Decode a single base64 string into a PIL Image."""
return Image.open(BytesIO(base64.b64decode(b64_data)))
_PARALLEL_DECODE_THRESHOLD = 4
_IMAGE_STRIPPED_PLACEHOLDER = "[preprocessed image]"
def strip_base64_images(examples: list[tuple[int, vf.RolloutOutput]]) -> None:
"""Strip base64 image data from rollout prompts to free memory.
The images have been decoded and indexed; the original data is no longer needed.
"""
for _, output in examples:
for step in output.get("trajectory", []):
prompt = step.get("prompt")
if not prompt or not isinstance(prompt, list):
continue
for msg in prompt:
content = msg.get("content", [])
if isinstance(content, list):
for item in content:
if item.get("type") == "image_url":
url = item.get("image_url", {}).get("url", "")
if url.startswith("data:image"):
item["image_url"]["url"] = _IMAGE_STRIPPED_PLACEHOLDER
def _extract_images_from_examples(
examples: list[tuple[int, vf.RolloutOutput]],
) -> tuple[list[Image.Image], dict[int, list[list[int]]]]:
"""
Extract images from all trajectory steps of each example.
Parses OpenAI-style message content looking for image_url items with base64 data URLs.
Images are deduplicated across the batch by their base64 content. Each step records
the indices of its images into the deduplicated all_images list.
Two-pass approach: first collects unique base64 keys (fast, string-only),
then decodes unique images in parallel via ThreadPoolExecutor.
Args:
examples: List of (cache_key, output) tuples where output contains a "trajectory"
@@ -229,8 +271,9 @@ def _extract_images_from_examples(
- step_image_indices_per_example: dict mapping cache_key to per-step lists of
indices into all_images (e.g., [[0], [0, 1], [1]] for the decreasing-images case)
"""
all_images: list[Image.Image] = []
image_registry: dict[str, int] = {} # b64_key -> index in all_images
# Pass 1: collect unique b64 keys and build step indices
unique_keys: list[str] = []
key_to_index: dict[str, int] = {}
step_image_indices_per_example: dict[int, list[list[int]]] = {}
for eid, output in examples:
@@ -242,51 +285,123 @@ def _extract_images_from_examples(
step_image_indices = []
for step in trajectory:
prompt = step.get("prompt")
step_image_pairs = _extract_images_from_messages(prompt)
b64_keys = _collect_b64_keys_from_messages(prompt)
indices = []
for img, key in step_image_pairs:
if key not in image_registry:
image_registry[key] = len(all_images)
all_images.append(img)
indices.append(image_registry[key])
for key in b64_keys:
if key not in key_to_index:
key_to_index[key] = len(unique_keys)
unique_keys.append(key)
indices.append(key_to_index[key])
step_image_indices.append(indices)
step_image_indices_per_example[eid] = step_image_indices
# Pass 2: decode unique images (parallel when worthwhile)
if len(unique_keys) > _PARALLEL_DECODE_THRESHOLD:
with ThreadPoolExecutor(max_workers=min(len(unique_keys), 16)) as pool:
all_images = list(pool.map(_decode_b64_image, unique_keys))
else:
all_images = [_decode_b64_image(k) for k in unique_keys]
del unique_keys, key_to_index
strip_base64_images(examples)
return all_images, step_image_indices_per_example
_DEFAULT_IMAGE_CHUNK_SIZE = 32
class _ImageStore:
"""Holds per-unique-image data, assembled lazily on demand.
Instead of duplicating pixel bytes for every step that references an image,
we store each image's bytes once and assemble the concatenation at retrieval time.
"""
def __init__(
self,
image_bytes: list[bytes],
image_num_patches: list[int],
patch_dim: int,
image_grids: list[list[int]],
):
self.image_bytes = image_bytes
self.image_num_patches = image_num_patches
self.patch_dim = patch_dim
self.image_grids = image_grids
self._cache: dict[tuple[int, ...], tuple[bytes, list[int], list[list[int]]]] = {}
def assemble(self, indices: list[int]) -> tuple[bytes, list[int], list[list[int]]]:
"""Assemble pixel bytes, shape, and grids for a set of image indices.
Results are cached by index tuple — multi-turn rollouts with the same
cumulative image set (common across rollouts of the same example) hit
the cache and skip the join.
"""
cache_key = tuple(indices)
cached = self._cache.get(cache_key)
if cached is not None:
return cached
total_patches = sum(self.image_num_patches[i] for i in indices)
pixel_bytes = b"".join(self.image_bytes[i] for i in indices)
shape = [total_patches, self.patch_dim]
grids = [self.image_grids[i] for i in indices]
result = (pixel_bytes, shape, grids)
self._cache[cache_key] = result
return result
def _preprocess_images_batched(
images: list[Image.Image],
step_image_indices_per_example: dict[int, list[list[int]]],
processor,
) -> dict[int, list[tuple[list | None, list | None]]]:
chunk_size: int = _DEFAULT_IMAGE_CHUNK_SIZE,
) -> tuple["_ImageStore | None", dict[int, list[list[int]]]]:
"""
Preprocess all images in a single batched call, then distribute results per step.
Preprocess all images in chunked batches, returning an _ImageStore and step indices.
Args:
images: Deduplicated flat list of all PIL images
step_image_indices_per_example: Dict mapping cache_key to per-step lists of
indices into images
processor: HuggingFace processor with image_processor attribute
Images are processed in chunks to avoid OOM on large batches. Per-image bytes are
stored once in the _ImageStore and assembled lazily at retrieval time.
Returns:
Dict mapping cache_key to list of (pixel_values, image_grid_thw) per step.
Tuple of (_ImageStore or None, step_image_indices_per_example).
The store is None when there are no images or no processor.
"""
if not images or processor is None:
return {
eid: [(None, None)] * max(len(step_indices), 1)
for eid, step_indices in step_image_indices_per_example.items()
}
image_sizes = [(img.width, img.height) for img in images]
processed = processor.image_processor(images=images, return_tensors="pt")
all_pixel_values = processed["pixel_values"]
all_grid_thw = processed["image_grid_thw"]
return None, step_image_indices_per_example
logger = get_logger()
image_sizes = [(img.width, img.height) for img in images]
# Process images in chunks to avoid OOM, parallelized across threads
# (PIL/numpy release the GIL so threads give real concurrency here)
chunks = [images[i : i + chunk_size] for i in range(0, len(images), chunk_size)]
def _process_chunk(chunk: list[Image.Image]) -> tuple[torch.Tensor, torch.Tensor]:
processed = processor.image_processor(images=chunk, return_tensors="pt")
return processed["pixel_values"], processed["image_grid_thw"]
if len(chunks) > 1:
with ThreadPoolExecutor(max_workers=min(len(chunks), 8)) as pool:
results = list(pool.map(_process_chunk, chunks))
else:
results = [_process_chunk(chunks[0])]
# Free PIL images now that preprocessing is done
del chunks
images.clear()
all_pixel_values_list = [r[0] for r in results]
all_grid_thw_list = [r[1] for r in results]
all_pixel_values = torch.cat(all_pixel_values_list, dim=0)
all_grid_thw = torch.cat(all_grid_thw_list, dim=0)
del all_pixel_values_list, all_grid_thw_list, results
logger.debug(
f"VLM image processing: {len(images)} images, sizes={image_sizes}, "
f"VLM image processing: {len(image_sizes)} images, sizes={image_sizes}, "
f"pixel_values={all_pixel_values.shape}, grid_thw={all_grid_thw.tolist()}"
)
@@ -295,24 +410,27 @@ def _preprocess_images_batched(
for g in all_grid_thw:
patch_starts.append(patch_starts[-1] + int(g[0] * g[1] * g[2]))
result = {}
for eid, step_indices_list in step_image_indices_per_example.items():
if not step_indices_list:
result[eid] = [(None, None)]
continue
patch_dim = all_pixel_values.shape[1]
per_step = []
for indices in step_indices_list:
if not indices:
per_step.append((None, None))
else:
grids = all_grid_thw[indices]
patches = sum([all_pixel_values[patch_starts[i] : patch_starts[i + 1]].tolist() for i in indices], [])
per_step.append((patches, grids.tolist()))
# Convert to bytes per-image and free the tensor immediately after
image_bytes_list: list[bytes] = []
image_num_patches_list: list[int] = []
image_grids_list: list[list[int]] = []
for i in range(len(image_sizes)):
img_slice = all_pixel_values[patch_starts[i] : patch_starts[i + 1]]
image_bytes_list.append(img_slice.numpy().tobytes())
image_num_patches_list.append(img_slice.shape[0])
image_grids_list.append(all_grid_thw[i].tolist())
del all_pixel_values, all_grid_thw
result[eid] = per_step
store = _ImageStore(
image_bytes=image_bytes_list,
image_num_patches=image_num_patches_list,
patch_dim=patch_dim,
image_grids=image_grids_list,
)
return result
return store, step_image_indices_per_example
class VLMImageCache:
@@ -320,28 +438,71 @@ class VLMImageCache:
def __init__(
self,
cache: dict[int, list[tuple[list | None, list | None]]],
cache: dict[int, list[tuple[bytes | None, list[int] | None, list[list[int]] | None]]],
num_unique_examples: int,
extract_time: float,
preprocess_time: float,
):
self._store: _ImageStore | None = None
self._step_indices: dict[int, list[list[int]]] | None = None
self.cache = cache
self.num_unique_examples = num_unique_examples
self.num_unique_images = 0
self.extract_time = extract_time
self.preprocess_time = preprocess_time
def get_for_step(self, cache_key: int, step_idx: int) -> tuple[list | None, list | None]:
@classmethod
def from_store(
cls,
store: _ImageStore | None,
step_indices: dict[int, list[list[int]]],
num_unique_examples: int,
num_unique_images: int,
extract_time: float,
preprocess_time: float,
) -> "VLMImageCache":
"""Create a store-backed cache that assembles bytes lazily."""
obj = cls.__new__(cls)
obj._store = store
obj._step_indices = step_indices
obj.cache = {}
obj.num_unique_examples = num_unique_examples
obj.num_unique_images = num_unique_images
obj.extract_time = extract_time
obj.preprocess_time = preprocess_time
return obj
def _assemble(self, indices: list[int]) -> tuple[bytes | None, list[int] | None, list[list[int]] | None]:
if not indices:
return (None, None, None)
return self._store.assemble(indices)
def get_for_step(
self, cache_key: int, step_idx: int
) -> tuple[bytes | None, list[int] | None, list[list[int]] | None]:
"""Get cumulative images up to and including the given step."""
if self._store is not None:
steps = self._step_indices.get(cache_key, [])
if not steps or step_idx >= len(steps):
return (None, None, None)
return self._assemble(steps[step_idx])
steps = self.cache.get(cache_key, [])
if not steps or step_idx >= len(steps):
return (None, None)
return (None, None, None)
return steps[step_idx]
def get_all(self, cache_key: int) -> tuple[list | None, list | None]:
def get_all(self, cache_key: int) -> tuple[bytes | None, list[int] | None, list[list[int]] | None]:
"""Get all images for the cache key (last step's cumulative images)."""
if self._store is not None:
steps = self._step_indices.get(cache_key, [])
if not steps:
return (None, None, None)
return self._assemble(steps[-1])
steps = self.cache.get(cache_key, [])
if not steps:
return (None, None)
return (None, None, None)
return steps[-1]
@@ -354,19 +515,22 @@ def build_vlm_image_cache(rollouts: list[vf.RolloutOutput], processor) -> VLMIma
examples = [(idx, rollout) for idx, rollout in enumerate(rollouts)]
unique_example_ids = {rollout["example_id"] for rollout in rollouts}
# Extract images
# Extract images (also strips base64 data from rollout prompts to free memory)
extract_start = time.perf_counter()
all_images, images_per_example = _extract_images_from_examples(examples)
num_unique_images = len(all_images)
extract_time = time.perf_counter() - extract_start
# Preprocess images
# Preprocess images (clears PIL image list when done)
preprocess_start = time.perf_counter()
cache = _preprocess_images_batched(all_images, images_per_example, processor)
store, step_indices = _preprocess_images_batched(all_images, images_per_example, processor)
preprocess_time = time.perf_counter() - preprocess_start
return VLMImageCache(
cache=cache,
return VLMImageCache.from_store(
store=store,
step_indices=step_indices,
num_unique_examples=len(unique_example_ids),
num_unique_images=num_unique_images,
extract_time=extract_time,
preprocess_time=preprocess_time,
)
@@ -58,7 +58,7 @@ else
if [ -z "$INFER_URLS" ]; then
INFER_URLS="http://$host:8000/v1"
else
INFER_URLS="$INFER_URLS,http://$host:8000/v1"
INFER_URLS="$INFER_URLS http://$host:8000/v1"
fi
done
fi
@@ -128,10 +128,10 @@ else
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
if [ "$TRAIN_NODE_RANK" -eq 0 ]; then
uv run orchestrator \
@ $CONFIG_DIR/orchestrator.toml \
--weight_broadcast.host $MASTER_ADDR \
--client.base-url $INFER_URLS \
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --client.base-url $INFER_URLS"
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $OUTPUT_DIR/slurm/latest_orchestrator.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_orchestrator.log &
fi
+38 -18
View File
@@ -65,6 +65,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
routed_experts=routed_experts,
# Multimodal fields (Qwen3-VL) - passed through without modification
pixel_values=training_example.pixel_values,
pixel_values_shape=training_example.pixel_values_shape,
image_grid_thw=training_example.image_grid_thw,
)
@@ -162,6 +163,23 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
return micro_batch
def _make_dummy_batch(source: MicroBatch) -> MicroBatch:
"""Create a zero-loss dummy batch from an existing batch, preserving its modality."""
dummy = copy.deepcopy(source)
dummy.advantages = [0.0] * len(dummy.input_ids)
dummy.loss_mask = [False] * len(dummy.input_ids)
return dummy
def _pad_group_for_distribution(group: list[MicroBatch], num_train_workers: int) -> list[MicroBatch]:
"""Pad a group of micro batches so its length is divisible by num_train_workers."""
num_padding = -len(group) % num_train_workers
if num_padding > 0 and len(group) > 0:
dummy = _make_dummy_batch(group[0])
group.extend([dummy] * num_padding)
return group
def prepare_batch(
rollouts: list[TrainingSample],
seq_len: int,
@@ -173,32 +191,34 @@ def prepare_batch(
"""
Prepare a batch of problems for each GPU. Each batch is a list of micro batches.
Each micro batch is shape [1, seq_len], the number of samples is not fixed per micro batch.
FSDP requires all ranks to execute the same operations at each step. If one rank
processes a multimodal batch (triggering the vision encoder) while another processes
a text-only batch, the all-gather will hang. We separate micro batches by modality
and distribute them so that at each step index, all ranks see the same modality.
"""
all_samples = [(idx, prepare_sample(rollout, seq_len)) for idx, rollout in zip(idxs, rollouts)]
micro_batches = packed_samples_into_micro_bs(all_samples, seq_len, num_loras)
micro_batches = [pad_micro_batch(micro_batch, pad_to_multiple_of) for micro_batch in micro_batches]
num_padding_batch = -len(micro_batches) % num_train_workers
# Separate by modality so each step index has uniform modality across all ranks
mm_batches = [b for b in micro_batches if _is_multimodal_sample(b)]
text_batches = [b for b in micro_batches if not _is_multimodal_sample(b)]
# because of fsdp we need to make sure that each data ran has the same number of micro batches otherwise training will hang.
# We create fake micro batches to fill the gap with real data but zero advantages, they would not contribute to the loss.
if num_train_workers > 1 and num_padding_batch > 0:
padded_batch = copy.deepcopy(micro_batches[0])
padded_batch.advantages = [0.0] * len(padded_batch.input_ids)
padded_batch.loss_mask = [False] * len(padded_batch.input_ids)
micro_batches.extend([padded_batch for _ in range(num_padding_batch)])
# Pad each group independently so its count is divisible by num_train_workers
mm_batches = _pad_group_for_distribution(mm_batches, num_train_workers)
text_batches = _pad_group_for_distribution(text_batches, num_train_workers)
assert len(micro_batches) % num_train_workers == 0, (
"Number of micro batches is not divisible by number of data ranks"
)
# Combine: all multimodal first, then all text-only. Since each group's length is
# divisible by num_train_workers, the modality boundary aligns with distribution rows.
ordered = mm_batches + text_batches
per_gpu_micro_batches = len(micro_batches) // num_train_workers
batches_per_gpu = []
for _ in range(num_train_workers):
batches = []
for _ in range(per_gpu_micro_batches):
batches.append(micro_batches.pop(0))
batches_per_gpu.append(batches)
assert len(ordered) % num_train_workers == 0, "Number of micro batches is not divisible by number of data ranks"
# Distribute in strided order so each step index has the same modality across ranks
batches_per_gpu: list[list[MicroBatch]] = [[] for _ in range(num_train_workers)]
for i, batch in enumerate(ordered):
batches_per_gpu[i % num_train_workers].append(batch)
return batches_per_gpu
+61
View File
@@ -42,6 +42,63 @@ from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.vlm import is_vlm_model
def _patch_qwen3_5_moe_conversion_mapping():
"""Fix Qwen3.5 MoE conversion mapping incorrectly applying qwen2_moe expert weight splitting.
Qwen3.5 MoE stores expert weights as fused 3D tensors natively in the checkpoint
(e.g. experts.gate_up_proj [num_experts, 2*intermediate, hidden]). The upstream mapping
incorrectly maps qwen3_5_moe → qwen2_moe, which assumes per-expert 2D checkpoint weights,
causing revert_weight_conversion to produce wrong shapes during weight broadcasting.
Remove once the pinned transformers commit fixes this.
"""
from transformers.conversion_mapping import (
get_checkpoint_conversion_mapping,
register_checkpoint_conversion_mapping,
)
# qwen3_5_moe_text: keep only the qwen3_5_text renaming, remove qwen2_moe expert conversion
qwen3_5_text_mapping = get_checkpoint_conversion_mapping("qwen3_5_text")
if qwen3_5_text_mapping is not None:
register_checkpoint_conversion_mapping("qwen3_5_moe_text", qwen3_5_text_mapping, overwrite=True)
# qwen3_5_moe: remove the qwen2_moe fallback entirely
register_checkpoint_conversion_mapping("qwen3_5_moe", [], overwrite=True)
def _patch_qwen3_5_text_position_ids():
"""Fix Qwen3.5 passing 3D MRoPE position_ids to decoder layers instead of 2D text_position_ids.
Upstream fix: https://github.com/huggingface/transformers/pull/44399
Remove once the pinned transformers commit includes this fix.
"""
import inspect
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5DecoderLayer, Qwen3_5TextModel
from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeDecoderLayer, Qwen3_5MoeTextModel
for text_model_cls, decoder_layer_cls in [
(Qwen3_5TextModel, Qwen3_5DecoderLayer),
(Qwen3_5MoeTextModel, Qwen3_5MoeDecoderLayer),
]:
source = inspect.getsource(text_model_cls.forward)
if "decoder_layer" in source and "position_ids=text_position_ids" in source.split("decoder_layer")[-1]:
continue # already fixed upstream
_original_forward = decoder_layer_cls.forward
def _make_patched_forward(original):
def _patched_forward(self, hidden_states, position_ids=None, **kwargs):
if position_ids is not None and position_ids.ndim == 3:
position_ids = position_ids[0]
return original(self, hidden_states, position_ids=position_ids, **kwargs)
return _patched_forward
decoder_layer_cls.forward = _make_patched_forward(_original_forward)
# Add filter to the standard logging module for transformers.modeling_utils to supress the
# flash attention dtype warnings since FSDP is used to handle mixed precision.
transformers_modeling_utils_logger = logging.getLogger("transformers.modeling_utils")
@@ -165,6 +222,10 @@ def get_model(
if is_vlm:
logger.info(f"Detected vision-language model: {config.name}")
if "Qwen3.5" in config.name or "qwen3_5" in config.name.lower():
_patch_qwen3_5_text_position_ids()
_patch_qwen3_5_moe_conversion_mapping()
model_config = cast(
PretrainedConfig,
AutoConfig.from_pretrained(
+1 -1
View File
@@ -97,7 +97,7 @@ class PerfCounter:
vocab_size = config.vocab_size
hidden_size = config.hidden_size
intermediate_size = config.intermediate_size
intermediate_size = getattr(config, "intermediate_size", getattr(config, "moe_intermediate_size", 0))
head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
num_attention_heads = config.num_attention_heads
num_hidden_layers = config.num_hidden_layers
+3 -1
View File
@@ -194,7 +194,9 @@ class DataLoader:
temperatures=torch.tensor(micro_batch.temperatures, dtype=torch.float).unsqueeze(0),
lora_num_tokens=torch.tensor(micro_batch.lora_num_tokens, dtype=torch.int32),
# Multimodal fields - no batch dimension for these as they are variable-sized
pixel_values=torch.tensor(micro_batch.pixel_values, dtype=torch.float)
pixel_values=torch.frombuffer(bytearray(micro_batch.pixel_values), dtype=torch.float32).reshape(
micro_batch.pixel_values_shape
)
if micro_batch.pixel_values is not None
else None,
image_grid_thw=torch.tensor(micro_batch.image_grid_thw, dtype=torch.long)
+35 -45
View File
@@ -105,67 +105,57 @@ def _safe_mean(values: Tensor, mask: Tensor) -> Tensor:
def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossOutputs:
"""Masked importance sampling with KL against the inference policy, and optional masking strategies."""
"""
We implement IPO (INTELLECT Policy Optimization) loss, which combines:
- DPPO-Binary TV Loss (https://arxiv.org/pdf/2602.04879)
- Kimi-K2.5 KL Loss (https://arxiv.org/pdf/2602.02276)
Unlike the DPPO-Bin TV mask, we mask independently of the advantage sign.
This is, because in Async RL, we do not take multiple steps on the same
data, and so policy updates are not well-predicted by the advantage sign.
This shift is similar to the shift from GRPO -> CISPO, but with the trust
region being approximated by the probability difference instead of ratio.
"""
trainer_logprobs = inputs.trainer_logprobs
inference_logprobs = inputs.inference_logprobs
teacher_logprobs = inputs.teacher_logprobs
advantages = inputs.advantages
loss_mask = inputs.loss_mask
log_importance_ratio = trainer_logprobs - inference_logprobs
teacher_kl = teacher_logprobs - trainer_logprobs if teacher_logprobs is not None else None
trainer_probs = torch.exp(trainer_logprobs)
inference_probs = torch.exp(inference_logprobs)
probs_diff = trainer_probs - inference_probs
ipo_invalid_mask_high = probs_diff > loss_config.ipo_mask_high
ipo_invalid_mask_low = probs_diff < -loss_config.ipo_mask_low
ipo_invalid_mask = ipo_invalid_mask_high | ipo_invalid_mask_low
token_importance_ratio = torch.exp(log_importance_ratio)
geo_seq_ratio = torch.exp(_safe_mean(log_importance_ratio, loss_mask))
token_mismatch_kl = token_importance_ratio - log_importance_ratio - 1
seq_log_importance_ratio = torch.clamp(log_importance_ratio[loss_mask].sum().detach(), max=10.0)
seq_importance_ratio = torch.clamp(torch.exp(seq_log_importance_ratio), max=loss_config.sequence_clip_high)
seq_min_ratio = torch.where(loss_mask, token_importance_ratio, torch.inf).min()
seq_max_ratio = torch.where(loss_mask, token_importance_ratio, -torch.inf).max()
seq_mask_low = seq_min_ratio < loss_config.sequence_mask_low
seq_mask_high = seq_max_ratio > loss_config.sequence_mask_high
token_mask_low_mask = token_importance_ratio < loss_config.token_mask_low
token_mask_high_mask = token_importance_ratio > loss_config.token_mask_high
geo_mask_low_mask = geo_seq_ratio < loss_config.geo_mask_low
geo_mask_high_mask = geo_seq_ratio > loss_config.geo_mask_high
is_masked = (
token_mask_low_mask
| token_mask_high_mask
| geo_mask_low_mask
| geo_mask_high_mask
| seq_mask_low
| seq_mask_high
)
is_masked = ipo_invalid_mask
is_masked_low = ipo_invalid_mask_low
is_masked_high = ipo_invalid_mask_high
keep_mask = loss_mask & ~is_masked
importance_ratio = seq_importance_ratio if loss_config.ratio_type == "sequence" else token_importance_ratio
log_importance_ratio = trainer_logprobs - inference_logprobs
importance_ratio = torch.exp(log_importance_ratio)
mismatch_kl = importance_ratio - log_importance_ratio - 1
advantages = loss_config.adv_tau * advantages
if teacher_logprobs is not None:
teacher_kl = teacher_logprobs - trainer_logprobs
advantages = advantages + loss_config.teacher_tau * teacher_kl.detach()
coeff = importance_ratio * (advantages - loss_config.kl_tau * log_importance_ratio)
loss = -(coeff.detach() * trainer_logprobs)[keep_mask].sum()
else:
teacher_kl = None
if loss_config.ratio_type == "sequence":
loss = loss / torch.clamp_min(loss_mask.sum(), 1)
pg_loss = keep_mask * advantages * importance_ratio
kl_loss = loss_mask * log_importance_ratio**2
loss = (-pg_loss + loss_config.kl_tau * kl_loss).sum()
metrics = {
"mismatch_kl": _safe_mean(token_mismatch_kl, loss_mask),
"masked_mismatch_kl": _safe_mean(token_mismatch_kl, loss_mask & is_masked),
"unmasked_mismatch_kl": _safe_mean(token_mismatch_kl, keep_mask),
"is_masked": is_masked[loss_mask].float(),
"is_masked_low": token_mask_low_mask[loss_mask].float(),
"is_masked_high": token_mask_high_mask[loss_mask].float(),
"sequence_masked_low": seq_mask_low.float(),
"sequence_masked_high": seq_mask_high.float(),
"geo_masked_low": geo_mask_low_mask.float(),
"geo_masked_high": geo_mask_high_mask.float(),
"geo_seq_ratio": geo_seq_ratio,
"mismatch_kl": _safe_mean(mismatch_kl, loss_mask), # all trainable tokens
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
"is_masked": _safe_mean(is_masked, loss_mask),
"is_masked_low": _safe_mean(is_masked_low, loss_mask),
"is_masked_high": _safe_mean(is_masked_high, loss_mask),
}
if teacher_kl is not None:
metrics["teacher_kl"] = _safe_mean(teacher_kl, loss_mask)
+1 -1
View File
@@ -294,7 +294,7 @@ def train(config: TrainerConfig):
seq_len = micro_batches[0]["input_ids"].shape[1]
# Normalize by the local number of unmasked tokens in the batch (per-batch length normalization)
if isinstance(config.loss, DefaultLossConfig) and config.loss.ratio_type == "token":
if isinstance(config.loss, DefaultLossConfig):
loss_scale = sum(micro_batch["loss_mask"].sum().item() for micro_batch in micro_batches)
else:
loss_scale = batch_size
+6 -6
View File
@@ -15,9 +15,9 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
advantage: float | None = None
reward: float | None = None
# Multimodal fields (Qwen3-VL)
# pixel_values: flattened image patches [num_patches, patch_dim] where patch_dim=1176 for Qwen3-VL
pixel_values: list[list[float]] | None = None
# Multimodal fields (Qwen3-VL) — pixel_values stored as raw float32 bytes for efficient serialization
pixel_values: bytes | None = None
pixel_values_shape: list[int] | None = None # [num_patches, patch_dim]
# image_grid_thw: grid dimensions [num_images, 3] where each entry is [temporal, height, width]
image_grid_thw: list[list[int]] | None = None
@@ -46,8 +46,8 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
lora_num_tokens: list[int] | None = None
routed_experts: list[list[list[int]]] | None = None
# Multimodal fields (Qwen3-VL)
# pixel_values: flattened image patches [num_patches, patch_dim] where patch_dim=1176 for Qwen3-VL
pixel_values: list[list[float]] | None = None
# Multimodal fields (Qwen3-VL) — pixel_values stored as raw float32 bytes for efficient serialization
pixel_values: bytes | None = None
pixel_values_shape: list[int] | None = None # [num_patches, patch_dim]
# image_grid_thw: grid dimensions [num_images, 3] where each entry is [temporal, height, width]
image_grid_thw: list[list[int]] | None = None
+1 -1
View File
@@ -154,7 +154,7 @@ def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
base_url=base_url,
headers=headers,
limits=httpx.Limits(max_connections=1, max_keepalive_connections=0),
timeout=httpx.Timeout(client_config.timeout),
timeout=httpx.Timeout(None),
)
return [_setup_admin_client(base_url) for base_url in client_config.base_url]
+1
View File
@@ -9,6 +9,7 @@ import fnmatch
# Add new patterns here as they are tested and supported
SUPPORTED_VLM_PATTERNS = [
"Qwen/Qwen3-VL*",
"Qwen/Qwen3.5*",
]
+2 -2
View File
@@ -212,8 +212,8 @@ def start_orchestrator(
"--wandb.name",
f"{wandb_name}-{proc_name}",
]
for base_url in INFERENCE_BASE_URLS:
cmd.extend(["--client.base-url", base_url])
cmd.append("--client.base-url")
cmd.extend(INFERENCE_BASE_URLS)
with open(orch_log_dir / "orchestrator.stdout", "w") as f:
proc = subprocess.Popen(
+219 -49
View File
@@ -2,6 +2,7 @@ import base64
from io import BytesIO
from unittest.mock import MagicMock
import numpy as np
import pytest
import verifiers as vf
from PIL import Image
@@ -11,11 +12,23 @@ from prime_rl.orchestrator.trajectories import (
_align_routed_experts,
_extract_images_from_examples,
_extract_images_from_messages,
_ImageStore,
build_vlm_image_cache,
interleave_rollout,
)
def _pixels(data: list[list[float]]) -> tuple[bytes, list[int]]:
"""Convert pixel values list to (bytes, shape) for test cache data."""
arr = np.array(data, dtype=np.float32)
return arr.tobytes(), list(arr.shape)
def _decode_pixels(pixel_bytes: bytes, shape: list[int]) -> list[list[float]]:
"""Decode raw pixel bytes back to nested list for assertions."""
return np.frombuffer(pixel_bytes, dtype=np.float32).reshape(shape).tolist()
@pytest.fixture
def single_step_trajectory_output():
output = vf.RolloutOutput(
@@ -921,60 +934,63 @@ def test_extract_images_from_examples_step_with_fewer_images_than_prior_steps():
def test_vlm_image_cache_get_for_step():
cache_data = {
1: [
([[1.0, 2.0]], [[1, 2, 3]]), # Step 0: 1 image
([[1.0, 2.0], [3.0, 4.0]], [[1, 2, 3], [1, 4, 4]]), # Step 1: 2 images cumulative
(*_pixels([[1.0, 2.0]]), [[1, 2, 3]]), # Step 0: 1 image
(*_pixels([[1.0, 2.0], [3.0, 4.0]]), [[1, 2, 3], [1, 4, 4]]), # Step 1: 2 images cumulative
],
}
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
# Step 0 should have 1 image
pv, grid = cache.get_for_step(1, 0)
assert pv == [[1.0, 2.0]]
pv, shape, grid = cache.get_for_step(1, 0)
assert _decode_pixels(pv, shape) == [[1.0, 2.0]]
assert grid == [[1, 2, 3]]
# Step 1 should have 2 images
pv, grid = cache.get_for_step(1, 1)
assert pv == [[1.0, 2.0], [3.0, 4.0]]
pv, shape, grid = cache.get_for_step(1, 1)
assert _decode_pixels(pv, shape) == [[1.0, 2.0], [3.0, 4.0]]
assert grid == [[1, 2, 3], [1, 4, 4]]
def test_vlm_image_cache_get_all():
cache_data = {
1: [
([[1.0]], [[1, 2, 3]]),
([[1.0], [2.0]], [[1, 2, 3], [1, 4, 4]]),
(*_pixels([[1.0]]), [[1, 2, 3]]),
(*_pixels([[1.0], [2.0]]), [[1, 2, 3], [1, 4, 4]]),
],
}
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
# get_all should return the last step's data
pv, grid = cache.get_all(1)
assert pv == [[1.0], [2.0]]
pv, shape, grid = cache.get_all(1)
assert _decode_pixels(pv, shape) == [[1.0], [2.0]]
assert grid == [[1, 2, 3], [1, 4, 4]]
def test_vlm_image_cache_step_out_of_range():
cache_data = {
1: [
([[1.0]], [[1, 2, 3]]),
(*_pixels([[1.0]]), [[1, 2, 3]]),
],
}
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
pv, grid = cache.get_for_step(1, 2)
pv, shape, grid = cache.get_for_step(1, 2)
assert pv is None
assert shape is None
assert grid is None
def test_vlm_image_cache_missing_example():
cache = VLMImageCache({}, num_unique_examples=0, extract_time=0.0, preprocess_time=0.0)
pv, grid = cache.get_for_step(999, 0)
pv, shape, grid = cache.get_for_step(999, 0)
assert pv is None
assert shape is None
assert grid is None
pv, grid = cache.get_all(999)
pv, shape, grid = cache.get_all(999)
assert pv is None
assert shape is None
assert grid is None
@@ -982,8 +998,8 @@ def test_interleave_rollout_with_vlm_cache():
"""Test that interleave_rollout correctly uses per-step images from VLM cache."""
cache_data = {
1: [
([[1.0]], [[1, 2, 3]]), # Step 0
([[1.0], [2.0]], [[1, 2, 3], [1, 4, 4]]), # Step 1
(*_pixels([[1.0]]), [[1, 2, 3]]), # Step 0
(*_pixels([[1.0], [2.0]]), [[1, 2, 3], [1, 4, 4]]), # Step 1
],
}
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
@@ -1046,14 +1062,14 @@ def test_interleave_rollout_with_vlm_cache():
assert rollout.completion_mask == [True, True, False, True, True]
assert rollout.completion_logprobs == [-0.1, -0.2, 0.0, -0.3, -0.4]
# Images: cumulative from last merged step (step 1 has 2 images)
assert rollout.pixel_values == [[1.0], [2.0]]
assert _decode_pixels(rollout.pixel_values, rollout.pixel_values_shape) == [[1.0], [2.0]]
assert rollout.image_grid_thw == [[1, 2, 3], [1, 4, 4]]
def test_interleave_rollout_uses_cache_key_override():
cache_data = {
7: [
([[9.0]], [[1, 2, 3]]),
(*_pixels([[9.0]]), [[1, 2, 3]]),
],
}
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
@@ -1089,7 +1105,7 @@ def test_interleave_rollout_uses_cache_key_override():
assert rollouts is not None
assert len(rollouts) == 1
assert rollouts[0].pixel_values == [[9.0]]
assert _decode_pixels(rollouts[0].pixel_values, rollouts[0].pixel_values_shape) == [[9.0]]
assert rollouts[0].image_grid_thw == [[1, 2, 3]]
@@ -1101,9 +1117,9 @@ def test_interleave_rollout_vlm_image_then_text_turns():
"""
cache_data = {
1: [
([[1.0, 2.0]], [[1, 3, 3]]), # Step 0: 1 image
([[1.0, 2.0]], [[1, 3, 3]]), # Step 1: same 1 image (no new)
([[1.0, 2.0]], [[1, 3, 3]]), # Step 2: same 1 image (no new)
(*_pixels([[1.0, 2.0]]), [[1, 3, 3]]), # Step 0: 1 image
(*_pixels([[1.0, 2.0]]), [[1, 3, 3]]), # Step 1: same 1 image (no new)
(*_pixels([[1.0, 2.0]]), [[1, 3, 3]]), # Step 2: same 1 image (no new)
],
}
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
@@ -1188,7 +1204,7 @@ def test_interleave_rollout_vlm_image_then_text_turns():
assert rollout.completion_ids == [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
assert rollout.completion_mask == [True, True, False, False, True, True, False, False, True, True]
# pixel_values from step 2 (cumulative = same 1 image throughout)
assert rollout.pixel_values == [[1.0, 2.0]]
assert _decode_pixels(rollout.pixel_values, rollout.pixel_values_shape) == [[1.0, 2.0]]
assert rollout.image_grid_thw == [[1, 3, 3]]
@@ -1199,9 +1215,9 @@ def test_interleave_rollout_vlm_new_image_mid_conversation():
"""
cache_data = {
1: [
([[1.0]], [[1, 2, 3]]), # Step 0: 1 image
([[1.0]], [[1, 2, 3]]), # Step 1: still 1 image
([[1.0], [2.0]], [[1, 2, 3], [1, 4, 4]]), # Step 2: 2 images
(*_pixels([[1.0]]), [[1, 2, 3]]), # Step 0: 1 image
(*_pixels([[1.0]]), [[1, 2, 3]]), # Step 1: still 1 image
(*_pixels([[1.0], [2.0]]), [[1, 2, 3], [1, 4, 4]]), # Step 2: 2 images
],
}
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
@@ -1279,7 +1295,7 @@ def test_interleave_rollout_vlm_new_image_mid_conversation():
assert rollout.prompt_ids == [1, 2]
assert rollout.completion_ids == [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# Cumulative images from last merged step (step 2): both images
assert rollout.pixel_values == [[1.0], [2.0]]
assert _decode_pixels(rollout.pixel_values, rollout.pixel_values_shape) == [[1.0], [2.0]]
assert rollout.image_grid_thw == [[1, 2, 3], [1, 4, 4]]
@@ -1291,9 +1307,9 @@ def test_interleave_rollout_vlm_extension_break():
"""
cache_data = {
1: [
([[1.0]], [[1, 2, 3]]), # Step 0: 1 image
([[1.0]], [[1, 2, 3]]), # Step 1: still 1 image
([[1.0], [2.0]], [[1, 2, 3], [1, 4, 4]]), # Step 2: 2 images (new image added)
(*_pixels([[1.0]]), [[1, 2, 3]]), # Step 0: 1 image
(*_pixels([[1.0]]), [[1, 2, 3]]), # Step 1: still 1 image
(*_pixels([[1.0], [2.0]]), [[1, 2, 3], [1, 4, 4]]), # Step 2: 2 images (new image added)
],
}
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
@@ -1373,13 +1389,13 @@ def test_interleave_rollout_vlm_extension_break():
# Sample 1: steps 0-1 merged, images from step 1 (still 1 image)
assert rollouts[0].prompt_ids == [1, 2]
assert rollouts[0].completion_ids == [3, 4, 5, 6, 7, 8]
assert rollouts[0].pixel_values == [[1.0]]
assert _decode_pixels(rollouts[0].pixel_values, rollouts[0].pixel_values_shape) == [[1.0]]
assert rollouts[0].image_grid_thw == [[1, 2, 3]]
# Sample 2: step 2 alone (extension broke), images from step 2 (2 images)
assert rollouts[1].prompt_ids == [100, 101, 102, 103]
assert rollouts[1].completion_ids == [104, 105]
assert rollouts[1].pixel_values == [[1.0], [2.0]]
assert _decode_pixels(rollouts[1].pixel_values, rollouts[1].pixel_values_shape) == [[1.0], [2.0]]
assert rollouts[1].image_grid_thw == [[1, 2, 3], [1, 4, 4]]
@@ -1391,9 +1407,9 @@ def test_interleave_rollout_vlm_image_appears_late():
"""
cache_data = {
1: [
(None, None), # Step 0: no images
(None, None), # Step 1: no images
([[5.0, 6.0]], [[1, 3, 3]]), # Step 2: first image appears
(None, None, None), # Step 0: no images
(None, None, None), # Step 1: no images
(*_pixels([[5.0, 6.0]]), [[1, 3, 3]]), # Step 2: first image appears
],
}
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
@@ -1475,7 +1491,7 @@ def test_interleave_rollout_vlm_image_appears_late():
assert rollout.completion_ids == [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
assert rollout.completion_mask == [True, True, False, False, True, True, False, False, True, True]
# pixel_values from step 2 (the first step with an image)
assert rollout.pixel_values == [[5.0, 6.0]]
assert _decode_pixels(rollout.pixel_values, rollout.pixel_values_shape) == [[5.0, 6.0]]
assert rollout.image_grid_thw == [[1, 3, 3]]
@@ -1570,10 +1586,10 @@ def test_interleave_rollout_vlm_interleaved_agents():
"""
cache_data = {
1: [
([[1.0]], [[1, 2, 2]]), # Step 0: image A
([[1.0]], [[1, 2, 2]]), # Step 1: still image A
([[9.0]], [[1, 5, 5]]), # Step 2: image B (agent2)
([[1.0], [3.0]], [[1, 2, 2], [1, 3, 3]]), # Step 3: images A+C (agent1)
(*_pixels([[1.0]]), [[1, 2, 2]]), # Step 0: image A
(*_pixels([[1.0]]), [[1, 2, 2]]), # Step 1: still image A
(*_pixels([[9.0]]), [[1, 5, 5]]), # Step 2: image B (agent2)
(*_pixels([[1.0], [3.0]]), [[1, 2, 2], [1, 3, 3]]), # Step 3: images A+C (agent1)
],
}
cache = VLMImageCache(cache_data, num_unique_examples=1, extract_time=0.0, preprocess_time=0.0)
@@ -1676,7 +1692,7 @@ def test_interleave_rollout_vlm_interleaved_agents():
assert agent1.prompt_ids == [1, 2]
assert agent1.completion_ids == [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
assert agent1.completion_mask == [True, True, False, False, True, True, False, False, True, True]
assert agent1.pixel_values == [[1.0], [3.0]]
assert _decode_pixels(agent1.pixel_values, agent1.pixel_values_shape) == [[1.0], [3.0]]
assert agent1.image_grid_thw == [[1, 2, 2], [1, 3, 3]]
# Agent2: step 2 alone → images from step 2 (B)
@@ -1684,7 +1700,7 @@ def test_interleave_rollout_vlm_interleaved_agents():
assert agent2.prompt_ids == [100, 101]
assert agent2.completion_ids == [102, 103]
assert agent2.completion_mask == [True, True]
assert agent2.pixel_values == [[9.0]]
assert _decode_pixels(agent2.pixel_values, agent2.pixel_values_shape) == [[9.0]]
assert agent2.image_grid_thw == [[1, 5, 5]]
@@ -1763,16 +1779,16 @@ def test_build_vlm_image_cache_handles_divergent_rollouts():
assert cache.num_unique_examples == 1
pv, grid = cache.get_for_step(0, 0)
assert pv == [[0.0]]
pv, shape, grid = cache.get_for_step(0, 0)
assert _decode_pixels(pv, shape) == [[0.0]]
assert grid == [[1, 1, 1]]
pv, grid = cache.get_for_step(1, 0)
assert pv == [[1.0]]
pv, shape, grid = cache.get_for_step(1, 0)
assert _decode_pixels(pv, shape) == [[1.0]]
assert grid == [[1, 1, 1]]
pv, grid = cache.get_for_step(1, 1)
assert pv == [[1.0], [2.0]]
pv, shape, grid = cache.get_for_step(1, 1)
assert _decode_pixels(pv, shape) == [[1.0], [2.0]]
assert grid == [[1, 1, 1], [1, 1, 1]]
@@ -1798,8 +1814,9 @@ def test_build_vlm_image_cache_no_images():
cache = build_vlm_image_cache([output], MagicMock())
pv, grid = cache.get_for_step(0, 0)
pv, shape, grid = cache.get_for_step(0, 0)
assert pv is None
assert shape is None
assert grid is None
@@ -1986,3 +2003,156 @@ def test_interleave_rollout_none_routed_experts_stays_none():
rollouts = interleave_rollout(output)
assert rollouts is not None
assert rollouts[0].routed_experts is None
# =============================================================================
# _ImageStore and store-backed VLMImageCache tests
# =============================================================================
def test_image_store_assemble():
"""_ImageStore.assemble joins per-image bytes and computes correct shape/grids."""
# 2 images: image 0 has 3 patches, image 1 has 2 patches, patch_dim=4
patch_dim = 4
img0 = np.arange(3 * patch_dim, dtype=np.float32).tobytes()
img1 = np.arange(2 * patch_dim, dtype=np.float32).tobytes()
store = _ImageStore(
image_bytes=[img0, img1],
image_num_patches=[3, 2],
patch_dim=patch_dim,
image_grids=[[1, 1, 3], [1, 1, 2]],
)
# Assemble both images
pixel_bytes, shape, grids = store.assemble([0, 1])
assert shape == [5, 4]
assert grids == [[1, 1, 3], [1, 1, 2]]
assert pixel_bytes == img0 + img1
# Assemble single image
pixel_bytes, shape, grids = store.assemble([1])
assert shape == [2, 4]
assert grids == [[1, 1, 2]]
assert pixel_bytes == img1
# Assemble in reverse order
pixel_bytes, shape, grids = store.assemble([1, 0])
assert shape == [5, 4]
assert grids == [[1, 1, 2], [1, 1, 3]]
assert pixel_bytes == img1 + img0
def test_vlm_image_cache_from_store():
"""VLMImageCache.from_store provides correct get_for_step/get_all via lazy assembly."""
patch_dim = 2
img0_data = np.array([[1.0, 2.0]], dtype=np.float32)
img1_data = np.array([[3.0, 4.0]], dtype=np.float32)
store = _ImageStore(
image_bytes=[img0_data.tobytes(), img1_data.tobytes()],
image_num_patches=[1, 1],
patch_dim=patch_dim,
image_grids=[[1, 2, 3], [1, 4, 4]],
)
step_indices = {
1: [[0], [0, 1]], # step 0: image 0; step 1: images 0+1
}
cache = VLMImageCache.from_store(
store=store,
step_indices=step_indices,
num_unique_examples=1,
num_unique_images=2,
extract_time=0.0,
preprocess_time=0.0,
)
# Step 0: just image 0
pv, shape, grid = cache.get_for_step(1, 0)
assert _decode_pixels(pv, shape) == [[1.0, 2.0]]
assert grid == [[1, 2, 3]]
# Step 1: images 0 + 1
pv, shape, grid = cache.get_for_step(1, 1)
assert _decode_pixels(pv, shape) == [[1.0, 2.0], [3.0, 4.0]]
assert grid == [[1, 2, 3], [1, 4, 4]]
# get_all returns last step
pv, shape, grid = cache.get_all(1)
assert _decode_pixels(pv, shape) == [[1.0, 2.0], [3.0, 4.0]]
assert grid == [[1, 2, 3], [1, 4, 4]]
# Missing key
pv, shape, grid = cache.get_for_step(999, 0)
assert pv is None
# Out of range step
pv, shape, grid = cache.get_for_step(1, 5)
assert pv is None
def test_vlm_image_cache_from_store_no_images():
"""from_store with store=None returns (None, None, None) for all queries."""
step_indices = {0: [[], []]} # 2 steps with no images
cache = VLMImageCache.from_store(
store=None,
step_indices=step_indices,
num_unique_examples=1,
num_unique_images=0,
extract_time=0.0,
preprocess_time=0.0,
)
pv, shape, grid = cache.get_for_step(0, 0)
assert pv is None
assert shape is None
assert grid is None
def test_build_vlm_image_cache_uses_store():
"""build_vlm_image_cache returns a store-backed cache."""
import torch
red_url = _create_test_image("red")
output = vf.RolloutOutput(
example_id=1,
trajectory=[
vf.TrajectoryStep(
prompt=[_create_image_message(red_url, "What color?")],
completion=[{"role": "assistant", "content": "Red"}],
response=MagicMock(),
tokens=MagicMock(),
reward=None,
advantage=None,
is_truncated=False,
trajectory_id="1",
extras={},
),
],
sampling_args={"temperature": 1.0},
error=None,
)
mock_processor = MagicMock()
mock_processor.image_processor = MagicMock(
side_effect=lambda images, return_tensors: {
"pixel_values": torch.arange(len(images), dtype=torch.float32).view(-1, 1),
"image_grid_thw": torch.tensor([[1, 1, 1]] * len(images)),
}
)
cache = build_vlm_image_cache([output], mock_processor)
# Should be store-backed
assert cache._store is not None
assert cache._step_indices is not None
# Should still work correctly
pv, shape, grid = cache.get_for_step(0, 0)
assert pv is not None
assert shape == [1, 1]
assert grid == [[1, 1, 1]]
+1 -1
View File
@@ -28,7 +28,7 @@ from prime_rl.inference.vllm.server import resolve_tool_call_parser
("Qwen/Qwen3-4B-Instruct-2507", "hermes"),
("Qwen/Qwen3-Coder-480B-A35B-Instruct", "hermes"),
("Qwen/Qwen3-Next-80B-A3B-Instruct", "hermes"),
("Qwen/Qwen3.5-397B-A17B", "hermes"),
("Qwen/Qwen3.5-397B-A17B", "qwen3_coder"),
],
)
def test_auto_detect_tool_call_parser(model_name: str, expected_parser: str):
Generated
+795 -1084
View File
File diff suppressed because it is too large Load Diff