Compare commits

...
Author SHA1 Message Date
samsjaandGitHub 03f7feff14 Add pydantic-config submodule (#2556)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-18 21:46:40 -07:00
87ab84b666 chore(orchestrator): deprecate use_token_client (#2549)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore(orchestrator): deprecate use_token_client (server-tokenized TITO)

Drop the server-tokenized TITO path (``openai_chat_completions_token`` /
``/v1/chat/completions/tokens``). The orchestrator now picks between
renderer-backed TITO (``use_renderer = true``, default) and MITO
(``use_renderer = false``, fallback for VLMs and external teacher rollouts).

- Remove ``OrchestratorConfig.use_token_client`` field and its validators
- Drop the TITO branch in ``setup_rollout_inference_pool``
- Drop the obsolete TITO warning in ``setup_inference_pool`` and flip the
  default ``train_client_type`` to ``openai_chat_completions`` in
  ``StaticInferencePool`` / ``ElasticInferencePool``
- Strip ``use_token_client = false`` from configs/examples/docs that
  carried the no-op fallback line
- CHANGELOG entry documenting the breaking removal

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

* chore(inference): remove server-side TITO route

Drop the ``/v1/chat/completions/tokens`` endpoint and the
``OpenAIServingChatWithTokens`` / ``ChatCompletionRequestWithTokens``
wrappers now that no client routes to them. Also drop the obsolete
``base()`` helper and unused imports from ``server.py``.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:22:07 -07:00
halleriteandGitHub 0b37bc923e fix(tests): inject prime lm_head + complete ring-attn restore (#2547)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-19 02:08:06 +02:00
halleriteandGitHub 6591943919 feat(orchestrator): validate renderer auto-resolution at config time (#2537) (#2540)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-19 01:06:07 +02:00
alelpoanandGitHub 4748472b9f docs: add testing-moe-at-small-scale to mint.json navigation (#2542)
Release / Push CUDA image to Docker (push) Canceled after 0s
Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>
2026-05-18 15:31:27 -07:00
samsjaandGitHub 8106bf0a02 [codex] add custom qwen3 dense model (#2505)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add custom qwen3 dense model

* format qwen3 model files

* remove qwen3 unit test
2026-05-18 15:30:47 -07:00
46653c1d70 [codex] add per-env trainer metrics (#2478)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add per-env trainer metrics

* require env names for trainer batches

* address per-env metric review feedback

* reuse tensor stats for env metrics

* fix sft trajectory env-name fixture

* address trainer metric naming comments

* fix: reuse trainer ratio tensors for env metrics

* fix: derive dppo mask from shared ratio

* address PR review: drop precomputed loss inputs, use {all,env} keys

- compute importance-ratio / mismatch_kl inside the loss functions instead of
  passing them in via LossInputs (per Mika)
- compute mismatch_kl inline in train.py only for per-env logging
- rename trainer aggregate keys to entropy/all and mismatch_kl/all to match the
  orchestrator {all,env}/{mean,std,max} convention; drop the leftover bare
  entropy/* and mismatch_kl/* keys
- drop the overly defensive env_names length check in DataLoader

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

* guard mismatch_kl logging behind sft_loss flag

SFT batches don't have meaningful inference_logprobs (sft_loss_fn ignores
them), so computing and logging mismatch_kl for those microbatches is wasted
work and produces misleading numbers. Skip the inline mismatch_kl compute and
the per-env / debug-log emissions when sft_loss is True.

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

* address review: simplify probs_diff and move mismatch_kl/all to trainer loop

* reserve env_name='all' for aggregate metric keys

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 15:19:52 -07:00
samsjaandGitHub c5fb9591b2 feat(orchestrator): default max_error_reschedule_attempts to 3 (#2484)
Release / Push CUDA image to Docker (push) Canceled after 0s
Follow-up to #2459. Switches the default from `None` (retry indefinitely)
to `3`, so single-example hangs in agent envs no longer block step progress
out of the box. Users who want the legacy infinite-retry behavior can still
set `None` explicitly.
2026-05-18 14:51:13 -07:00
alelpoanandGitHub b22e768fc4 docs: fix typos and grammar errors in documentation (#2544)
Release / Push CUDA image to Docker (push) Canceled after 0s
* docs: fix "seemless" typo

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

* docs: fix model name Qwen-4B to Qwen3-4B

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

* docs: fix "violation to" grammar error

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

* docs: fix "asynchronoously" typo

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

* docs: fix duplicate "the the"

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

---------

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>
2026-05-18 14:34:27 -07:00
faresobeidandGitHub ef8f459ca0 clean quack norm (#2543)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-18 14:28:54 -07:00
c3c6b70f11 [codex] chore: bump vllm to 0.21.0 (#2519)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore: bump vllm

* fix: adapt dp pause patch for vllm 0.21

* Drop deep_gemm ep_scatter and silu_mul_quant int64 monkey patches

Both int64-addressing carries are fixed upstream in vLLM 0.21.0.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 13:55:08 -07:00
f18297fd7d chore(verifiers): bump submodule to main (dd89b5e9) (#2534)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 20:18:58 -07:00
HubertandGitHub 6d80c412b6 Allow capped inflight rollout capacity (#2533)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-17 20:08:31 -07:00
a166a8b8df fix(orchestrator): trim glibc heap after each step to prevent RSS growth (#2527)
Release / Push CUDA image to Docker (push) Canceled after 0s
numpy/pandas allocate array data via malloc() (outside Python's allocator),
so gc.collect() alone doesn't reclaim RSS after per-step DataFrames are freed.
glibc retains freed pages in its internal pool, causing ~+6 MB/step monotonic
RssAnon growth on the orchestrator process.

malloc_trim(0) forces glibc to return freed heap pages to the OS, producing
a stable sawtooth pattern (peak during rollout generation, drops after trim)
with no upward trend.

Verified on alphabet-sort (512 rollouts/step, 20 steps, no wandb):
- Without fix: 941 MB → 973 MB by step 3 (+6 MB/step, unbounded)
- With fix:    941 MB → 942 MB by step 5 (flat, sawtooth only)

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 15:57:34 -07:00
samsjaandGitHub 66ff00d117 make renderers default for rollouts (#2521)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-17 12:58:38 +02:00
ae610d9dd8 feat(renderer): expose preserve_*_thinking flags in RendererConfig (#2436)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(renderer): expose preserve_*_thinking flags in RendererConfig

Adds two new fields to RendererConfig:
  - preserve_all_thinking
  - preserve_thinking_between_tool_calls

The orchestrator forwards them in two places so train and infer stay
consistent:

  1. create_renderer() — bound at construction on the training-side
     renderer used by build_trajectory_step / render_ids.
  2. setup_inference_pool() → setup_clients() → vf.ClientConfig — the
     verifiers RendererClient picks them up and forwards to its
     create_renderer_pool, so every inference render carries the same
     thinking-preservation behaviour.

Both flags are off by default → zero behaviour change for existing
configs. Setting either without orchestrator.use_renderer=True is
rejected by validate_renderer_args, matching the existing renderer
knobs.

Bumps source pins:
  - verifiers 3b77145 → a7516a1 (PR #1298: ClientConfig propagation)
  - renderers (now a separate repo): pinned to fe67f9f (PR #4:
    construction-time preserve flags)

Re-applies #2433, which was merged into feat/unify-inference-generate
by mistake.

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

* fix(sft): forward preserve_*_thinking flags through SFT renderer path

The flags were added to the shared RendererConfig but only wired up
in the orchestrator. SFT also constructs a renderer via create_renderer
for training-side tokenization, so it must forward both flags or
silently ignore them.

Also tighten validate_renderer_args to reject either flag when
use_renderer=False, matching the orchestrator validator.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 17:38:53 -07:00
84 changed files with 925 additions and 824 deletions
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
+2 -2
View File
@@ -32,7 +32,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v5
- name: Install dependencies
@@ -97,7 +97,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v5
- name: Install dependencies
+1 -1
View File
@@ -79,7 +79,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
+1 -1
View File
@@ -29,7 +29,7 @@ jobs:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
- name: Docker meta
id: meta
uses: crazy-max/ghaction-docker-meta@v2
+3
View File
@@ -10,3 +10,6 @@
[submodule "configs/private"]
path = configs/private
url = git@github.com:PrimeIntellect-ai/research-configs.git
[submodule "pydantic-config"]
path = deps/pydantic-config
url = https://github.com/PrimeIntellect-ai/pydantic-config
+1
View File
@@ -2,6 +2,7 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`orchestrator.use_token_client` removed**: The server-tokenized TITO path has been deprecated end-to-end. The orchestrator-side config flag (`use_token_client`), the verifiers client_type (`openai_chat_completions_token`), and the inference server's `/v1/chat/completions/tokens` route (along with the `OpenAIServingChatWithTokens` wrapper) are all gone. The orchestrator now picks between renderer-backed TITO (`use_renderer = true`, default) and MITO (`use_renderer = false`, fallback). Existing configs with `use_token_client = true` must migrate to `use_renderer = true` (or `use_renderer = false` for MITO); configs with `use_token_client = false` can simply drop the field. (2026-05-19)
- **`orchestrator.advantage.length_penalty` → discriminated sub-config**: The scalar `length_penalty: Literal["tokens","turns"] | None` is replaced by a `LengthPenaltyConfig | None` discriminated on `type`. Token shaping now takes weighted completion + tool-response token costs. Migration: `length_penalty = "tokens"` becomes `[orchestrator.advantage.length_penalty]\ntype = "tokens"` (default weights `completion_weight = 1.0`, `tool_response_weight = 1.0` — total context). `length_penalty = "turns"` becomes `[orchestrator.advantage.length_penalty]\ntype = "turns"`. (2026-05-06)
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
- **`AdvantageInputs` API**: Replaced the `rewards`/`completion_lengths`/`num_turns` tensor fields with a single `rollouts: list[list[vf.RolloutOutput]]` (grouped by problem). Custom advantage functions can now access any rollout metadata. Existing custom advantages must update their signatures and extract per-rollout fields directly (e.g. `torch.tensor([[r["reward"] for r in g] for g in inputs.rollouts])`). (2026-05-01)
+1 -1
View File
@@ -94,7 +94,7 @@ cd prime-rl
2. Initialize submodules
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
```
3. Install [uv](https://docs.astral.sh/uv/)
+6 -1
View File
@@ -45,4 +45,9 @@ rollouts_per_example = 32
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+6 -1
View File
@@ -46,4 +46,9 @@ rollouts_per_example = 32
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+6 -1
View File
@@ -4,7 +4,7 @@ seq_len = 2048
[ckpt]
[model]
name = "PrimeIntellect/Qwen3-0.6B"
name = "Qwen/Qwen3-0.6B"
[trainer.optim]
lr = 1e-5
@@ -22,3 +22,8 @@ name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
[inference]
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
[orchestrator.renderer]
preserve_all_thinking = true
@@ -20,4 +20,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -19,4 +19,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -31,4 +31,8 @@ id = "reverse-text"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
gpu_memory_utilization = 0.7
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -30,4 +30,8 @@ id = "reverse-text"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
gpu_memory_utilization = 0.7
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -27,3 +27,7 @@ gpu_memory_utilization = 0.7
[inference.model]
max_model_len = 2048
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -20,3 +20,7 @@ id = "reverse-text"
[ckpt]
interval = 10
resume_step = -1
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[renderer]
name = "default"
+6 -1
View File
@@ -28,4 +28,9 @@ args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", que
[trainer]
[inference]
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
@@ -16,6 +16,7 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
rollouts_per_example = 16
use_renderer = false
[orchestrator.train.sampling]
max_completion_tokens = 64
+6 -1
View File
@@ -31,4 +31,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+6 -1
View File
@@ -32,4 +32,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+6 -1
View File
@@ -32,4 +32,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+7 -2
View File
@@ -6,7 +6,7 @@ project = "gsm8k-debug"
name = "gsm8k"
[model]
name = "PrimeIntellect/Qwen3-0.6B"
name = "Qwen/Qwen3-0.6B"
[orchestrator]
batch_size = 512
@@ -22,4 +22,9 @@ args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max
[trainer] # Default trainer config
[inference] # Default inference config
[inference] # Default inference config
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
[orchestrator.renderer]
preserve_all_thinking = true
+6 -1
View File
@@ -36,4 +36,9 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
max_model_len = 8192
[log]
level = "debug"
level = "debug"
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+5 -1
View File
@@ -52,4 +52,8 @@ temperature = 0.5
[trainer.optim]
lr = 3e-6
[inference] # Default inference config
[inference] # Default inference config
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -11,6 +11,7 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
rollouts_per_example = 16
use_renderer = false
[orchestrator.train.sampling]
@@ -12,6 +12,7 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 16
rollouts_per_example = 2
use_renderer = false
[orchestrator.train.sampling]
max_completion_tokens = 32
Vendored Submodule
+1
Submodule deps/pydantic-config added at b6a2411e44
+1 -1
+1 -1
+2 -2
View File
@@ -8,7 +8,7 @@ Checkpointing is non-standard due to trainer/orchestrator separation and natural
The default checkpoint directory is `checkpoints` and each checkpoint step will live in a step subdirectory, i.e. `checkpoints/step_{step}`.
Checkpointing is configured with the config key `--ckpt`. One can specify the interval (`--ckpt.interval`), whether to save checkpoints asynchronoously (`--ckpt.save-async`), how many recent step checkpoints to keep on disk (`--ckpt.keep-last`), and keep checkpoints at every N steps permanently (`--ckpt.keep-interval`). By default, we do not checkpoint to save disk space.
Checkpointing is configured with the config key `--ckpt`. One can specify the interval (`--ckpt.interval`), whether to save checkpoints asynchronously (`--ckpt.save-async`), how many recent step checkpoints to keep on disk (`--ckpt.keep-last`), and keep checkpoints at every N steps permanently (`--ckpt.keep-interval`). By default, we do not checkpoint to save disk space.
## SFT
@@ -54,4 +54,4 @@ uv run rl \
--orchestrator @ path/to/orch.toml \
--max-steps 20 \
--ckpt.resume-step 10
```
```
+1 -1
View File
@@ -30,4 +30,4 @@ name = "Qwen/Qwen-14B"
PRIME_MODEL__NAME=Qwen/Qwen3-4B uv run ... @ qwen8b.toml @ qwen14b.toml --model.name Qwen/Qwen3-32B
```
In this example, the CLI argument `--model.name Qwen/Qwen3-32B` will take precedence and the script will use `Qwen/Qwen3-32B` as the model name. If the CLI argument wasn't set, then the second config file would take precedence and the script would use `Qwen/Qwen-14B` as the model name. If the second config file wasn't set, then the first config file would take precedence and the script would use `Qwen/Qwen3-8B` as the model name. Finally, if the first config file wasn't set, then the environment variable would take precedence and the script would use `Qwen/Qwen-4B` as the model name. If the environment variable wasn't set, then the default value would be used and the script would use `Qwen/Qwen3-0.6B` as the model name.
In this example, the CLI argument `--model.name Qwen/Qwen3-32B` will take precedence and the script will use `Qwen/Qwen3-32B` as the model name. If the CLI argument wasn't set, then the second config file would take precedence and the script would use `Qwen/Qwen-14B` as the model name. If the second config file wasn't set, then the first config file would take precedence and the script would use `Qwen/Qwen3-8B` as the model name. Finally, if the first config file wasn't set, then the environment variable would take precedence and the script would use `Qwen/Qwen3-4B` as the model name. If the environment variable wasn't set, then the default value would be used and the script would use `Qwen/Qwen3-0.6B` as the model name.
+1 -1
View File
@@ -48,7 +48,7 @@ For more details on multi-node deployment options, see the [deployment](deployme
## SFT
We provide a fairly straight-forward SFT trainer which is capable of fine-tuning any conversational model on multi-turn conversation with tool calling. It shares a lot of components with the RL trainer, such as the modeling code, parallelism techniques, checkpoint format, logger, etc. which ensures a seemless post-training workflow.
We provide a fairly straight-forward SFT trainer which is capable of fine-tuning any conversational model on multi-turn conversation with tool calling. It shares a lot of components with the RL trainer, such as the modeling code, parallelism techniques, checkpoint format, logger, etc. which ensures a seamless post-training workflow.
To start an SFT training, you need to prepare a conversational dataset in either [prompt-completion format](https://huggingface.co/docs/trl/en/dataset_formats#prompt-completion) or raw `messages` format. If `messages` is provided, the trainer interprets the full conversation as a single sample with an empty prompt and applies role-based loss masking across the whole chat. If both `messages` and `prompt` / `completion` are present, `messages` takes precedence. Single-turn fine-tuning should be compatible with the chat templates of most models. However, to properly handle loss masking, we require that the tokenizer's chat template satisfies a prefix property: the tokenization of any conversation prefix must be a prefix of the tokenization of the full conversation. For instance, tokenizing message 1 should yield a token sequence that forms a prefix of tokenizing messages 1 and 2, which in turn should be a prefix of tokenizing messages 1, 2, 3, and so forth. An example of a chat template that *does not* satisfy this property is Qwen3's chat template, as it strips away past think sections.
+2 -1
View File
@@ -15,8 +15,9 @@
"benchmarking",
"deployment",
"kubernetes",
"testing-moe-at-small-scale",
"troubleshooting"
]
}
]
}
}
+2 -1
View File
@@ -71,7 +71,8 @@ Use this mode when you want to train from teacher-generated completions directly
type = "sft"
[orchestrator]
use_token_client = false
use_renderer = false
use_sft_loss = true
[orchestrator.teacher_rollout_model.client]
base_url = ["https://your-openai-compatible-endpoint/v1"]
+1 -1
View File
@@ -39,7 +39,7 @@ Interleaving enforces a strict invariant:
> The prompt at turn $t$ must be the exact concatenation of prior messages exactly as the LLM originally generated them
We call this the "exact prefix" invariant. For example, at turn 2, the LLM should see U1,A1,U2 as the prompt, where U1 exactly matches the user message in turn 1 and A1 exactly matches the produced assistant message in turn 1. Any violation to this invariant will result in downstream problems when computing the importance sampling ratio during training.
We call this the "exact prefix" invariant. For example, at turn 2, the LLM should see U1,A1,U2 as the prompt, where U1 exactly matches the user message in turn 1 and A1 exactly matches the produced assistant message in turn 1. Any violation of this invariant will result in downstream problems when computing the importance sampling ratio during training.
For example, assume that at turn 2 the prompt is U1,A1',U2 where A1' varies from A1. In this scenario it is not clear whether to add A1 or A1' to the interleaved rollout:
- If we add A1', the logprobs from turn 1 might be off because the inference LLM produced A1 but the trainer LLM is computing logprobs for A1'
+1 -1
View File
@@ -12,7 +12,7 @@ ulimit -n 32000
Assuming this is happening on the RL or SFT trainer, you can try the following:
- Use full activation checkpointing (`--model.ac`)
- Reduce the the micro batch size (`--data.micro-batch-size`) and sequence length (`--data.seq-len`)
- Reduce the micro batch size (`--data.micro-batch-size`) and sequence length (`--data.seq-len`)
- (*Experimental*) Use context parallelism with `--model.cp`
> I cannot pass my TOML config file
+5 -1
View File
@@ -94,4 +94,8 @@ args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200
id = "aime2025"
[inference.parallel]
tp = 8
tp = 8
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
+1 -1
View File
@@ -29,7 +29,7 @@ save_adapter_separately = true
[orchestrator]
batch_size = 256
rollouts_per_example = 4
use_token_client = false
use_renderer = false
use_sft_loss = true
[orchestrator.train.sampling]
+6 -1
View File
@@ -34,4 +34,9 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
seq_len = 16384
[inference.model]
max_model_len = 8192
max_model_len = 8192
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+5 -1
View File
@@ -68,4 +68,8 @@ hard_threshold = 0.0
seed = 42
[inference.parallel]
tp = 8
tp = 8
# PrimeIntellect/MiniMax-M2.5-bf16 — template-identical to MiniMaxAI/MiniMax-M2.5 (mapped).
[orchestrator.renderer]
name = "minimax-m2"
+5 -1
View File
@@ -23,4 +23,8 @@ lr = 3e-6
[ckpt] # Checkpoint at the end of training
[inference]
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
+7
View File
@@ -29,3 +29,10 @@ max_completion_tokens = 1024
[inference.parallel]
dp = 6
# Qwen3 finetune with the standard PI template patch (byte-identical to
# PrimeIntellect/Qwen3-0.6B base); always re-emits prior <think> blocks.
# Match that with the qwen3 renderer's preserve_all_thinking.
[orchestrator.renderer]
name = "qwen3"
preserve_all_thinking = true
+6
View File
@@ -10,6 +10,12 @@ dependencies = [
# doesn't expose `BaseConfig` / `cli`. Pin to samsja's fork so plain
# `pip install prime-rl-configs` (no uv workspace context) resolves it.
"pydantic-config @ git+https://github.com/samsja/pydantic_config.git",
# OrchestratorConfig validates renderer.name='auto' against
# renderers.base.MODEL_RENDERER_MAP. Renderers itself is light; its only
# weighty transitive (transformers) is lazy-imported via the validator,
# so plain `from prime_rl.configs.orchestrator import OrchestratorConfig`
# still doesn't pull it into sys.modules.
"renderers>=0.1.8.dev4",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
]
@@ -1026,10 +1026,11 @@ class OrchestratorConfig(BaseConfig):
oversampling_factor: Annotated[
float | None,
Field(
ge=1,
gt=0,
description=(
"Rollout-mode batching only. Multiplier used to derive max_inflight_rollouts from batch_size "
"when max_inflight_rollouts is unset."
"when max_inflight_rollouts is unset. Values below 1.0 intentionally cap in-flight rollout "
"capacity below batch_size."
),
),
] = None
@@ -1088,7 +1089,7 @@ class OrchestratorConfig(BaseConfig):
ge=1,
description="The group is dropped from the current step's batch once this many of its dispatch rounds have returned errored or empty rollouts (the trainer proceeds with the rollouts from other groups). Counts rounds, not individual rollouts: a non-group-scoring env that dispatches `rollouts_per_example` rollouts at once still only counts one round per failed batch. `None` means retry indefinitely (legacy behavior). Useful for unblocking single-example hangs in agent envs.",
),
] = None
] = 3
max_async_level: Annotated[
int,
@@ -1118,26 +1119,16 @@ class OrchestratorConfig(BaseConfig):
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
] = None
use_token_client: Annotated[
bool,
Field(
description="Whether to use the token-in-token-out (TITO) client for training across all environments. "
"WARNING: Only use this if your environment has a linear history and the chat template has the extension "
"property (i.e. no tokens are ever removed or inserted by the chat template). Mutually exclusive with "
"``use_renderer``."
),
] = True
use_renderer: Annotated[
bool,
Field(
description="Whether to use the renderer client (client-side tokenization via the ``renderers`` package, "
"served by ``/v1/generate``). Mutually exclusive with ``use_token_client``. When True, the "
"``[orchestrator.renderer]`` block (name / tool_parser / reasoning_parser / pool_size) "
"applies; when False those fields must be left at their defaults. Not supported for VLMs — "
"VLMs must use the token client (TITO) so image preprocessing and chat templating stay server-side."
description="Whether to use the renderer-backed TITO client (client-side tokenization via the ``renderers`` package, "
"served by ``/v1/generate``). When True, the ``[orchestrator.renderer]`` block "
"(name / tool_parser / reasoning_parser / pool_size) applies. This is the default for text-only "
"rollouts. Set to False to fall back to MITO (``openai_chat_completions``); VLMs and external "
"teacher rollouts require MITO."
),
] = False
] = True
env_install_prerelease: Annotated[
bool,
@@ -1208,10 +1199,6 @@ class OrchestratorConfig(BaseConfig):
)
if has_teacher and not self.use_sft_loss:
raise ValueError("orchestrator.teacher_rollout_model requires orchestrator.use_sft_loss = true.")
if has_teacher and self.use_token_client:
raise ValueError(
"orchestrator.use_token_client must be false when orchestrator.teacher_rollout_model is configured."
)
if has_teacher and self.use_renderer:
raise ValueError(
"orchestrator.use_renderer must be false when orchestrator.teacher_rollout_model is configured "
@@ -1219,36 +1206,17 @@ class OrchestratorConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_client_mode(self):
"""The two client toggles select among three exclusive modes:
- ``use_token_client=True`` + ``use_renderer=False`` → TITO (default)
- ``use_token_client=False`` + ``use_renderer=True`` → renderer
- ``use_token_client=False`` + ``use_renderer=False`` → MITO
Both True is invalid: TITO and renderer are different wire protocols
(server-side templating vs client-side tokenization).
"""
if self.use_token_client and self.use_renderer:
raise ValueError(
"orchestrator.use_token_client and orchestrator.use_renderer are mutually exclusive. "
"Pick one: token client (TITO, server-side templating) or renderer client (client-side "
"tokenization)."
)
return self
@model_validator(mode="after")
def validate_renderer_vs_vlm(self):
"""The renderer client takes plain message dicts and tokenizes
them client-side. VLMs need server-side image preprocessing and
chat templating, so they must use the token client (TITO) — fail
chat templating, so they must use MITO — fail
loudly when both are set."""
if self.use_renderer and self.model.vlm is not None:
raise ValueError(
"orchestrator.use_renderer is not supported for VLMs. Use the token client "
"(``use_token_client=true``, the default) so image preprocessing and chat "
"templating stay on the inference server."
"orchestrator.use_renderer is not supported for VLMs. Use MITO "
"(``use_renderer=false``) so image preprocessing and chat templating stay on the "
"inference server."
)
return self
@@ -1269,6 +1237,12 @@ class OrchestratorConfig(BaseConfig):
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
if self.renderer.pool_size is not None:
renderer_args_set.append(f"renderer.pool_size={self.renderer.pool_size!r}")
if self.renderer.preserve_all_thinking:
renderer_args_set.append(f"renderer.preserve_all_thinking={self.renderer.preserve_all_thinking!r}")
if self.renderer.preserve_thinking_between_tool_calls:
renderer_args_set.append(
f"renderer.preserve_thinking_between_tool_calls={self.renderer.preserve_thinking_between_tool_calls!r}"
)
if renderer_args_set:
raise ValueError(
@@ -1277,6 +1251,42 @@ class OrchestratorConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_renderer_auto_resolves(self):
"""Reject the silent DefaultRenderer fallback at config time.
When ``use_renderer=True`` with ``renderer.name='auto'`` and the
model isn't in ``MODEL_RENDERER_MAP``, ``create_renderer`` would
fall back to ``DefaultRenderer``. That fallback doesn't fix the
position-dependent chat-template bug the renderer client exists to
solve, and rejects envs that pass tools (the rollout dies with
"RendererPool does not support tools") unless
``renderer.tool_parser`` is configured. Surface at config time so
``--dry-run`` reports the error.
"""
if not self.use_renderer or self.renderer.name != "auto":
return self
from renderers.base import MODEL_RENDERER_MAP
model_id = self.tokenizer.name or self.model.name
if model_id in MODEL_RENDERER_MAP:
return self
raise ValueError(
f"orchestrator.use_renderer=True with renderer.name='auto' but "
f"{model_id!r} is not in renderers.base.MODEL_RENDERER_MAP, so it "
f"would silently fall back to DefaultRenderer. Pick one: "
f"(a) [orchestrator.renderer] name='default' — for fine-tunes / "
f"vendored mirrors with custom chat templates (DefaultRenderer "
f"calls apply_chat_template); pair with tool_parser=<name> if "
f"the env uses tools. "
f"(b) [orchestrator.renderer] name=<model-specific renderer> — "
f"if {model_id!r} is template-identical to a mapped family "
f"(and ideally also add it upstream to "
f"renderers.base.MODEL_RENDERER_MAP). "
f"(c) orchestrator.use_renderer=false — opt out of the renderer "
f"client entirely."
)
@model_validator(mode="after")
def nccl_max_async_level(self):
if self.weight_broadcast.type == "nccl":
@@ -1304,13 +1314,17 @@ class OrchestratorConfig(BaseConfig):
assert self.batch_size is not None
if self.batch_size % self.rollouts_per_example != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
resolved_max_inflight_rollouts = max(
self.rollouts_per_example,
int(self.batch_size * oversampling_factor),
)
if self.max_inflight_rollouts is not None and self.oversampling_factor is not None:
expected_max_inflight_rollouts = int(self.batch_size * self.oversampling_factor)
expected_max_inflight_rollouts = resolved_max_inflight_rollouts
if self.max_inflight_rollouts != expected_max_inflight_rollouts:
raise ValueError("max_inflight_rollouts conflicts with oversampling_factor * batch_size")
if self.max_inflight_rollouts is None:
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
self.max_inflight_rollouts = int(self.batch_size * oversampling_factor)
self.max_inflight_rollouts = resolved_max_inflight_rollouts
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.rollouts_per_example:
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
@@ -438,7 +438,7 @@ class RLConfig(BaseConfig):
"""Forbid configuring a local inference server when rollouts come from an external teacher.
Orchestrator-only invariants (``use_sft_loss`` paired with ``teacher_rollout_model``,
and ``use_token_client`` coupling) live on ``OrchestratorConfig`` so the hosted
and ``use_renderer`` coupling) live on ``OrchestratorConfig`` so the hosted
orchestrator entrypoint also enforces them.
"""
if self.orchestrator.teacher_rollout_model is not None and self.inference is not None:
@@ -414,6 +414,12 @@ class SFTConfig(BaseConfig):
renderer_args_set.append(f"renderer.tool_parser={self.renderer.tool_parser!r}")
if self.renderer.reasoning_parser is not None:
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
if self.renderer.preserve_all_thinking:
renderer_args_set.append(f"renderer.preserve_all_thinking={self.renderer.preserve_all_thinking!r}")
if self.renderer.preserve_thinking_between_tool_calls:
renderer_args_set.append(
f"renderer.preserve_thinking_between_tool_calls={self.renderer.preserve_thinking_between_tool_calls!r}"
)
if renderer_args_set:
raise ValueError(
@@ -135,7 +135,7 @@ class BaseModelConfig(BaseConfig):
class RendererConfig(BaseConfig):
"""Configures the client-side renderer (chat-template + response parsing).
Only consumed when ``orchestrator.use_renderer = true``. The renderer
Consumed when ``use_renderer = true``. The renderer
owns both directions: render messages → token ids on the client, and
parse model output tokens → structured ``content`` / ``reasoning_content``
/ ``tool_calls``.
@@ -186,6 +186,37 @@ class RendererConfig(BaseConfig):
),
] = None
preserve_all_thinking: Annotated[
bool,
Field(
description=(
"Override flag forwarded to the renderer at construction. When "
"True, every past-assistant turn's ``reasoning_content`` is "
"re-emitted between ``<think>``/``</think>`` (or the model's "
"equivalent), even if the underlying chat template would drop "
"it. Off by default — preserves byte-identical output to the "
"stock template. Strict superset of "
"``preserve_thinking_between_tool_calls``."
),
),
] = False
preserve_thinking_between_tool_calls: Annotated[
bool,
Field(
description=(
"Override flag forwarded to the renderer at construction. When "
"True, preserves past-assistant ``reasoning_content`` only "
"inside the *current* tool cycle — the contiguous "
"assistant→tool→…→assistant block after the most recent user "
"message, when that block contains at least one tool response. "
"A new user turn closes the block; older blocks fall back to "
"the template default (typically dropped). Use "
"``preserve_all_thinking`` to keep older blocks too."
),
),
] = False
class ElasticConfig(BaseConfig):
"""Configures elastic inference pool with DNS-based service discovery.
+5 -4
View File
@@ -18,7 +18,7 @@ dependencies = [
"torchaudio",
"torchdata>=0.11.0",
"transformers",
"vllm>=0.20.2",
"vllm>=0.21.0",
"wandb>=0.26.1",
"ring-flash-attn>=0.1.8",
"prime>=0.6.4",
@@ -98,7 +98,7 @@ gpt-oss = [
"kernels",
]
quack = [
"quack-kernels>=0.3.3",
"quack-kernels>=0.4.1",
]
all = [
"prime-rl[flash-attn]",
@@ -176,6 +176,7 @@ override-dependencies = [
[tool.uv.exclude-newer-package]
# we want latest vllm, remove next patch
vllm = false
tokenspeed-mla = false
flash_attn_3 = false
# PrimeIntellect-published on PyPI (trusted publisher)
prime = false
@@ -231,8 +232,8 @@ flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdi
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", branch = "main" }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" }
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_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" }
+12
View File
@@ -116,6 +116,14 @@ id = "math-env"
On the CLI, list items are indexed: `--env.0.id reverse-text --env.1.id math-env`.
When composing multiple TOML files, list fields are replaced wholesale by the later file. To change one
`orchestrator.filters` entry in an overlay, include the full desired filter list in that overlay.
For quick KL smoke runs with very small rollout batches, enforced `zero_advantage` filtering can remove
every rollout and stop the orchestrator. If the goal is only trainer/inference mismatch KL, keep the
filter present but set `enforce = false` in a temporary overlay and call out that the run is not a reward
learning validation.
### Dict fields
In TOML, use a section:
@@ -157,6 +165,10 @@ If you wish to configure values of the default variant, you don't need to set th
For hosted multi-tenant runs where the trainer image's `trainer.loss.type` is fixed, the orchestrator exposes a per-run override that forces SFT loss on every micro-batch without rebuilding the trainer. Set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; both must be configured together (the orchestrator validator enforces this). The orchestrator stamps each `TrainingSample.sft_loss = True`, which the trainer's `compute_loss` honors by dispatching to `sft_loss_fn` per batch — independent of the trainer's configured default loss.
### RL rollout client defaults
For text-only RL rollouts, the orchestrator defaults to renderer-backed TITO (`use_renderer = true`). VLM configs must explicitly fall back to MITO (`use_renderer = false`) so image preprocessing and chat templating stay server-side. External teacher rollouts must also set `use_renderer = false`.
### Model fields
For `BaseModel | None` fields (like `[ckpt]`, `[wandb]`, `[compile]`), a bare flag enables them with defaults:
-1
View File
@@ -49,7 +49,6 @@ uv run inference --model.name Qwen/Qwen3-0.6B --model.enforce-eager
Always use the `inference` entrypoint — never `vllm serve` directly.
Custom endpoints beyond standard OpenAI API:
- `/v1/chat/completions/tokens` — accepts token IDs as prompt input
- `/update_weights` — hot-reload model weights from the trainer
- `/load_lora_adapter` — load LoRA adapters at runtime
- `/init_broadcaster` — initialize weight broadcast for distributed training
+5 -3
View File
@@ -12,18 +12,18 @@ prime-rl is a monorepo with submodules. Clone the repo first, then initialize su
```bash
git clone git@github.com:PrimeIntellect-ai/prime-rl.git
cd prime-rl
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
```
For an existing clone, initialize the public submodules by passing explicit paths:
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
```
Do **not** use `git submodule update --init --recursive` without explicit paths — it will also attempt to clone `configs/private` (a private submodule) and fail with "Repository not found" for users without access. Git will retry the clone once internally before aborting, which is expected behavior.
The public submodules live under `deps/`: `deps/verifiers/`, `deps/renderers/`, and `deps/research-environments/`. Each is also a uv workspace member, so source edits inside them apply to the prime-rl venv without re-sync.
The public submodules live under `deps/`: `deps/verifiers/`, `deps/renderers/`, `deps/research-environments/`, and `deps/pydantic-config/`. The uv workspace members among them apply source edits to the prime-rl venv without re-sync.
The install script (`scripts/install.sh`) handles the private submodule gracefully — it iterates each submodule individually so a failed `configs/private` init does not abort the rest.
@@ -36,6 +36,8 @@ uv sync --all-extras # recommended: includes envs, flash-attn, flash-attn-cute,
The `envs` extra installs the env packages listed in `pyproject.toml > [tool.uv.workspace] members`. Adding a new env means adding it there, in the `envs` extra, and in `[tool.uv.sources]`.
When intentionally bumping a package to a release newer than the workspace-wide `exclude-newer = "7 days"` window, add that package and any newly required transitive packages to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
## Advanced
### Mamba-SSM (NemotronH models)
+2 -3
View File
@@ -143,8 +143,8 @@ These tell you whether training is healthy or diverging.
| Metric | Source | Description |
|--------|--------|-------------|
| `mismatch_kl/mean` | trainer | KL divergence between trainer and (old) inference policy |
| `entropy/mean` | trainer | policy entropy |
| `mismatch_kl/{all,env}/{mean,std,max}` | trainer | KL divergence between trainer and (old) inference policy over trainable tokens (W&B) |
| `entropy/{all,env}/{mean,std,max}` | trainer | policy entropy over trainable tokens (W&B) |
| `masked_advantage_positive/mean` | trainer | fraction of DPPO-masked trainable tokens with positive advantage (W&B) |
| `masked_advantage_negative/mean` | trainer | fraction of DPPO-masked trainable tokens with negative advantage (W&B) |
| `optim/grad_norm` | trainer | gradient norm — spikes may precede divergence |
@@ -253,4 +253,3 @@ PRIME-RL::Launcher
```
For multi-node runs, trainer and inference processes are distributed across separate nodes. Use `srun` or `ssh` to inspect processes on other nodes directly.
+13 -295
View File
@@ -1,5 +1,4 @@
import torch
from vllm.triton_utils import tl, triton
def transformers_v5_compat():
@@ -15,8 +14,6 @@ def transformers_v5_compat():
_patch_qwen35_lora()
_patch_lora_key_prefix()
monkey_patch_deep_gemm_ep_scatter()
monkey_patch_deep_gemm_silu_mul_quant_int64()
monkey_patch_dp_engine_core_pause_resume_deadlock()
monkey_patch_vllm_layerwise_reload_alias_buffers()
@@ -51,294 +48,6 @@ def monkey_patch_vllm_layerwise_reload_alias_buffers():
logger.warning("Enabled vLLM layerwise reload alias-buffer patch.")
@triton.jit
def _apply_expert_map_triton(expert_id, expert_map):
if expert_id != -1:
expert_id = tl.load(expert_map + expert_id).to(expert_id.dtype)
return expert_id
@triton.jit
def _fwd_kernel_ep_scatter_2_int64(
total_token_num,
expert_start_loc,
recv_x,
recv_x_stride0,
recv_x_stride1,
recv_x_scale,
recv_x_scale_stride0,
recv_x_scale_stride1,
recv_topk,
recv_topk_stride0,
recv_topk_stride1,
output_tensor,
output_tensor_stride0,
output_tensor_stride1,
output_tensor_scale,
output_tensor_scale_stride0,
output_tensor_scale_stride1,
output_index,
output_index_stride0,
output_index_stride1,
topk_num: tl.constexpr,
expert_map,
HAS_EXPERT_MAP: tl.constexpr,
HIDDEN_SIZE: tl.constexpr,
HIDDEN_SIZE_PAD: tl.constexpr,
SCALE_HIDDEN_SIZE: tl.constexpr,
SCALE_HIDDEN_SIZE_PAD: tl.constexpr,
):
start_token_id = tl.program_id(0)
grid_num = tl.num_programs(0)
offset_in = tl.arange(0, HIDDEN_SIZE_PAD)
mask = offset_in < HIDDEN_SIZE
offset_in_s = tl.arange(0, SCALE_HIDDEN_SIZE_PAD)
mask_s = offset_in_s < SCALE_HIDDEN_SIZE
output_tensor_stride0 = output_tensor_stride0.to(tl.int64)
for token_id in range(start_token_id, total_token_num, grid_num):
to_copy = tl.load(recv_x + token_id * recv_x_stride0 + offset_in, mask=mask)
to_copy_s = tl.load(
recv_x_scale + token_id * recv_x_scale_stride0 + offset_in_s,
mask=mask_s,
)
for topk_index in tl.range(0, topk_num, 1, num_stages=4):
expert_id = tl.load(recv_topk + token_id * recv_topk_stride0 + topk_index)
if HAS_EXPERT_MAP:
expert_id = _apply_expert_map_triton(expert_id, expert_map)
if expert_id >= 0:
dest_token_index = tl.atomic_add(expert_start_loc + expert_id, 1)
dest_token_index_i64 = dest_token_index.to(tl.int64)
tl.store(
output_index + token_id * output_index_stride0 + topk_index,
dest_token_index,
)
output_tensor_ptr = output_tensor + dest_token_index_i64 * output_tensor_stride0
output_tensor_scale_ptr = output_tensor_scale + dest_token_index * output_tensor_scale_stride0
tl.store(output_tensor_ptr + offset_in, to_copy, mask=mask)
tl.store(output_tensor_scale_ptr + offset_in_s, to_copy_s, mask=mask_s)
def _triton_ep_scatter_int64(
recv_x: torch.Tensor,
recv_x_scale: torch.Tensor,
recv_topk: torch.Tensor,
num_recv_tokens_per_expert: torch.Tensor,
expert_map: torch.Tensor | None,
expert_start_loc: torch.Tensor,
output_tensor: torch.Tensor,
output_tensor_scale: torch.Tensor,
m_indices: torch.Tensor,
output_index: torch.Tensor,
) -> None:
from vllm.model_executor.layers.fused_moe import deep_gemm_utils
block_e = 128
num_warps = 8
num_experts = num_recv_tokens_per_expert.shape[0]
hidden_size = recv_x.shape[1]
assert m_indices.shape[0] % block_e == 0
assert expert_start_loc.shape[0] == num_experts
deep_gemm_utils._fwd_kernel_ep_scatter_1[(num_experts,)](
num_recv_tokens_per_expert,
expert_start_loc,
m_indices,
num_experts=num_experts,
num_warps=num_warps,
BLOCK_E=block_e,
BLOCK_EXPERT_NUM=triton.next_power_of_2(num_experts),
)
grid = min(recv_topk.shape[0], 1024 * 8)
_fwd_kernel_ep_scatter_2_int64[(grid,)](
recv_topk.shape[0],
expert_start_loc,
recv_x,
recv_x.stride(0),
recv_x.stride(1),
recv_x_scale,
recv_x_scale.stride(0),
recv_x_scale.stride(1),
recv_topk,
recv_topk.stride(0),
recv_topk.stride(1),
output_tensor,
output_tensor.stride(0),
output_tensor.stride(1),
output_tensor_scale,
output_tensor_scale.stride(0),
output_tensor_scale.stride(1),
output_index,
output_index.stride(0),
output_index.stride(1),
topk_num=recv_topk.shape[1],
expert_map=expert_map,
HAS_EXPERT_MAP=expert_map is not None,
num_warps=num_warps,
HIDDEN_SIZE=hidden_size,
HIDDEN_SIZE_PAD=triton.next_power_of_2(hidden_size),
SCALE_HIDDEN_SIZE=recv_x_scale.shape[1],
SCALE_HIDDEN_SIZE_PAD=triton.next_power_of_2(recv_x_scale.shape[1]),
)
def monkey_patch_deep_gemm_ep_scatter():
# Temporary local carry of the upstream fix while it is under review:
# issue: https://github.com/vllm-project/vllm/issues/39211
# PR: https://github.com/vllm-project/vllm/pull/39213
from vllm.logger import init_logger
from vllm.model_executor.layers.fused_moe import deep_gemm_utils
logger = init_logger(__name__)
deep_gemm_utils.ep_scatter = torch.no_grad()(_triton_ep_scatter_int64)
logger.warning("Enabled int64-addressing Triton patch for vLLM DeepGEMM ep_scatter.")
@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,
fp8_min: tl.constexpr,
fp8_max: tl.constexpr,
use_ue8m0: tl.constexpr,
GROUP_SIZE: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
pid_m = tl.program_id(0)
pid_n = tl.program_id(1)
N_2 = N // 2
m_offset = (pid_m * BLOCK_M).to(tl.int64)
n_offset = (pid_n * BLOCK_N).to(tl.int64)
if m_offset >= M:
return
offs_n = tl.arange(0, BLOCK_N).to(tl.int64)
offs_m = tl.arange(0, BLOCK_M).to(tl.int64)
base_y_ptr = y_ptr + m_offset * N + n_offset
act_in_ptrs = base_y_ptr + offs_m[:, None] * N + offs_n[None, :]
act_in = tl.load(act_in_ptrs)
mul_in = tl.load(act_in_ptrs + N_2)
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,
):
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
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,
fp8_min,
fp8_max,
use_ue8m0,
group_size,
block_m,
block_n,
)
return output, output_scales
def monkey_patch_deep_gemm_silu_mul_quant_int64():
# Temporary local carry for large DeepGEMM profile shapes whose row offsets
# exceed signed int32 address arithmetic in vLLM's Triton kernel.
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.
@@ -897,9 +606,9 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
- on resume, wake every DP rank and force an immediate global unfinished
sync instead of waiting for the normal 32-step cadence
This keeps the upstream pause-side fix from
https://github.com/vllm-project/vllm/pull/37024 and extends it with the
resume-side wave-state fix.
This also bypasses vLLM's two-phase DP pause implementation
(https://github.com/vllm-project/vllm/pull/39366), which makes resume
reject states that our weight-update flow can validly hit.
"""
from vllm.config import ParallelConfig
from vllm.v1.core.sched.interface import PauseState
@@ -909,7 +618,8 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
_base_add_request = EngineCore.add_request
_base_handle_client_request = EngineCoreProc._handle_client_request
_base_resume_scheduler = DPEngineCoreProc.resume_scheduler
_base_pause_complete = EngineCoreProc._pause_complete
_base_resume_scheduler = EngineCoreProc.resume_scheduler
def _patched_add_request(self, request: Request, request_wave: int = 0):
_base_add_request(self, request, request_wave)
@@ -930,8 +640,15 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
else:
_base_handle_client_request(self, request_type, request)
def _patched_pause_complete(self) -> bool:
self.pending_pause = False
self.ignore_start_dp_wave = False
return _base_pause_complete(self)
def _patched_resume_scheduler(self):
was_paused = self.scheduler.pause_state != PauseState.UNPAUSED
self.pending_pause = False
self.ignore_start_dp_wave = False
_base_resume_scheduler(self)
if was_paused:
self.engines_running = True
@@ -948,6 +665,7 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
DPEngineCoreProc.add_request = _patched_add_request
DPEngineCoreProc._handle_client_request = _patched_handle_client_request
DPEngineCoreProc._pause_complete = _patched_pause_complete
DPEngineCoreProc.resume_scheduler = _patched_resume_scheduler
DPEngineCoreProc._has_global_unfinished_reqs = _patched_has_global_unfinished_reqs
+3 -59
View File
@@ -1,22 +1,17 @@
import asyncio
from argparse import Namespace
from http import HTTPStatus
from typing import Any
import uvloop
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from starlette.datastructures import State
from vllm.engine.protocol import EngineClient
from vllm.entrypoints.openai.api_server import init_app_state
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionResponse
from vllm.entrypoints.openai.cli_args import make_arg_parser, validate_parsed_serve_args
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
from vllm.entrypoints.openai.engine.serving import OpenAIServing
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.entrypoints.openai.utils import validate_json_request
from vllm.entrypoints.serve.lora.protocol import LoadLoRAAdapterRequest
from vllm.entrypoints.utils import load_aware_call, with_cancellation
from vllm.logger import init_logger
from vllm.utils.argparse_utils import FlexibleArgumentParser
@@ -140,10 +135,6 @@ from prime_rl.inference.patches import (
monkey_patch_load_lora_adapter,
monkey_patch_tokenize_params_validation,
)
from prime_rl.inference.vllm.serving_chat_with_tokens import (
ChatCompletionRequestWithTokens,
OpenAIServingChatWithTokens,
)
# NOTE: Fix harmony stop token propagation for GPT-OSS models
# Upstream issue still open: https://github.com/vllm-project/vllm/issues/22519
@@ -165,10 +156,6 @@ def engine_client(request: Request) -> EngineClient:
return request.app.state.engine_client
def base(request: Request) -> OpenAIServing:
return request.app.state.openai_serving_tokenization
def models(request: Request) -> OpenAIServingModels:
return request.app.state.openai_serving_models
@@ -179,36 +166,6 @@ WORKER_EXTENSION_CLS = {
}
def chat_with_tokens(request: Request) -> OpenAIServingChatWithTokens | None:
return request.app.state.openai_serving_chat_with_tokens
@router.post(
"/v1/chat/completions/tokens",
dependencies=[Depends(validate_json_request)],
responses={
HTTPStatus.OK.value: {"content": {"text/event-stream": {}}},
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse},
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
},
)
@with_cancellation
@load_aware_call
async def _chat_with_tokens(request: ChatCompletionRequestWithTokens, raw_request: Request):
handler = chat_with_tokens(raw_request)
if handler is None:
return base(raw_request).create_error_response(message="The model does not support Chat Completions API")
generator = await handler.create_chat_completion_with_tokens(request, raw_request)
if isinstance(generator, ErrorResponse):
return JSONResponse(content=generator.model_dump(), status_code=generator.error.code)
elif isinstance(generator, ChatCompletionResponse):
return JSONResponse(content=generator.model_dump())
return StreamingResponse(content=generator, media_type="text/event-stream")
@router.post("/pause")
async def pause(request: Request):
await engine_client(request).pause_generation(mode="keep", clear_cache=False)
@@ -277,10 +234,7 @@ async def custom_init_app_state(
Modifies init_app_state:
1. Call the original init_app_state to set up standard state, including
vLLM 0.20's ``serving_tokens`` for ``/inference/v1/generate``.
2. Replace ``serving_chat`` with our ``OpenAIServingChatWithTokens`` wrapper
so the ``/v1/chat/completions/tokens`` (TITO) endpoint can stream
token IDs alongside the rendered chat completion.
3. Replace ``serving_tokens`` with ``PrimeRlServingTokens`` so DP-rank
2. Replace ``serving_tokens`` with ``PrimeRlServingTokens`` so DP-rank
routing and ``routed_experts`` export survive the migration off the
legacy ``/v1/generate`` endpoint.
"""
@@ -289,16 +243,6 @@ async def custom_init_app_state(
state.reset_prefix_cache_after_update = getattr(args, "reset_prefix_cache_after_update", True)
state.liveness_timeout_seconds = args.liveness_timeout_seconds
# TITO: server-side chat templating + token IDs.
if "generate" in supported_tasks and state.openai_serving_chat is not None:
original_chat = state.openai_serving_chat
serving_chat = object.__new__(OpenAIServingChatWithTokens)
serving_chat.__dict__.update(original_chat.__dict__)
state.openai_serving_chat = serving_chat
state.openai_serving_chat_with_tokens = serving_chat
else:
state.openai_serving_chat_with_tokens = None
# Swap in our ServingTokens subclass for /inference/v1/generate so the
# X-data-parallel-rank header and routed_experts response field — both
# used by prime-RL's renderer / router-replay paths — keep working.
@@ -1,243 +0,0 @@
from collections.abc import AsyncGenerator, AsyncIterator
from typing import ClassVar, Optional, Union
from fastapi import Request
from pydantic import Field
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest, ChatCompletionResponse
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 prime_rl.inference.vllm.serving_tokens import _RoutedExpertsCaptureBase
logger = init_logger(__name__)
class _RoutedExpertsCapture(_RoutedExpertsCaptureBase):
"""Chat-endpoint variant: mutates choices in-place because
``ChatCompletionResponseChoice`` is ``extra='allow'``, so an extra
``routed_experts`` attribute survives serialization."""
def post_process(self, response: ChatCompletionResponse) -> None:
for choice in response.choices:
if choice.index in self.routed_experts:
choice.routed_experts = self.routed_experts[choice.index]
class ChatCompletionRequestWithTokens(ChatCompletionRequest):
field_names: ClassVar[Optional[set[str]]] = None
tokens: list[int] = Field(description=("Prompt tokens to use for the request."))
class OpenAIServingChatWithTokens(OpenAIServingChat):
"""OpenAI-compatible generate API that allows token-in and routed experts capture."""
async def chat_completion_full_generator(
self,
request: ChatCompletionRequest,
result_generator: AsyncIterator[RequestOutput],
request_id: str,
model_name: str,
conversation,
tokenizer,
request_metadata: RequestResponseMetadata,
reasoning_parser: ReasoningParser | None = None,
) -> ErrorResponse | ChatCompletionResponse:
# We need to override the full_generator to be able to capture the routed experts
# By default, VLLM does not save the routed experts into ChatCompletionResponse.choices, so we need to capture them manually
# How this works:
# 1. We create a custom generator that encapsulates the original result_generator in self._generator
# 2. We override it's __aiter__ method to also capture the routed experts as an extra field in ChatCompletionResponse.choices
# 3. We override the full_generator method to use the custom generator instead of the original one if expert routing is enabled
if self.model_config.enable_return_routed_experts:
capture = _RoutedExpertsCapture(result_generator)
result_generator = capture
else:
capture = None
response = await super().chat_completion_full_generator(
request,
result_generator,
request_id,
model_name,
conversation,
tokenizer,
request_metadata,
reasoning_parser,
)
if capture and isinstance(response, ChatCompletionResponse):
capture.post_process(response)
return response
async def create_chat_completion_with_tokens(
self,
request: ChatCompletionRequestWithTokens,
raw_request: Optional[Request] = None,
) -> Union[AsyncGenerator[str, None], ChatCompletionResponse, ErrorResponse]:
"""
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
assert tokenizer is not None
reasoning_parser: ReasoningParser | None = None
try:
if self.reasoning_parser_cls:
# Pass the same chat template kwargs as used in tokenization
chat_template_kwargs = self._prepare_extra_chat_template_kwargs(
request.chat_template_kwargs,
self.default_chat_template_kwargs,
)
reasoning_parser = self.reasoning_parser_cls(
tokenizer,
chat_template_kwargs=chat_template_kwargs, # type: ignore[call-arg]
)
except RuntimeError as e:
logger.exception("Error in reasoning parser creation.")
return self.create_error_response(str(e))
result = await self.render_chat_request(request)
if isinstance(result, ErrorResponse):
return result
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.
engine_prompts[0]["prompt_token_ids"] = request.tokens # type: ignore
request_id = f"chatcmpl-{self._base_request_id(raw_request, request.request_id)}"
request_metadata = RequestResponseMetadata(request_id=request_id)
if raw_request:
raw_request.state.request_metadata = request_metadata
try:
lora_request = self._maybe_get_adapters(request, supports_default_mm_loras=True)
model_name = self.models.model_name(lora_request)
except (ValueError, TypeError, RuntimeError) as e:
logger.exception("Error preparing request components")
return self.create_error_response(e)
# Extract data_parallel_rank from header (router can inject it)
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_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(
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
if request.use_beam_search:
sampling_params = request.to_beam_search_params(max_tokens, self.default_sampling_params)
else:
sampling_params = request.to_sampling_params(
max_tokens,
self.default_sampling_params,
)
self._log_inputs(
sub_request_id,
engine_prompt,
params=sampling_params,
lora_request=lora_request,
)
trace_headers = None if raw_request is None else await self._get_trace_headers(raw_request.headers)
if isinstance(sampling_params, BeamSearchParams):
generator = self.beam_search(
prompt=engine_prompt,
request_id=sub_request_id,
params=sampling_params,
lora_request=lora_request,
trace_headers=trace_headers,
)
else:
reasoning_ended = (
reasoning_parser.is_reasoning_end(prompt_token_ids or []) if reasoning_parser else None
)
generator = self.engine_client.generate(
engine_prompt,
sampling_params,
sub_request_id,
lora_request=lora_request,
trace_headers=trace_headers,
priority=request.priority,
data_parallel_rank=data_parallel_rank,
reasoning_ended=reasoning_ended,
)
generators.append(generator)
except ValueError as e:
return self.create_error_response(e)
assert len(generators) == 1
(result_generator,) = generators
if request.stream:
return self.chat_completion_stream_generator(
request,
result_generator,
request_id,
model_name,
conversation,
tokenizer,
request_metadata,
reasoning_parser,
)
try:
return await self.chat_completion_full_generator(
request,
result_generator,
request_id,
model_name,
conversation,
tokenizer,
request_metadata,
reasoning_parser,
)
except GenerationError:
raise # Let FastAPI's global generation_error_handler handle it
except ValueError as e:
return self.create_error_response(e)
+7 -10
View File
@@ -226,10 +226,8 @@ class PrimeRlServingTokens(ServingTokens):
# but never threads it into the engine, so PD disagg never fires on
# ``/inference/v1/generate`` — decode receives an empty NIXL handshake
# and ends up re-prefilling the prompt locally (~100× slower under
# concurrency). The chat path bridges this via
# ``ChatCompletionRequestWithTokens.to_sampling_params``; we mirror that
# bridge here so the engine's KV connector picks the params up out of
# ``sampling_params.extra_args``.
# concurrency). Bridge it through ``sampling_params.extra_args`` so the
# engine's KV connector picks the params up.
#
# Upstream fix: https://github.com/vllm-project/vllm/pull/42644 — drop
# this block once we pin a vLLM version that includes it.
@@ -300,12 +298,11 @@ class PrimeRlServingTokens(ServingTokens):
model_name: str,
request_metadata: RequestResponseMetadata,
) -> ErrorResponse | GenerateResponse:
# Mirror serving_chat_with_tokens: wrap the result generator to capture
# routed_experts as it streams, defer the rest to upstream, then post-
# process the response into our PrimeRlGenerateResponse subclass so the
# encoded experts surface in the JSON. Skipping the wrapper when the
# engine isn't producing routed experts keeps us a no-op subclass on
# the common path.
# Wrap the result generator to capture routed_experts as it streams,
# defer the rest to upstream, then post-process the response into our
# PrimeRlGenerateResponse subclass so the encoded experts surface in
# the JSON. Skipping the wrapper when the engine isn't producing routed
# experts keeps us a no-op subclass on the common path.
capture: _RoutedExpertsCapture | None = None
if self.model_config.enable_return_routed_experts:
capture = _RoutedExpertsCapture(result_generator)
+23 -17
View File
@@ -1,4 +1,5 @@
import asyncio
import ctypes
import gc
import os
import time
@@ -552,6 +553,7 @@ async def orchestrate(config: OrchestratorConfig):
for sample in samples:
sample.advantage = rollout["advantage"]
sample.reward = rollout["reward"]
sample.env_name = rollout["env_name"]
if config.use_sft_loss:
sample.sft_loss = True
sample_decode_tokens = sum(sample.completion_mask)
@@ -797,6 +799,13 @@ async def orchestrate(config: OrchestratorConfig):
del train_rollouts, train_examples, training_batch, vlm_cache
del results_df, metrics_df
gc.collect()
# Return free glibc heap pages to the OS. numpy/pandas allocate array data
# via malloc (outside Python's allocator), so gc.collect() alone doesn't
# reclaim the RSS. malloc_trim(0) forces glibc to return freed pages.
try:
ctypes.CDLL("libc.so.6").malloc_trim(0)
except Exception as e:
logger.warning(f"malloc_trim(0) failed - RSS may grow unboundedly: {e}")
event_loop_lag_monitor.reset()
@@ -896,19 +905,16 @@ async def setup_rollout_inference_pool(
):
"""Set up rollout inference.
Routing policy is driven by ``config.use_token_client`` and
``config.use_renderer`` (mutually exclusive — config-level validators
block both being True):
Routing policy is driven by ``config.use_renderer``:
- external teacher rollout → MITO (``openai_chat_completions``),
forced regardless of the toggles (config-level validator
rejects ``use_token_client`` / ``use_renderer`` in that case)
- ``use_renderer=True`` → renderer client (``/v1/generate``).
Not allowed for VLMs (validated at config time).
- ``use_token_client=True`` → TITO
(``openai_chat_completions_token``, ``/v1/chat/completions/tokens``).
Default. VLMs land here too.
- both False → MITO (``openai_chat_completions``).
forced regardless of the toggle (config-level validator rejects
``use_renderer`` in that case)
- ``use_renderer=True`` → renderer-backed TITO client (``/v1/generate``).
Default for text-only rollouts. Not allowed for VLMs (validated at
config time).
- ``use_renderer=False`` → MITO (``openai_chat_completions``). VLMs
land here too.
"""
if config.teacher_rollout_model is not None:
logger.info("Using external rollout model (MITO) without renderer client")
@@ -926,6 +932,8 @@ async def setup_rollout_inference_pool(
renderer=config.renderer.name,
tool_parser=config.renderer.tool_parser,
reasoning_parser=config.renderer.reasoning_parser,
preserve_all_thinking=config.renderer.preserve_all_thinking,
preserve_thinking_between_tool_calls=config.renderer.preserve_thinking_between_tool_calls,
)
logger.info(f"Initialized {type(renderer).__name__} for {config.model.name}")
inference_pool = await setup_inference_pool(
@@ -937,19 +945,17 @@ async def setup_rollout_inference_pool(
tool_parser=config.renderer.tool_parser,
reasoning_parser=config.renderer.reasoning_parser,
renderer_pool_size=config.renderer.pool_size,
preserve_all_thinking=config.renderer.preserve_all_thinking,
preserve_thinking_between_tool_calls=config.renderer.preserve_thinking_between_tool_calls,
)
logger.info("Using direct renderer rollout client")
return renderer, inference_pool
train_client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
if config.use_token_client:
logger.info("Using token client (TITO) for rollouts — server-side templating, /v1/chat/completions/tokens")
else:
logger.info("Using MITO (openai_chat_completions) for rollouts")
logger.info("Using MITO (openai_chat_completions) for rollouts")
inference_pool = await setup_inference_pool(
rollout_client_config,
model_name=rollout_model_name,
train_client_type=train_client_type,
train_client_type="openai_chat_completions",
eval_client_type="openai_chat_completions",
)
return None, inference_pool
@@ -337,6 +337,7 @@ def interleave_rollout(
completion_temperatures=[temperature] * len(completion_ids),
teacher_logprobs=None,
advantage=None,
env_name=output["env_name"],
routed_experts=routed_experts,
mm_token_type_ids=None,
)
+13
View File
@@ -14,6 +14,8 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
advantages = [training_example.advantage] * len(input_ids)
position_ids = list(range(len(input_ids)))
mm_token_type_ids = training_example.mm_token_type_ids
assert training_example.env_name != "all", "env_name='all' is reserved for aggregate metric keys"
env_names = [training_example.env_name] * len(input_ids)
# Per-token temperatures: prompt tokens use first completion temp (masked out anyway)
# Default to 1.0 if completion is empty (e.g., model generated only tool calls with no text)
@@ -38,6 +40,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
routed_experts = routed_experts[:seq_len]
if mm_token_type_ids is not None:
mm_token_type_ids = mm_token_type_ids[:seq_len]
env_names = env_names[:seq_len]
assert (
len(input_ids)
@@ -61,6 +64,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
assert len(mm_token_type_ids) == len(input_ids), (
f"mm_token_type_ids: {len(mm_token_type_ids)}, input_ids: {len(input_ids)}"
)
assert len(env_names) == len(input_ids), f"env_names: {len(env_names)}, input_ids: {len(input_ids)}"
return MicroBatch(
input_ids=input_ids,
@@ -72,6 +76,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
temperatures=temperatures,
routed_experts=routed_experts,
mm_token_type_ids=mm_token_type_ids,
env_names=env_names,
# Multimodal fields (Qwen3-VL) - passed through without modification
pixel_values=training_example.pixel_values,
pixel_values_shape=training_example.pixel_values_shape,
@@ -137,6 +142,7 @@ def packed_samples_into_micro_bs(
if bin_content.mm_token_type_ids is None:
bin_content.mm_token_type_ids = []
bin_content.mm_token_type_ids.extend(sample.mm_token_type_ids)
bin_content.env_names.extend(sample.env_names)
bin_content.position_ids.extend(sample.position_ids)
bin_content.lora_num_tokens[idx] += len(sample.input_ids)
break
@@ -161,6 +167,12 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
padding_size = (pad_to_multiple_of - (len(micro_batch.input_ids) % pad_to_multiple_of)) % pad_to_multiple_of
if len(micro_batch.env_names) != len(micro_batch.input_ids):
raise ValueError(
f"MicroBatch.env_names must match input_ids length before padding: "
f"env_names={len(micro_batch.env_names)}, input_ids={len(micro_batch.input_ids)}"
)
if not (pad_to_multiple_of > 1 and padding_size > 0):
return micro_batch
@@ -178,6 +190,7 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
)
if micro_batch.mm_token_type_ids is not None:
micro_batch.mm_token_type_ids.extend([0] * padding_size)
micro_batch.env_names.extend([""] * padding_size)
return micro_batch
+3
View File
@@ -7,6 +7,7 @@ from transformers.configuration_utils import PretrainedConfig
from transformers.models.auto.auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update
from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES
from transformers.models.llama.configuration_llama import LlamaConfig
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
from prime_rl.trainer.models.afmoe import AfmoeConfig, AfmoeForCausalLM
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
@@ -18,6 +19,7 @@ from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, cast_float_and
from prime_rl.trainer.models.llama import LlamaForCausalLM
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
from prime_rl.trainer.models.qwen3 import Qwen3ForCausalLM
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalLM
@@ -34,6 +36,7 @@ AutoConfig.register("qwen3_5_moe_text", Qwen3_5MoeConfig, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, OrderedDict())
_CUSTOM_CAUSAL_LM_MAPPING.register(LlamaConfig, LlamaForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3Config, Qwen3ForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(AfmoeConfig, AfmoeForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(Glm4MoeConfig, Glm4MoeForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(GlmMoeDsaConfig, GlmMoeDsaForCausalLM, exist_ok=True)
+3 -2
View File
@@ -38,6 +38,7 @@ class AttentionConfig:
use_qk_norm: bool
rms_norm_eps: float
qk_norm_type: Literal["per_head", "per_layer"] = "per_head"
output_bias: bool = False
# TODO: Does torch compile support config._attn_implementation forking?
@@ -70,7 +71,7 @@ class FlashAttention(nn.Module):
self.v_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.output_bias)
self.use_qk_norm = config.use_qk_norm
self.qk_norm_type = config.qk_norm_type
if self.use_qk_norm:
@@ -201,7 +202,7 @@ class SDPAAttention(nn.Module):
self.v_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.output_bias)
self.use_qk_norm = config.use_qk_norm
self.qk_norm_type = config.qk_norm_type
if self.use_qk_norm:
+1 -21
View File
@@ -20,25 +20,6 @@ def _get_quack_rmsnorm():
return None
class _ContiguousGrad(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return x
@staticmethod
def backward(ctx, grad):
return grad.contiguous()
def _contiguous_grad(x: torch.Tensor) -> torch.Tensor:
"""Identity in forward, makes gradient contiguous in backward.
Quack's RMSNorm backward kernel requires contiguous gradients (stride[-1]==1)
but upstream ops like attention permute can produce non-contiguous ones.
"""
return _ContiguousGrad.apply(x) if x.requires_grad else x
@dataclass
class RMSNormConfig:
hidden_size: int
@@ -55,8 +36,7 @@ class RMSNorm(nn.Module):
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
quack_fn = _get_quack_rmsnorm() if hidden_states.is_cuda else None
if quack_fn is not None:
out = quack_fn(hidden_states, self.weight, eps=self.variance_epsilon)
return _contiguous_grad(out)
return quack_fn(hidden_states, self.weight, eps=self.variance_epsilon)
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
@@ -0,0 +1,3 @@
from prime_rl.trainer.models.qwen3.modeling_qwen3 import Qwen3ForCausalLM, Qwen3Model, Qwen3PreTrainedModel
__all__ = ["Qwen3ForCausalLM", "Qwen3Model", "Qwen3PreTrainedModel"]
@@ -0,0 +1,263 @@
from typing import Optional, Union
import torch
from torch import Tensor, nn
from transformers.cache_utils import Cache
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import BaseModelOutputWithPast
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
def _get_rope_type(config: Qwen3Config) -> str:
rope_parameters = getattr(config, "rope_parameters", None)
if isinstance(rope_parameters, dict):
return rope_parameters.get("rope_type", rope_parameters.get("type", "default"))
if rope_parameters is not None:
return getattr(rope_parameters, "rope_type", getattr(rope_parameters, "type", "default"))
rope_scaling = getattr(config, "rope_scaling", None)
if isinstance(rope_scaling, dict):
return rope_scaling.get("rope_type", rope_scaling.get("type", "default"))
return "default"
class Qwen3DecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: Qwen3Config, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.layer_type = config.layer_types[layer_idx]
attn_config = AttentionConfig(
hidden_size=config.hidden_size,
head_dim=getattr(config, "head_dim", config.hidden_size // config.num_attention_heads),
num_attention_heads=config.num_attention_heads,
num_key_value_heads=config.num_key_value_heads,
is_causal=True,
attention_bias=config.attention_bias,
output_bias=config.attention_bias,
use_qk_norm=True,
rms_norm_eps=config.rms_norm_eps,
)
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](attn_config)
if self.layer_type == "sliding_attention":
if config._attn_implementation == "sdpa":
raise ValueError("Qwen3 sliding attention is only supported by the custom model with flash attention.")
self.self_attn.sliding_window = config.sliding_window
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
gate_act=config.hidden_act,
bias=False,
)
self.mlp = MLP(mlp_config)
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> torch.FloatTensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
return residual + hidden_states
@auto_docstring
class Qwen3PreTrainedModel(PreTrainedModelPrimeRL):
config: Qwen3Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Qwen3DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_can_compile_fullgraph = True
_supports_attention_backend = True
_can_record_outputs = {
"hidden_states": Qwen3DecoderLayer,
}
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return True
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return True
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
return state_dict
@auto_docstring
class Qwen3Model(Qwen3PreTrainedModel):
def __init__(self, config: Qwen3Config):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.layers = nn.ModuleList(
[Qwen3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
rotary_config = RotaryEmbeddingConfig(
max_position_embeddings=config.max_position_embeddings,
rope_type=_get_rope_type(config),
model_config=config,
)
self.rotary_emb = RotaryEmbedding(rotary_config)
self.gradient_checkpointing = False
self.post_init()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
) -> BaseModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
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)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
cu_seqlens = None
max_seqlen = None
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
hidden_states = self.norm(hidden_states)
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
@auto_docstring
class Qwen3ForCausalLM(Qwen3PreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_gather_output"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = Qwen3Model(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.post_init()
def set_decoder(self, decoder):
self.model = decoder
def get_decoder(self):
return self.model
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
temperature: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
compatibility; prime-rl asserts `use_cache is None` since training does not
perform autoregressive decoding, so this argument is unused.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels used by PrimeRL's wrapped LM head to optionally compute per-token logprobs/entropy.
If not provided, the wrapped LM head returns logits only.
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Per-token temperatures for logprobs/entropy computation when `labels` are provided.
"""
assert use_cache is None, "use_cache is not supported for custom qwen3 for now"
assert past_key_values is None, "past_key_values is not supported for custom qwen3 for now"
outputs: BaseModelOutputWithPast = self.model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
)
hidden_states = outputs.last_hidden_state
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
return self.lm_head(
hidden_states[:, slice_indices, :],
labels[:, slice_indices] if labels is not None else None,
temperature=temperature,
)
def init_buffers_post_meta(self):
buffer_names = [name for name, _ in self.named_buffers()]
if "model.rotary_emb.inv_freq" in buffer_names:
rotary_emb = self.model.rotary_emb
inv_freq, rotary_emb.attention_scaling = rotary_emb.rope_init_fn(
rotary_emb.config, rotary_emb.inv_freq.device
)
rotary_emb.inv_freq.copy_(inv_freq)
__all__ = ["Qwen3ForCausalLM", "Qwen3Model", "Qwen3PreTrainedModel"]
+4
View File
@@ -24,6 +24,7 @@ class TensorMicroBatch(TypedDict):
teacher_logprobs: Float[Tensor, "batch seq"] | None
loss_mask: Bool[Tensor, "batch seq"]
temperatures: Float[Tensor, "batch seq"] # Per-token temperatures
env_names: list[str]
# Batch level
lora_num_tokens: Int[Tensor, "n_loras"]
@@ -108,6 +109,7 @@ class FakeDataLoader:
"inference_logprobs": inference_logprobs.unsqueeze(0),
"teacher_logprobs": None,
"temperatures": torch.ones(input_ids.shape[0]).unsqueeze(0),
"env_names": ["fake"] * input_ids.shape[0],
"loss_mask": loss_mask.unsqueeze(0),
"lora_num_tokens": lora_num_tokens,
"routed_experts": None,
@@ -135,6 +137,7 @@ class FakeDataLoader:
"inference_logprobs": torch.randn(self.seq_len, generator=generator).unsqueeze(0),
"teacher_logprobs": None,
"temperatures": torch.ones(self.seq_len).unsqueeze(0),
"env_names": ["fake"] * self.seq_len,
"loss_mask": torch.ones(self.seq_len, dtype=torch.bool).unsqueeze(0),
"lora_num_tokens": lora_num_tokens,
"routed_experts": None,
@@ -205,6 +208,7 @@ class DataLoader:
else None,
loss_mask=torch.tensor(micro_batch.loss_mask, dtype=torch.bool).unsqueeze(0),
temperatures=torch.tensor(micro_batch.temperatures, dtype=torch.float).unsqueeze(0),
env_names=micro_batch.env_names,
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.frombuffer(bytearray(micro_batch.pixel_values), dtype=torch.float32).reshape(
+19 -9
View File
@@ -104,6 +104,15 @@ def _safe_mean(values: Tensor, mask: Tensor) -> Tensor:
return values[mask].sum() / denom
def compute_importance_ratio_and_mismatch_kl(
trainer_logprobs: Tensor, inference_logprobs: Tensor
) -> tuple[Tensor, Tensor, Tensor]:
log_importance_ratio = trainer_logprobs - inference_logprobs
importance_ratio = torch.exp(log_importance_ratio)
mismatch_kl = importance_ratio - log_importance_ratio - 1
return log_importance_ratio, importance_ratio, mismatch_kl
def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossOutputs:
"""
DPPO+KL loss, combining:
@@ -122,9 +131,11 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
advantages = inputs.advantages
loss_mask = inputs.loss_mask
trainer_probs = torch.exp(trainer_logprobs)
inference_probs = torch.exp(inference_logprobs)
probs_diff = trainer_probs - inference_probs
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
trainer_logprobs, inference_logprobs
)
probs_diff = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
dppo_invalid_mask_high = probs_diff > loss_config.dppo_mask_high
dppo_invalid_mask_low = probs_diff < -loss_config.dppo_mask_low
positive_advantages = advantages > 0
@@ -137,10 +148,6 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
drop_mask = loss_mask & is_masked
keep_mask = loss_mask & ~is_masked
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
@@ -153,7 +160,6 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
loss = (-pg_loss + loss_config.kl_tau * kl_loss).sum()
metrics = {
"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),
@@ -235,7 +241,11 @@ def compute_loss(
teacher_logprobs = [None] * len(trainer_logprobs)
for t_logp, i_logp, teach_logp, adv, mask in zip(
trainer_logprobs, inference_logprobs, teacher_logprobs, advantages, loss_mask
trainer_logprobs,
inference_logprobs,
teacher_logprobs,
advantages,
loss_mask,
):
inputs = LossInputs(
trainer_logprobs=t_logp,
+31 -13
View File
@@ -29,6 +29,7 @@ from prime_rl.utils.logger import setup_logger
from prime_rl.trainer.rl.loss import (
compute_entropy,
compute_loss,
compute_importance_ratio_and_mismatch_kl,
selective_log_softmax,
setup_loss_fn,
shift_tensor_left,
@@ -474,9 +475,27 @@ def train(config: TrainerConfig):
loss.backward()
# Add relevant tensors to tensor dict for logging purposes
tensors["entropy"].append(out["entropy"][loss_mask].detach().to("cpu"))
entropy = out["entropy"][loss_mask].detach().to("cpu")
tensors["entropy/all"].append(entropy)
tensors["loss"].append(loss.detach().to("cpu").unsqueeze(0))
env_names = micro_batch["env_names"]
masked_env_names = [env_name for env_name, keep in zip(env_names, loss_mask.flatten().tolist()) if keep]
env_to_indices: dict[str, list[int]] = {}
for idx, env_name in enumerate(masked_env_names):
env_to_indices.setdefault(env_name, []).append(idx)
for env_name, indices in env_to_indices.items():
tensors[f"entropy/{env_name}"].append(entropy[indices])
if not micro_batch["sft_loss"]:
with torch.no_grad():
_, _, mismatch_kl = compute_importance_ratio_and_mismatch_kl(out["logprobs"], inference_logprobs)
mismatch_kl = mismatch_kl[loss_mask].detach().to("cpu")
tensors["mismatch_kl/all"].append(mismatch_kl)
for env_name, indices in env_to_indices.items():
tensors[f"mismatch_kl/{env_name}"].append(mismatch_kl[indices])
if is_tt_moe_model(model):
load_balance_stats = get_load_balance_stats(model)
for k, v in load_balance_stats.items():
@@ -485,13 +504,12 @@ def train(config: TrainerConfig):
# Add loss tensors to tensor dict for logging purposes
for key, loss_tensor in loss_tensors.items():
loss_tensor = loss_tensor.detach().to("cpu")
tensors[key].append(loss_tensor)
tensors[key].append(loss_tensor.detach().to("cpu"))
# Debug log with *local, micro step* stats
micro_step_message = f"Micro Step {micro_step}/{len(micro_batches)} | Loss: {tensors['loss'][-1].mean().item():.4f} | Entropy: {tensors['entropy'][-1].mean().item():.4f}"
if "mismatch_kl" in tensors:
micro_step_message += f" | Mismatch KL: {tensors['mismatch_kl'][-1].mean().item():.4f}"
micro_step_message = f"Micro Step {micro_step}/{len(micro_batches)} | Loss: {tensors['loss'][-1].mean().item():.4f} | Entropy: {tensors['entropy/all'][-1].mean().item():.4f}"
if not micro_batch["sft_loss"]:
micro_step_message += f" | Mismatch KL: {tensors['mismatch_kl/all'][-1].mean().item():.4f}"
if "max_vio" in tensors:
micro_step_message += f" | Max Vio: {tensors['max_vio'][-1].mean().item():.4f}"
logger.debug(micro_step_message)
@@ -539,9 +557,9 @@ def train(config: TrainerConfig):
# Log step metrics
step_time = time.perf_counter() - step_start_time
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Loss: {tensor_stats['loss/mean']:.4f} | Entropy: {tensor_stats['entropy/mean']:.4f}"
if "mismatch_kl/mean" in tensor_stats:
step_message += f" | Mismatch KL: {tensor_stats['mismatch_kl/mean']:.4f}"
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Loss: {tensor_stats['loss/mean']:.4f} | Entropy: {tensor_stats['entropy/all/mean']:.4f}"
if "mismatch_kl/all/mean" in tensor_stats:
step_message += f" | Mismatch KL: {tensor_stats['mismatch_kl/all/mean']:.4f}"
if grad_norm is not None:
step_message += f" | Grad. Norm: {grad_norm:.4f}"
step_message += f" | LR: {current_lr:.2e} | Throughput: {throughput:.0f} tokens/s | MFU: {mfu:.1f}% | Peak Mem.: {peak_memory:.1f} GiB"
@@ -570,8 +588,8 @@ def train(config: TrainerConfig):
monitor.log(optim_metrics, step=progress.step)
# Compute derived metrics
entropy_mean = tensor_stats.get("entropy/mean", 0.0)
mismatch_kl_mean = tensor_stats.get("mismatch_kl/mean")
entropy_mean = tensor_stats.get("entropy/all/mean", 0.0)
mismatch_kl_mean = tensor_stats.get("mismatch_kl/all/mean")
if mismatch_kl_mean is not None and entropy_mean > 0:
tensor_stats["kl_ent_ratio/mean"] = mismatch_kl_mean / entropy_mean
@@ -605,8 +623,8 @@ def train(config: TrainerConfig):
peak_memory_gib=peak_memory,
learning_rate=current_lr,
mfu=mfu,
entropy=tensor_stats.get("entropy/mean", 0.0),
mismatch_kl=tensor_stats.get("mismatch_kl/mean", 0.0),
entropy=tensor_stats.get("entropy/all/mean", 0.0),
mismatch_kl=tensor_stats.get("mismatch_kl/all/mean", 0.0),
zero_grad_ratio=zero_grad_ratio,
)
# Update run/LoRA metrics
+2
View File
@@ -166,6 +166,8 @@ def train(config: SFTConfig):
renderer=config.renderer.name,
tool_parser=config.renderer.tool_parser,
reasoning_parser=config.renderer.reasoning_parser,
preserve_all_thinking=config.renderer.preserve_all_thinking,
preserve_thinking_between_tool_calls=config.renderer.preserve_thinking_between_tool_calls,
)
if isinstance(renderer, DefaultRenderer):
raise ValueError(
+17 -3
View File
@@ -352,10 +352,16 @@ class Tensors(defaultdict):
def compute_stats(self) -> dict[str, float | int]:
"""Synchronize the tensor statistic across all ranks for each key and compute relevant statistics."""
local_keys = list(self.keys())
gathered_keys: list[list[str] | None] = [None] * dist.get_world_size()
dist.all_gather_object(gathered_keys, local_keys)
keys = sorted({key for rank_keys in gathered_keys if rank_keys is not None for key in rank_keys})
metrics = {}
for key in list(self.keys()):
for key in keys:
# All-gather tensors across steps and ranks (get global distribution)
tensors = torch.cat(self.pop(key), dim=0).to("cuda")
values = self.pop(key, [])
tensors = torch.cat(values, dim=0).to("cuda") if values else torch.empty(0, device="cuda")
assert tensors.ndim == 1, "Can only aggregate 1D tensors"
tensors = flexible_all_gather(tensors)
assert tensors.ndim == 1, "Can only aggregate 1D tensors"
@@ -382,6 +388,11 @@ class Tensors(defaultdict):
return metrics
def _is_env_tensor_stat(key: str, allowed_stats: set[str]) -> bool:
parts = key.split("/")
return len(parts) >= 3 and parts[-1] in allowed_stats
def filter_rl_trainer_tensor_stats_for_wandb(metrics: dict[str, float | int]) -> dict[str, float | int]:
"""Drop noisy per-token distribution keys before sending RL trainer stats to W&B."""
skip_prefixes = ("trainer_probs/", "inference_probs/")
@@ -402,9 +413,12 @@ def filter_rl_trainer_tensor_stats_for_wandb(metrics: dict[str, float | int]) ->
continue
if any(k.startswith(p) for p in skip_prefixes):
continue
if k.startswith("entropy/") and k != "entropy/mean":
if k.startswith("entropy/") and not _is_env_tensor_stat(k, {"mean", "std", "max"}):
continue
if any(k.startswith(p) for p in mean_max_only_prefixes):
if _is_env_tensor_stat(k, {"mean", "std", "max"}):
out[k] = v
continue
if not (k.endswith("/mean") or k.endswith("/max")):
continue
out[k] = v
+2
View File
@@ -11,6 +11,7 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
completion_mask: list[bool]
completion_logprobs: list[float]
completion_temperatures: list[float] # Per-token temperatures used during generation
env_name: str
teacher_logprobs: list[float] | None = None
advantage: float | None = None
reward: float | None = None
@@ -47,6 +48,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
inference_logprobs: list[float]
position_ids: list[int]
temperatures: list[float] # Per-token temperatures used during generation
env_names: list[str]
teacher_logprobs: list[float] | None = None
lora_num_tokens: list[int] | None = None
routed_experts: list[list[list[int]]] | None = None
+24 -9
View File
@@ -62,12 +62,14 @@ class StaticInferencePool:
self,
client_config: ClientConfig,
model_name: str,
train_client_type: str = "openai_chat_completions_token",
train_client_type: str = "openai_chat_completions",
eval_client_type: str = "openai_chat_completions",
renderer_name: str = "auto",
tool_parser: str | None = None,
reasoning_parser: str | None = None,
renderer_pool_size: int | None = None,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
):
renderer_model_name = model_name if train_client_type == "renderer" else None
self._train_clients = setup_clients(
@@ -78,6 +80,8 @@ class StaticInferencePool:
tool_parser=tool_parser,
reasoning_parser=reasoning_parser,
renderer_pool_size=renderer_pool_size,
preserve_all_thinking=preserve_all_thinking,
preserve_thinking_between_tool_calls=preserve_thinking_between_tool_calls,
)
self._eval_clients = setup_clients(client_config, client_type=eval_client_type)
self._admin_clients = setup_admin_clients(client_config)
@@ -123,23 +127,18 @@ class StaticInferencePool:
async def setup_inference_pool(
client_config: ClientConfig,
model_name: str,
train_client_type: str = "openai_chat_completions_token",
train_client_type: str = "openai_chat_completions",
eval_client_type: str = "openai_chat_completions",
renderer_name: str = "auto",
tool_parser: str | None = None,
reasoning_parser: str | None = None,
renderer_pool_size: int | None = None,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
) -> InferencePool:
"""Create an inference pool from config (static or elastic)."""
logger = get_logger()
if train_client_type == "openai_chat_completions_token":
logger.warning(
"Token-in-token-out (TITO) client is enabled for training. Only use "
"this if your environment has a linear history and the chat "
"template has the extension property."
)
if client_config.is_elastic:
from prime_rl.utils.elastic import ElasticInferencePool
@@ -152,6 +151,8 @@ async def setup_inference_pool(
tool_parser=tool_parser,
reasoning_parser=reasoning_parser,
renderer_pool_size=renderer_pool_size,
preserve_all_thinking=preserve_all_thinking,
preserve_thinking_between_tool_calls=preserve_thinking_between_tool_calls,
)
logger.info(
@@ -168,6 +169,8 @@ async def setup_inference_pool(
tool_parser=tool_parser,
reasoning_parser=reasoning_parser,
renderer_pool_size=renderer_pool_size,
preserve_all_thinking=preserve_all_thinking,
preserve_thinking_between_tool_calls=preserve_thinking_between_tool_calls,
)
@@ -179,9 +182,20 @@ def setup_clients(
tool_parser: str | None = None,
reasoning_parser: str | None = None,
renderer_pool_size: int | None = None,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
) -> list[vf.ClientConfig]:
clients = []
client_idx = 0
# Only forward preserve flags when the client actually uses a renderer —
# MITO/TITO clients ignore them and the verifiers ClientConfig may reject
# unknown extras on older versions.
renderer_extra: dict = {}
if client_type == "renderer":
renderer_extra = {
"preserve_all_thinking": preserve_all_thinking,
"preserve_thinking_between_tool_calls": preserve_thinking_between_tool_calls,
}
for base_url in client_config.base_url:
for dp_rank in range(client_config.dp_rank_count):
headers = client_config.headers.copy()
@@ -205,6 +219,7 @@ def setup_clients(
max_retries=10,
extra_headers=headers,
extra_headers_from_state=client_config.extra_headers_from_state,
**renderer_extra,
)
)
client_idx += 1
+12 -2
View File
@@ -104,12 +104,14 @@ class ElasticInferencePool:
self,
client_config: ClientConfig,
model_name: str,
train_client_type: str = "openai_chat_completions_token",
train_client_type: str = "openai_chat_completions",
eval_client_type: str = "openai_chat_completions",
renderer_name: str = "auto",
tool_parser: str | None = None,
reasoning_parser: str | None = None,
renderer_pool_size: int | None = None,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
):
self.logger = get_logger()
self.client_config = client_config
@@ -125,6 +127,8 @@ class ElasticInferencePool:
self.tool_parser = tool_parser
self.reasoning_parser = reasoning_parser
self.renderer_pool_size = renderer_pool_size
self.preserve_all_thinking = preserve_all_thinking
self.preserve_thinking_between_tool_calls = preserve_thinking_between_tool_calls
self.router_url = client_config.router_url
self._servers: dict[str, ServerState] = {}
@@ -146,12 +150,14 @@ class ElasticInferencePool:
cls,
client_config: ClientConfig,
model_name: str,
train_client_type: str = "openai_chat_completions_token",
train_client_type: str = "openai_chat_completions",
eval_client_type: str = "openai_chat_completions",
renderer_name: str = "auto",
tool_parser: str | None = None,
reasoning_parser: str | None = None,
renderer_pool_size: int | None = None,
preserve_all_thinking: bool = False,
preserve_thinking_between_tool_calls: bool = False,
) -> ElasticInferencePool:
if client_config.elastic is None:
raise ValueError("Elastic inference pool requires elastic config")
@@ -164,6 +170,8 @@ class ElasticInferencePool:
tool_parser=tool_parser,
reasoning_parser=reasoning_parser,
renderer_pool_size=renderer_pool_size,
preserve_all_thinking=preserve_all_thinking,
preserve_thinking_between_tool_calls=preserve_thinking_between_tool_calls,
)
await pool.start()
return pool
@@ -214,6 +222,8 @@ class ElasticInferencePool:
tool_parser=self.tool_parser,
reasoning_parser=self.reasoning_parser,
renderer_pool_size=self.renderer_pool_size,
preserve_all_thinking=self.preserve_all_thinking,
preserve_thinking_between_tool_calls=self.preserve_thinking_between_tool_calls,
)
if urls
else []
+26 -3
View File
@@ -6,7 +6,11 @@ from prime_rl.transport.types import TrainingSample
@pytest.fixture
def make_training_example():
def _make_training_example(temperature: float = 1.0, sft_loss: bool = False) -> TrainingSample:
def _make_training_example(
temperature: float = 1.0,
sft_loss: bool = False,
env_name: str = "test-env",
) -> TrainingSample:
return TrainingSample(
prompt_ids=[1, 2],
prompt_mask=[False, False],
@@ -16,12 +20,26 @@ def make_training_example():
completion_temperatures=[temperature, temperature], # Per-token temperatures
teacher_logprobs=[0.0, 0.0, 0.0, 0.0],
advantage=1.0,
env_name=env_name,
sft_loss=sft_loss,
)
return _make_training_example
def test_training_sample_requires_env_name():
with pytest.raises(TypeError, match="env_name"):
TrainingSample(
prompt_ids=[1, 2],
prompt_mask=[False, False],
completion_ids=[3, 4],
completion_mask=[True, True],
completion_logprobs=[-0.1, -0.2],
completion_temperatures=[1.0, 1.0],
advantage=1.0,
)
@pytest.mark.parametrize(
("rollout_count", "num_train_workers", "expected_batches_per_worker"), [(4, 2, 2), (5, 2, 3), (7, 1, 7), (11, 4, 3)]
)
@@ -58,8 +76,8 @@ def test_prepare_batch_balances_micro_batches_across_workers(
def test_prepare_batch_packs_different_temperatures(make_training_example):
"""With per-token temperatures, samples can be packed together regardless of their temperature values."""
example1 = make_training_example(temperature=0.7)
example2 = make_training_example(temperature=1.1)
example1 = make_training_example(temperature=0.7, env_name="env-a")
example2 = make_training_example(temperature=1.1, env_name="env-b")
batches_per_gpu = prepare_batch(
rollouts=[example1, example2],
@@ -78,6 +96,7 @@ def test_prepare_batch_packs_different_temperatures(make_training_example):
assert flat_batches[0].temperatures[:4] == [0.7, 0.7, 0.7, 0.7]
# Second sample (4 tokens): all get temp 1.1
assert flat_batches[0].temperatures[4:8] == [1.1, 1.1, 1.1, 1.1]
assert flat_batches[0].env_names == ["env-a"] * 4 + ["env-b"] * 4
def test_prepare_sample_propagates_sft_loss(make_training_example):
@@ -117,6 +136,7 @@ def test_prepare_sample_with_routed_experts():
completion_logprobs=[-0.1, -0.2],
completion_temperatures=[1.0, 1.0],
advantage=1.0,
env_name="test-env",
routed_experts=routed_experts,
)
@@ -137,6 +157,7 @@ def test_prepare_sample_truncates_routed_experts():
completion_logprobs=[-0.1, -0.2],
completion_temperatures=[1.0, 1.0],
advantage=1.0,
env_name="test-env",
routed_experts=routed_experts,
)
@@ -144,6 +165,7 @@ def test_prepare_sample_truncates_routed_experts():
assert micro_batch.routed_experts is not None
assert len(micro_batch.routed_experts) == 3
assert micro_batch.routed_experts == routed_experts[:3]
assert micro_batch.env_names == ["test-env"] * 3
def test_prepare_sample_none_routed_experts():
@@ -156,6 +178,7 @@ def test_prepare_sample_none_routed_experts():
completion_logprobs=[-0.1, -0.2],
completion_temperatures=[1.0, 1.0],
advantage=1.0,
env_name="test-env",
)
micro_batch = prepare_sample(sample, seq_len=8)
@@ -43,13 +43,14 @@ def test_setup_rollout_inference_pool_uses_direct_renderer_client_for_local_vllm
config = SimpleNamespace(
teacher_rollout_model=None,
use_renderer=True,
use_token_client=False,
model=SimpleNamespace(name="student-model"),
renderer=SimpleNamespace(
name="qwen3_vl",
tool_parser=None,
reasoning_parser=None,
pool_size=None,
preserve_all_thinking=False,
preserve_thinking_between_tool_calls=False,
),
)
rollout_client_config = SimpleNamespace(base_url=["http://localhost:8000/v1"])
@@ -79,6 +80,8 @@ def test_setup_rollout_inference_pool_uses_direct_renderer_client_for_local_vllm
renderer="qwen3_vl",
tool_parser=None,
reasoning_parser=None,
preserve_all_thinking=False,
preserve_thinking_between_tool_calls=False,
)
setup_pool_mock.assert_awaited_once_with(
rollout_client_config,
@@ -89,6 +92,8 @@ def test_setup_rollout_inference_pool_uses_direct_renderer_client_for_local_vllm
tool_parser=None,
reasoning_parser=None,
renderer_pool_size=None,
preserve_all_thinking=False,
preserve_thinking_between_tool_calls=False,
)
asyncio.run(run())
@@ -60,6 +60,7 @@ def test_pretokenize_rollout_trajectory_for_sft():
tokenizer = SimpleChatTokenizer()
output = vf.RolloutOutput(
example_id=42,
env_name="test-env",
trajectory=[
vf.TrajectoryStep(
prompt=[{"role": "user", "content": "U1"}],
@@ -50,6 +50,7 @@ def test_compute_teacher_logprobs_uses_inference_generate(monkeypatch):
completion_mask=[True, True],
completion_logprobs=[-0.1, -0.2],
completion_temperatures=[1.0, 1.0],
env_name="test-env",
)
result = await orchestrator_utils.compute_teacher_logprobs(
@@ -18,6 +18,13 @@ from prime_rl.orchestrator.trajectories import (
interleave_rollout,
)
_interleave_rollout = interleave_rollout
def interleave_rollout(output, *args, **kwargs):
output.setdefault("env_name", "test-env")
return _interleave_rollout(output, *args, **kwargs)
def _pixels(data: list[list[float]]) -> tuple[bytes, list[int]]:
"""Convert pixel values list to (bytes, shape) for test cache data."""
@@ -372,6 +379,7 @@ def test_branching_equivalent_multi_step_trajectory_with_tool_calls(
def test_interleave_rollout_single_step_trajectory(single_step_trajectory_output):
single_step_trajectory_output["env_name"] = "test-env"
rollouts = interleave_rollout(single_step_trajectory_output)
assert rollouts is not None
assert len(rollouts) == 1
@@ -383,6 +391,7 @@ def test_interleave_rollout_single_step_trajectory(single_step_trajectory_output
assert rollout.completion_mask == [True, True]
assert rollout.completion_logprobs == [-0.1, -0.2]
assert rollout.completion_temperatures == [1.0, 1.0]
assert rollout.env_name == "test-env"
def test_interleave_rollout_multi_step_trajectory(multi_step_trajectory_output):
+75
View File
@@ -157,6 +157,81 @@ def test_removed_fused_lm_head_chunk_size_field_is_rejected():
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
def test_orchestrator_vlm_configs_must_disable_renderer():
with pytest.raises(ValidationError, match="orchestrator.use_renderer is not supported for VLMs"):
OrchestratorConfig.model_validate(
{
"model": {
"vlm": {
"vision_encoder_attr": "model.visual",
"language_model_attr": "model.language_model",
}
}
}
)
config = OrchestratorConfig.model_validate(
{
"model": {
"vlm": {
"vision_encoder_attr": "model.visual",
"language_model_attr": "model.language_model",
}
},
"use_renderer": False,
}
)
assert config.use_renderer is False
def test_selective_activation_checkpointing_requires_custom_impl():
with pytest.raises(ValidationError, match="Selective activation checkpointing requires model.impl='custom'"):
TrainerModelConfig.model_validate({"impl": "hf", "ac": {"mode": "selective"}})
def test_orchestrator_renderer_auto_rejects_unmapped_model():
"""use_renderer=True with renderer.name='auto' must reject models not in MODEL_RENDERER_MAP."""
with pytest.raises(ValidationError, match="silently fall back to DefaultRenderer"):
OrchestratorConfig.model_validate({"model": {"name": "not-a-real-org/not-a-real-model"}})
def test_orchestrator_renderer_auto_accepts_mapped_model():
"""The default Qwen model is in MODEL_RENDERER_MAP and should validate cleanly."""
config = OrchestratorConfig.model_validate({"model": {"name": "Qwen/Qwen3-0.6B"}})
assert config.use_renderer is True
assert config.renderer.name == "auto"
def test_orchestrator_explicit_renderer_skips_unmapped_check():
"""Explicit renderer.name bypasses the auto-resolution check — user opted in."""
config = OrchestratorConfig.model_validate(
{
"model": {"name": "not-a-real-org/not-a-real-model"},
"renderer": {"name": "qwen3"},
}
)
assert config.renderer.name == "qwen3"
def test_orchestrator_use_renderer_false_skips_unmapped_check():
"""use_renderer=False means the renderer client isn't used, so MODEL_RENDERER_MAP doesn't apply."""
config = OrchestratorConfig.model_validate(
{
"model": {"name": "not-a-real-org/not-a-real-model"},
"use_renderer": False,
}
)
assert config.use_renderer is False
def test_orchestrator_explicit_default_renderer_with_unmapped_model():
"""renderer.name='default' is an explicit opt-in to DefaultRenderer and must pass."""
config = OrchestratorConfig.model_validate(
{
"model": {"name": "not-a-real-org/not-a-real-model"},
"renderer": {"name": "default", "tool_parser": "qwen3"},
}
)
assert config.renderer.name == "default"
assert config.renderer.tool_parser == "qwen3"
@@ -105,8 +105,8 @@ def test_kl_zero_when_identical():
)
result = default_loss_fn(inputs, DefaultLossConfig())
assert result.metrics["mismatch_kl"].item() == pytest.approx(0.0, abs=1e-6), (
f"Expected zero KL for identical models, got {result.metrics['mismatch_kl'].item()}"
assert result.metrics["unmasked_mismatch_kl"].item() == pytest.approx(0.0, abs=1e-6), (
f"Expected zero KL for identical models, got {result.metrics['unmasked_mismatch_kl'].item()}"
)
@@ -138,7 +138,7 @@ def test_kl_positive_after_perturbation():
loss_mask=loss_mask,
)
result = default_loss_fn(inputs, DefaultLossConfig())
kl = result.metrics["mismatch_kl"].item()
kl = result.metrics["unmasked_mismatch_kl"].item()
assert kl > 0, f"Expected positive KL after perturbation, got {kl}"
assert kl < 100, f"KL unexpectedly large: {kl}"
+15 -10
View File
@@ -117,18 +117,23 @@ def test_qwen3_5_moe_cp_patching():
"""Verify substitute_ring_attn patches Qwen3_5MoeGatedFlashAttention._compute_attention."""
from unittest.mock import MagicMock
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
from prime_rl.trainer.models.layers.attn import FlashAttention, substitute_ring_attn
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
original_method = Qwen3_5MoeGatedFlashAttention._compute_attention
mock_group = MagicMock()
substitute_ring_attn(process_group=mock_group, heads_k_stride=1)
assert Qwen3_5MoeGatedFlashAttention._compute_attention is not original_method
# Restore to avoid polluting other tests
Qwen3_5MoeGatedFlashAttention._compute_attention = original_method
# substitute_ring_attn rewrites _compute_attention on all three classes;
# snapshot every one so the patch can't leak into later tests via the
# untouched siblings.
originals = {
cls: cls._compute_attention for cls in (FlashAttention, AfmoeFlashAttention, Qwen3_5MoeGatedFlashAttention)
}
try:
mock_group = MagicMock()
substitute_ring_attn(process_group=mock_group, heads_k_stride=1)
assert Qwen3_5MoeGatedFlashAttention._compute_attention is not originals[Qwen3_5MoeGatedFlashAttention]
finally:
for cls, method in originals.items():
cls._compute_attention = method
if __name__ == "__main__":
+3
View File
@@ -32,6 +32,8 @@ def create_run_with_config(output_dir: Path, run_name: str) -> Path:
"rollouts_per_example": 1,
"env": [{"id": "test-env"}],
"sampling": {"temperature": 1.0},
# test-model isn't in MODEL_RENDERER_MAP; bypass the renderer-resolution validator.
"use_renderer": False,
}
with open(control_dir / "orch.toml", "wb") as f:
tomli_w.dump(config, f)
@@ -46,6 +48,7 @@ def make_training_sample() -> TrainingSample:
completion_mask=[True],
completion_logprobs=[-0.1],
completion_temperatures=[1.0],
env_name="test-env",
)
+7 -1
View File
@@ -30,7 +30,13 @@ def attn(request) -> AttnImplementation:
@pytest.fixture
def model(attn):
config = ModelConfig(name="Qwen/Qwen3-0.6B", attn=attn)
return get_model(config)
model = get_model(config)
# Mirror setup_model: the custom Qwen3 forward calls lm_head with
# (hidden_states, labels, temperature=...), which only VanillaOutputLinear
# / FusedOutputLinear accept. Plain nn.Linear errors with
# `Linear.forward() got an unexpected keyword argument 'temperature'`.
inject_prime_lm_head(model, chunk_size=None)
return model
def test_model_to_gpu(model):
+4
View File
@@ -42,6 +42,8 @@ def create_run_with_config(
"batch_size": 32,
"rollouts_per_example": 4,
"env": [{"id": "test-env"}],
# test-model isn't in MODEL_RENDERER_MAP; bypass the renderer-resolution validator.
"use_renderer": False,
}
with open(config_dir / "orch.toml", "wb") as f:
@@ -201,6 +203,7 @@ def test_config_loading(tmp_path: Path) -> None:
"max_steps": 1000,
"rollouts_per_example": 4,
"env": [{"id": "test-env"}],
"use_renderer": False,
}
create_run_with_config(tmp_path, "run_test123", config=test_config)
@@ -245,6 +248,7 @@ def test_config_cleanup_on_deletion(tmp_path: Path) -> None:
"batch_size": 16,
"rollouts_per_example": 4,
"env": [{"id": "test-env"}],
"use_renderer": False,
}
run_dir = create_run_with_config(tmp_path, "run_delete_me", config=test_config)
Generated
+56 -25
View File
@@ -15,13 +15,14 @@ conflicts = [[
]]
[options]
exclude-newer = "2026-05-08T23:46:46.215125045Z"
exclude-newer = "2026-05-11T22:34:17.526963383Z"
exclude-newer-span = "P7D"
[options.exclude-newer-package]
vllm = false
vllm-router = false
dion = false
tokenspeed-mla = false
nixl-cu12 = false
deep-ep = false
flash-attn-3 = false
@@ -3871,8 +3872,8 @@ dependencies = [
{ name = "transformers", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "uvloop", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "verifiers", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "vllm", version = "0.20.2+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_aarch64.whl" }, marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine != 'aarch64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "vllm", version = "0.20.2+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_x86_64.whl" }, marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "vllm", version = "0.21.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl" }, marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine != 'aarch64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "vllm", version = "0.21.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl" }, marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "wandb", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
@@ -4004,7 +4005,7 @@ requires-dist = [
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
{ name = "pyarrow", specifier = ">=21.0.0" },
{ name = "pyzmq", specifier = ">=27.1.0" },
{ name = "quack-kernels", marker = "extra == 'quack'", specifier = ">=0.3.3" },
{ name = "quack-kernels", marker = "extra == 'quack'", specifier = ">=0.4.1" },
{ name = "renderers", editable = "deps/renderers" },
{ name = "reverse-text", marker = "extra == 'envs'", editable = "deps/verifiers/environments/reverse_text" },
{ name = "rich", specifier = ">=14.0.0" },
@@ -4023,9 +4024,9 @@ requires-dist = [
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=c1c3424" },
{ name = "uvloop", specifier = ">=0.21.0" },
{ name = "verifiers", editable = "deps/verifiers" },
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64'", specifier = ">=0.20.2" },
{ name = "vllm", marker = "platform_machine == 'aarch64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_aarch64.whl" },
{ name = "vllm", marker = "platform_machine == 'x86_64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_x86_64.whl" },
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64'", specifier = ">=0.21.0" },
{ name = "vllm", marker = "platform_machine == 'aarch64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl" },
{ name = "vllm", marker = "platform_machine == 'x86_64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "wandb", specifier = ">=0.26.1" },
{ name = "wiki-search", marker = "extra == 'envs'", editable = "deps/verifiers/environments/wiki_search" },
@@ -4049,6 +4050,7 @@ source = { editable = "packages/prime-rl-configs" }
dependencies = [
{ name = "pydantic", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "pydantic-config", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "renderers", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tomli", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tomli-w", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
@@ -4057,6 +4059,7 @@ dependencies = [
requires-dist = [
{ name = "pydantic", specifier = ">=1.10.13" },
{ name = "pydantic-config", git = "https://github.com/samsja/pydantic_config.git?branch=main" },
{ name = "renderers", editable = "deps/renderers" },
{ name = "tomli", specifier = ">=2.2.1" },
{ name = "tomli-w", specifier = ">=1.2.0" },
]
@@ -5454,6 +5457,30 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/05/a1/d62dfe7376beaaf1394917e0f8e93ee5f67fea8fcf4107501db35996586b/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:38337540fbbddff8e999d59970f3c6f35a82de10053206a7562f1ea02d046fa5", size = 10033429, upload-time = "2026-01-05T10:45:14.333Z" },
]
[[package]]
name = "tokenspeed-mla"
version = "0.1.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "apache-tvm-ffi", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "nvidia-cutlass-dsl", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tokenspeed-triton", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "torch", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/42/20/4110d624d81d63f0bee2f19dba7ea0e1d8a31ea50147e6c1db82223c88a4/tokenspeed_mla-0.1.2-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:592590f36d85e624ecdc5e357ff35e29e761e6d879900dce8b67a6785c8ce75c", size = 743769, upload-time = "2026-05-13T03:30:54.486Z" },
{ url = "https://files.pythonhosted.org/packages/84/01/4bf8b74ead3e8e7c1c809435396254c067a33fde48acc20f602aae622d97/tokenspeed_mla-0.1.2-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:c9466a351fe039792e56cf49f3e79744c1dc28c7af10306a02e62b8e92fa5985", size = 748681, upload-time = "2026-05-13T03:30:56.718Z" },
]
[[package]]
name = "tokenspeed-triton"
version = "3.7.10.post20260505"
source = { registry = "https://pypi.org/simple" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/71/22/5d882546d461728d2dff369af5185ff1ded7f15c83e013fa6b2a56a86058/tokenspeed_triton-3.7.10.post20260505-cp312-abi3-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:06bad3e25ccaba22bb43eb8499f01008f9aaa0bfb3fbfb0cef1b37d2c006c6f0", size = 82059541, upload-time = "2026-05-05T07:48:59.923Z" },
{ url = "https://files.pythonhosted.org/packages/af/c3/4808d86016368fed9495c3a3408cc7f912e7863ff3432937404bd0a551a6/tokenspeed_triton-3.7.10.post20260505-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:19618c7db01a9bd33885f7acbf8945adb2f5534668aa97629b56d481753cbcad", size = 89127692, upload-time = "2026-05-05T07:49:04.22Z" },
]
[[package]]
name = "toml"
version = "0.10.2"
@@ -5866,8 +5893,8 @@ rl = [
{ name = "requests", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "torch", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "transformers", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "vllm", version = "0.20.2+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_aarch64.whl" }, marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine != 'aarch64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "vllm", version = "0.20.2+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_x86_64.whl" }, marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "vllm", version = "0.21.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl" }, marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine != 'aarch64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "vllm", version = "0.21.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl" }, marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "wandb", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
ta = [
@@ -5941,9 +5968,9 @@ requires-dist = [
{ name = "torch", marker = "extra == 'rl'", specifier = ">=2.8.0,<2.9.0", index = "https://download.pytorch.org/whl/cu128" },
{ name = "transformers", marker = "extra == 'rl'", git = "https://github.com/huggingface/transformers.git?rev=c1c3424" },
{ name = "typing-extensions", marker = "python_full_version < '3.12'" },
{ name = "vllm", marker = "platform_machine == 'aarch64' and extra == 'rl'", url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_aarch64.whl" },
{ name = "vllm", marker = "platform_machine == 'aarch64' and extra == 'rl'", url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl" },
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'rl'", specifier = ">=0.10.0,<0.11.0" },
{ name = "vllm", marker = "platform_machine == 'x86_64' and extra == 'rl'", url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_x86_64.whl" },
{ name = "vllm", marker = "platform_machine == 'x86_64' and extra == 'rl'", url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl" },
{ name = "wandb", marker = "extra == 'rl'" },
]
provides-extras = ["browser", "openenv", "renderers", "rg", "rl", "ta"]
@@ -5986,8 +6013,8 @@ wheels = [
[[package]]
name = "vllm"
version = "0.20.2+cu129"
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_aarch64.whl" }
version = "0.21.0+cu129"
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl" }
resolution-markers = [
"platform_machine == 'aarch64' and sys_platform == 'linux'",
]
@@ -6052,6 +6079,7 @@ dependencies = [
{ name = "tiktoken", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine != 'aarch64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tilelang", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine != 'aarch64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tokenizers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine != 'aarch64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tokenspeed-mla", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine != 'aarch64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine != 'aarch64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "torchaudio", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine != 'aarch64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "torchvision", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine != 'aarch64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
@@ -6062,7 +6090,7 @@ dependencies = [
{ name = "xgrammar", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine != 'aarch64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
wheels = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_aarch64.whl", hash = "sha256:8a58a086c5c4ed2883eee36aaaf6b79c83463d02da3015454acf92afcc8e150e" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:de0af3ab4c0cc86e98712bbe89bb30eae967b5bf87873920b7cf13bbfd096aaa" },
]
[package.metadata]
@@ -6096,14 +6124,14 @@ requires-dist = [
{ name = "matplotlib", marker = "extra == 'bench'" },
{ name = "mcp" },
{ name = "mistral-common", extras = ["audio"], marker = "extra == 'audio'" },
{ name = "mistral-common", extras = ["image"], specifier = ">=1.11.0" },
{ name = "model-hosting-container-standards", specifier = ">=0.1.13,<1.0.0" },
{ name = "mistral-common", extras = ["image"], specifier = ">=1.11.2" },
{ name = "model-hosting-container-standards", specifier = ">=0.1.14,<1.0.0" },
{ name = "msgspec" },
{ name = "ninja" },
{ name = "numba", specifier = "==0.65.0" },
{ name = "numpy" },
{ name = "nvidia-cudnn-frontend", specifier = ">=1.13.0,<1.19.0" },
{ name = "nvidia-cutlass-dsl", specifier = ">=4.4.2" },
{ name = "nvidia-cutlass-dsl", specifier = "==4.4.2" },
{ name = "openai", specifier = ">=2.0.0" },
{ name = "openai-harmony", specifier = ">=0.0.3" },
{ name = "opencv-python-headless", specifier = ">=4.13.0" },
@@ -6147,6 +6175,7 @@ requires-dist = [
{ name = "tiktoken", specifier = ">=0.6.0" },
{ name = "tilelang", specifier = "==0.1.9" },
{ name = "tokenizers", specifier = ">=0.21.1" },
{ name = "tokenspeed-mla", specifier = "==0.1.2" },
{ name = "torch", specifier = "==2.11.0" },
{ name = "torchaudio", specifier = "==2.11.0" },
{ name = "torchvision", specifier = "==0.26.0" },
@@ -6154,15 +6183,15 @@ requires-dist = [
{ name = "transformers", specifier = ">=4.56.0,!=5.0.*,!=5.1.*,!=5.2.*,!=5.3.*,!=5.4.*,!=5.5.0" },
{ name = "typing-extensions", specifier = ">=4.10" },
{ name = "watchfiles" },
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = ">=0.1.32,<1.0.0" },
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = ">=0.2.0,<1.0.0" },
{ name = "zentorch-weekly", marker = "extra == 'zen'", specifier = "==5.2.1.dev20260408" },
]
provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttensor", "runai", "audio", "video", "flashinfer", "helion", "grpc", "otel"]
[[package]]
name = "vllm"
version = "0.20.2+cu129"
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_x86_64.whl" }
version = "0.21.0+cu129"
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl" }
resolution-markers = [
"platform_machine == 'x86_64' and sys_platform == 'linux'",
]
@@ -6227,6 +6256,7 @@ dependencies = [
{ name = "tiktoken", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tilelang", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tokenizers", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tokenspeed-mla", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "torch", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "torchaudio", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "torchvision", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
@@ -6237,7 +6267,7 @@ dependencies = [
{ name = "xgrammar", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
wheels = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_x86_64.whl", hash = "sha256:2f8c2bf2ac6d3d16f930535e66822abd71065468521884eb5b910225b2abef4b" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:920777691e340df7a8328adfb1e57b9996dbb537edfb654dd32f70844f5f423d" },
]
[package.metadata]
@@ -6271,14 +6301,14 @@ requires-dist = [
{ name = "matplotlib", marker = "extra == 'bench'" },
{ name = "mcp" },
{ name = "mistral-common", extras = ["audio"], marker = "extra == 'audio'" },
{ name = "mistral-common", extras = ["image"], specifier = ">=1.11.0" },
{ name = "model-hosting-container-standards", specifier = ">=0.1.13,<1.0.0" },
{ name = "mistral-common", extras = ["image"], specifier = ">=1.11.2" },
{ name = "model-hosting-container-standards", specifier = ">=0.1.14,<1.0.0" },
{ name = "msgspec" },
{ name = "ninja" },
{ name = "numba", specifier = "==0.65.0" },
{ name = "numpy" },
{ name = "nvidia-cudnn-frontend", specifier = ">=1.13.0,<1.19.0" },
{ name = "nvidia-cutlass-dsl", specifier = ">=4.4.2" },
{ name = "nvidia-cutlass-dsl", specifier = "==4.4.2" },
{ name = "openai", specifier = ">=2.0.0" },
{ name = "openai-harmony", specifier = ">=0.0.3" },
{ name = "opencv-python-headless", specifier = ">=4.13.0" },
@@ -6322,6 +6352,7 @@ requires-dist = [
{ name = "tiktoken", specifier = ">=0.6.0" },
{ name = "tilelang", specifier = "==0.1.9" },
{ name = "tokenizers", specifier = ">=0.21.1" },
{ name = "tokenspeed-mla", specifier = "==0.1.2" },
{ name = "torch", specifier = "==2.11.0" },
{ name = "torchaudio", specifier = "==2.11.0" },
{ name = "torchvision", specifier = "==0.26.0" },
@@ -6329,7 +6360,7 @@ requires-dist = [
{ name = "transformers", specifier = ">=4.56.0,!=5.0.*,!=5.1.*,!=5.2.*,!=5.3.*,!=5.4.*,!=5.5.0" },
{ name = "typing-extensions", specifier = ">=4.10" },
{ name = "watchfiles" },
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = ">=0.1.32,<1.0.0" },
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = ">=0.2.0,<1.0.0" },
{ name = "zentorch-weekly", marker = "extra == 'zen'", specifier = "==5.2.1.dev20260408" },
]
provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttensor", "runai", "audio", "video", "flashinfer", "helion", "grpc", "otel"]