Add Qwen 3-8 flash multimodal support (#3916)

Adds native image training to Qwen3.8 Flash Next (`qwen4_exp`) through
Prime-RL’s existing multimodal pipeline.

- Adds the checkpoint-compatible vision encoder and composite model,
merges image features into placeholders, and constructs packed MRoPE
positions.
- Preserves raw token IDs for PLE hashing; CP shards merged embeddings,
token IDs and positions after vision encoding.
- Keeps vision parameter names and checkpoint conversion intact,
including frozen-vision and text-only dummy-forward handling.
- Includes #4259’s validated linear patch projection, learned-position
interpolation and rotary-trig alignment. No fused-head or
hyperconnection experiments.
- Provides Qwen3.5/Qwen3.8 image RL examples using the included
`primeintellect/color-codeword@0.1.0` environment and native `null`
harness, with disjoint training/evaluation slices and comments showing
where to substitute your multimodal environment. Qwen3.8 uses CP8.

Rebased onto main `088570f8` (2026-10-26). Main now supplies #4252’s PLE
memory fix, #4264’s FLA 0.6.0 update and #4279’s new QSA
kernels/activation-checkpoint plan handling.

### Validation

Nebius H200, PyTorch 2.13.0+cu130, exact release kernel wheel
`v0.1.0-b52bd9d`, job **6812**:

- **47 passed:** Qwen3.8 model/meta/checkpoint and VLM checks, Qwen3.5
VLM regressions, activation-checkpoint policies and kernel selection
tests.
- Four fixed-input old/new attention controls include the production
24-query-head / 2-KV-head / 256-dimension geometry, packed/batched
shapes and 2,051 selection slots. Outputs and gradients remain close to
the FP32 reference (roughly 0.21–0.24% relative L2); the new output and
Q/K/V gradients are bitwise identical across three repeats.
- Old/new selector sets match exactly in all three paired controls,
including packed bounds and a CP query offset. The new selector’s order
is repeatable.
- These are component numerical checks, not a full-model KL measurement
or a full-size trainer update. Two-GPU packed-image CP2 + full AC +
compilation also passes forward/backward on both ranks (job 6817), with
finite gradients and outputs matching the unsharded reference within
atol=0.02, rtol=0.03.
- Example follow-up: both previously failing `test_load_configs` cases
pass (**2 passed**). Both configs also load 1,024 shuffled image
training tasks and 128 disjoint evaluation tasks, and resolve
`ColorCodewordEnv` with `NullHarness`. Browser-only fields were replaced
with the native harness's compaction setting. Both examples inherit the
default Prime runtime (no subprocess override); train/eval runtime
resolution was verified. Whitespace checks pass.
- Ruff lint/format and whitespace checks pass. Vision implementation and
vision tests are unchanged from the previously validated PR head. The
examples retain CP8 for Qwen3.8 and use main’s renamed max_staleness
field (8).

Earlier frozen-model validation of the three vision changes used one
eight-image prefix and all 4,545 generated targets, with saved inference
expert replay and stable attention ordering. Exact full-vocabulary KL
fell **0.002570 → 0.001602** with FLA 0.5.2 and **0.002430 → 0.001249**
with FLA 0.6.0. These results predate this main rebase and do not
establish training-wide gains.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> New vision encoder and MRoPE/CP paths affect large-scale RL training
numerics and distributed behavior; mitigated by extensive unit tests but
not full production KL validation in this PR.
> 
> **Overview**
> **Adds native vision-language training for Qwen3.8 Flash Next**
(`qwen4_exp`) on top of Prime-RL’s existing multimodal stack, alongside
doc and example updates for Qwen3.5/Qwen3.8 image RL and SFT.
> 
> The trainer gains a composite **VLM model**: vision encoder
(`model.visual`), image-token scatter into language embeddings, **packed
MRoPE** positions from `mm_token_type_ids` / `image_grid_thw`, and
**context-parallel sharding after** vision merge. PLE still hashes raw
placeholder `input_ids`; checkpoint conversion **keeps** `model.visual`
weights instead of dropping them. `QwenVLAdapter` registers `qwen4_exp`.
> 
> **Docs** list Qwen3.8 in model/VLM tables, add a `qwen3.8` renderer,
and revise multimodal limits (FP32 trainer + BF16 vLLM is OK; monitor
mismatch KL metrics).
> 
> **Examples**: new `rl-qwen3.5.toml` and `rl-qwen3.8.toml` (4×8 H200
trainer + 4 inference replicas, `color-codeword`, GRPO/IPO); expanded
`examples/extra/vlm/README.md`.
> 
> **Tests** cover VLM forward/backward, router replay, MRoPE packing,
and composite checkpoint roundtrip.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b12f244d24b0e86afa8a3746e9f3c1cfdebc3113. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Codex <codex@local>
This commit is contained in:
Hubert
2026-10-27 16:14:14 +01:00
committed by GitHub
co-authored by Cursor Codex
parent 2e382590db
commit 7f528dfc63
18 changed files with 1346 additions and 57 deletions
+2 -1
View File
@@ -33,7 +33,7 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
3. Native integration with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments through the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars), including built-in support for SWE and agentic environments.
4. End-to-end post-training: SFT, RL training, and evals.
5. Multi-node deployment with Slurm support.
6. Multimodal support for VLMs such as Qwen3.5.
6. Multimodal support for Qwen3.5 and Qwen3.8 VLMs, with [image RL and SFT examples](examples/extra/vlm/README.md).
7. Hackable, modular, and extensible by design.
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.3/).
@@ -50,6 +50,7 @@ The trainer runs the PrimeRL model implementations under `src/prime_rl/trainer/m
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
| Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Qwen3.8 Flash Next VLM (`qwen4_exp`) | `Qwen/Qwen3.8-Flash-Next` | yes | ✅ | ✅ |
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
| Muse Glimmer, text only (`muse_glimmer`) | `meta-models/Muse-Glimmer-30B` | no | — | ✅ |
+5 -5
View File
@@ -26,6 +26,7 @@ The trainer only runs `prime-rl`'s own model implementations, selected from the
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
| Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
| Qwen3.8 Flash Next VLM | `Qwen/Qwen3.8-Flash-Next` | ✅ | ✅ |
| Laguna | `poolside/Laguna-XS.2` | ✅ | ✅ |
| MiniMax M2 | `MiniMax/MiniMax-M2` | ✅ | ✅ |
| Muse Glimmer (text only) | `meta-models/Muse-Glimmer-30B` | — | ✅ |
@@ -161,16 +162,15 @@ The built-in VLM registry covers:
|---|---|---|---|
| Qwen3.5 | `qwen3_5` | `model.visual` | `model.language_model` |
| Qwen3.5-MoE | `qwen3_5_moe` | `model.visual` | `model.language_model` |
| Qwen3.8 Flash Next | `qwen4_exp` | `model.visual` | `model.language_model` |
### Enabling VLM Mode
Add `[model.vlm]` and bfloat16 dtypes:
Add `[model.vlm]` to your RL or SFT config:
```toml
[model]
name = "Qwen/Qwen3.5-4B"
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
[model.vlm]
vision_encoder_attr = "model.visual"
@@ -185,8 +185,8 @@ VLM training requires a registered custom PrimeRL implementation.
### Limitations
- **Vision encoder frozen by default.** The default LoRA targets do not match Qwen3.5 vision modules. Set `freeze_vision_encoder = false` to fine-tune the encoder; this is incompatible with LoRA because LoRA freezes all non-adapter parameters.
- **bfloat16 mandatory.** The trainer config validator refuses any other `optimization_dtype` / `reduce_dtype` for VLMs — vLLM serves VLMs in bfloat16 and a mismatch breaks the importance ratio.
- **Higher KL mismatch with multi-image inputs.** Expect noisier `mismatch_kl` than text-only; this is from minor numerical differences between the trainer's and vLLM's image processing.
- **Precision settings are separate.** The examples serve with `inference.vllm.dtype = "bfloat16"` while retaining `trainer.model.optimization_dtype = "float32"` and `reduce_dtype = "float32"`. VLM mode does not require BF16 optimizer state or gradient reduction.
- **Monitor trainer–inference mismatch.** Image encoding, parallel reductions and model kernels can contribute numerical differences. Track `mismatch_kl/all/mean`, `masked_mismatch_kl/mean`, `unmasked_mismatch_kl/mean` and `is_masked/mean` alongside reward.
- **Images aren't logged to monitors.** Sample logging captures the prompt text but not the actual images.
## LoRA Training
+1 -1
View File
@@ -607,7 +607,7 @@ tok.apply_chat_template(messages, tokenize=False)
# (the <think>R1</think> from turn 2 is gone)
```
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `glm-5`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `kimi-k2`, `kimi-k2.5`, `nemotron-3`, `gpt-oss`; anything else falls back to `DefaultRenderer` (a generic `apply_chat_template` wrapper). Pick one via:
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.8`, `glm-5`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `kimi-k2`, `kimi-k2.5`, `nemotron-3`, `gpt-oss`; anything else falls back to `DefaultRenderer` (a generic `apply_chat_template` wrapper). Pick one via:
```toml
[orchestrator.renderer]
+2 -2
View File
@@ -204,9 +204,9 @@ clear_thinking = true
The same config selects the renderer for RL under `[orchestrator.renderer]`. The [`renderers` README](https://github.com/PrimeIntellect-ai/renderers#custom-renderers) shows the class behind this example.
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5.
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, Qwen3.8, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5/Qwen3.8.
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE).
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) only works for models with a registered PrimeRL VLM class: Qwen3.5 dense and MoE, and Qwen3.8 Flash Next (`qwen4_exp`, text and images). See the [multimodal examples](../examples/extra/vlm/README.md) for SFT and multi-node image RL configurations.
See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectories) for the full picture.
+1 -1
View File
@@ -31,7 +31,7 @@ Walk-throughs for the core environments (baseline eval → optional SFT warmup
Examples that don't follow the basic eval → SFT → RL walk-through pattern:
- [`dynamo/`](extra/dynamo/README.md) — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
- [`vlm/`](extra/vlm/README.md) — multimodal (VLM) SFT, dense + MoE LoRA configs
- [`vlm/`](extra/vlm/README.md) — Qwen3.5 / Qwen3.8 multi-node image RL and dense + MoE LoRA SFT
## Related config folders
+29 -12
View File
@@ -1,22 +1,39 @@
# VLM SFT
# Vision-language training
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training (`[model.vlm]` set) requires a PrimeRL VLM implementation (see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
RL and SFT examples for the custom [PrimeRL VLM implementations](../../../docs/advanced.md#multimodal-training).
## Image RL
| Config | Model | Batch / group | CP |
|---|---|---|---|
| [`rl-qwen3.5.toml`](rl-qwen3.5.toml) | `Qwen/Qwen3.5-122B-A10B` | 336 / 16 | 4 |
| [`rl-qwen3.8.toml`](rl-qwen3.8.toml) | `Qwen/Qwen3.8-Flash-Next` | 256 / 16 | 8 |
Both target **4 trainer + 4 inference nodes**, each with 8× H200 GPUs.
The examples use `primeintellect/color-codeword` with separate training and evaluation task slices. Replace it with your multimodal environment and compatible harness, and update run/W&B names and the shared output path. Install environments with `uv sync --all-extras --all-packages` and export any credentials they require.
After [setup](../../../README.md#setup), validate from a shared checkout:
```bash
uv run rl @ examples/extra/vlm/rl-qwen3.8.toml --dry-run
```
Remove `--dry-run` to submit; swap in `rl-qwen3.5.toml` for Qwen3.5. See [Scaling](../../../docs/scaling.md) for Slurm configuration and [Training](../../../docs/training.md) for monitoring and resume.
## SFT
Both configs use LoRA with a frozen vision encoder and assistant-only loss masking.
| Config | Model | Hardware |
|---|---|---|
| [`sft.toml`](sft.toml) | `Qwen/Qwen3.5-0.8B` (dense, LoRA rank 16) | tiny — sanity-scale (20 steps) |
| [`sft-moe.toml`](sft-moe.toml) | `Qwen/Qwen3.6-35B-A3B` (MoE, LoRA rank 32, `ep = 8`) | one 8-GPU node (`num_train_gpus = 8`) |
| [`sft.toml`](sft.toml) | `Qwen/Qwen3.5-0.8B` (dense, LoRA rank 16) | sanity-scale, 20 steps |
| [`sft-moe.toml`](sft-moe.toml) | `Qwen/Qwen3.6-35B-A3B` (MoE, LoRA rank 32, EP8) | one 8-GPU node |
## Run it
Point `data.name` at your multimodal chat dataset (HF dataset with a `messages` column — see [Training § Dataset Format](../../../docs/training.md#dataset-format)), then:
Set `data.name` to your [multimodal chat dataset](../../../docs/training.md#dataset-format), then:
```bash
uv run sft @ examples/extra/vlm/sft.toml
```
Notes:
- The MoE config declares `[deployment]` with `num_train_gpus = 8`; keep its `ep` in sync with the GPU count.
- `micro_batch_size = 1` is required for VLM SFT — do not raise it.
- Checkpoints land in `<run_dir>/checkpoints/step_<N>`; export HF-format weights with `tools/convert_dcp_to_bf16.py` (see [Training](../../../docs/training.md)).
Keep `micro_batch_size = 1` for VLM SFT and the MoE config's EP degree aligned with its GPU count. See [Training](../../../docs/training.md) for checkpoint export.
+183
View File
@@ -0,0 +1,183 @@
# Qwen3.5 image RL: 4 trainer + 4 inference nodes, each with 8 H200 GPUs.
# Customize the environment IDs, W&B names and shared paths before launching.
seq_len = 237568
max_steps = 200
output_dir = "/shared/outputs"
[run]
name = "your-run-name"
[model]
name = "Qwen/Qwen3.5-122B-A10B"
[model.vlm]
language_model_attr = "model.language_model"
vision_encoder_attr = "model.visual"
freeze_vision_encoder = true
[deployment]
type = "multi_node"
gpus_per_node = 8
num_train_nodes = 4
num_infer_nodes = 1
num_infer_replicas = 4
orchestrator_on_inference = true
[slurm]
time = "7-00:00:00"
job_name = "your-run-name"
[ckpt]
interval = 10
keep_last = 1
keep_interval = 200
[weight_broadcast]
type = "nccl"
timeout = 7200
[trainer]
dist_timeout_seconds = 7200
enable_router_replay = true
[trainer.model]
cp = 4
ep = 8
attn = "flash_attention_3"
offload = "optimizer"
optimization_dtype = "float32"
reduce_dtype = "float32"
freeze_moe_router = false
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
mode = "full"
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.model.compile]
fullgraph = false
[trainer.optim]
type = "muon"
lr = 1e-6
mu = 0.95
betas1 = 0.9
betas2 = 0.95
weight_decay = 0.01
max_norm = 1.0
[trainer.scheduler]
type = "constant"
[trainer.log]
level = "info"
[monitors.wandb]
entity = "your-wandb-entity"
project = "your-wandb-project"
name = "your-run-name"
[monitors.file]
path = "metrics.jsonl"
compress = true
float_decimals = 6
[inference]
enable_fp32_lm_head = true
enable_fp32_router_logits = true
[inference.vllm]
seed = 0
dtype = "bfloat16"
max_model_len = 237568
max_num_seqs = 256
max_num_batched_tokens = 8192
tensor_parallel_size = 4
data_parallel_size = 2
enable_expert_parallel = true
all2all_backend = "allgather_reducescatter"
gpu_memory_utilization = 0.85
mm_encoder_tp_mode = "data"
mm_processor_cache_gb = 128
mm_processor_cache_type = "lru"
mamba_cache_dtype = "float32"
enable_prefix_caching = true
enable_auto_tool_choice = true
tool_call_parser = "qwen3_coder"
reasoning_parser = "None"
safetensors_load_strategy = "prefetch"
enable_return_routed_experts = true
[inference.router]
type = "vllm-router"
policy = "sticky_least_loaded"
[inference.env_vars]
VLLM_ENGINE_READY_TIMEOUT_S = "7200"
[orchestrator]
batch_size = 336
max_staleness = 8
# Adaptive episode cap: starts at 96 and grows or backs off with engine pressure.
[orchestrator.concurrency]
initial_inflight = 96
max_inflight = 512
[orchestrator.renderer]
name = "qwen3.5"
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
type = "grpo"
# Cycle through the task catalog in a seeded shuffled order.
[orchestrator.train.select]
shuffle = true
seed = 0
[orchestrator.train.sampling]
temperature = 1.0
top_p = 1.0
max_completion_tokens = 16384
[orchestrator.train.sampling.extra_body]
min_p = 0.0
top_k = -1
return_token_ids = true
[trainer.loss]
type = "ipo"
eps = 0.3
adv_tau = 1.0
max_importance_ratio = 10000.0
# Replace color-codeword with your multimodal environment and compatible harness.
[[orchestrator.train.source]]
name = "color-codeword"
select.include.idx = ["0:1024"]
env.taskset.id = "primeintellect/color-codeword@0.1.0"
env.agent.harness.id = "null"
env.agent.harness.compaction.summarize_at_tokens = 184320
[orchestrator.eval]
interval = 10
group_size = 2
skip_first_step = false
retrigger_on_resume = true
[orchestrator.eval.sampling]
temperature = 1.0
top_p = 1.0
max_tokens = 16384
[[orchestrator.eval.source]]
name = "color-codeword-eval"
select.include.idx = ["1024:1152"]
env.taskset.id = "primeintellect/color-codeword@0.1.0"
env.agent.harness.id = "null"
env.agent.harness.compaction.summarize_at_tokens = 184320
+189
View File
@@ -0,0 +1,189 @@
# Qwen3.8 image RL: 4 trainer + 4 inference nodes, each with 8 H200 GPUs.
# Customize the environment IDs, W&B names and shared paths before launching.
seq_len = 237568
max_steps = 200
output_dir = "/shared/outputs"
[run]
name = "your-run-name"
[model]
name = "Qwen/Qwen3.8-Flash-Next"
[model.vlm]
language_model_attr = "model.language_model"
vision_encoder_attr = "model.visual"
freeze_vision_encoder = true
[deployment]
type = "multi_node"
gpus_per_node = 8
num_train_nodes = 4
num_infer_nodes = 1
num_infer_replicas = 4
orchestrator_on_inference = true
[slurm]
time = "7-00:00:00"
job_name = "your-run-name"
[ckpt]
interval = 10
keep_last = 1
keep_interval = 200
[weight_broadcast]
type = "nccl"
timeout = 7200
[trainer]
dist_timeout_seconds = 7200
enable_router_replay = true
[trainer.model]
cp = 8
ep = 8
attn = "flash_attention_3"
offload = "optimizer"
optimization_dtype = "float32"
reduce_dtype = "float32"
freeze_moe_router = false
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
mode = "full"
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.model.compile]
fullgraph = false
[trainer.optim]
type = "muon"
lr = 1e-6
mu = 0.95
betas1 = 0.9
betas2 = 0.95
weight_decay = 0.01
max_norm = 1.0
[trainer.scheduler]
type = "constant"
[trainer.log]
level = "info"
[monitors.wandb]
entity = "your-wandb-entity"
project = "your-wandb-project"
name = "your-run-name"
[monitors.file]
path = "metrics.jsonl"
compress = true
float_decimals = 6
[inference]
enable_fp32_lm_head = true
enable_fp32_router_logits = true
[inference.vllm]
seed = 0
dtype = "bfloat16"
max_model_len = 237568
max_num_seqs = 256
max_num_batched_tokens = 8192
tensor_parallel_size = 4
data_parallel_size = 2
enable_expert_parallel = true
all2all_backend = "allgather_reducescatter"
gpu_memory_utilization = 0.85
mm_encoder_tp_mode = "data"
mm_processor_cache_gb = 128
mm_processor_cache_type = "lru"
mamba_cache_dtype = "float32"
enable_prefix_caching = true
enable_auto_tool_choice = true
tool_call_parser = "qwen3_coder"
reasoning_parser = "qwen3"
safetensors_load_strategy = "prefetch"
enable_return_routed_experts = true
[inference.vllm.engram_config]
cpu_offload = true
[inference.router]
type = "vllm-router"
policy = "sticky_least_loaded"
[inference.env_vars]
VLLM_ENGINE_READY_TIMEOUT_S = "7200"
[orchestrator]
batch_size = 256
max_staleness = 8
# Adaptive episode cap: starts at 96 and grows or backs off with engine pressure.
[orchestrator.concurrency]
initial_inflight = 96
max_inflight = 512
[orchestrator.renderer]
name = "qwen3.8"
enable_thinking = true
preserve_thinking = true
reasoning_effort = "xhigh"
[orchestrator.train]
group_size = 16
[orchestrator.train.algo]
type = "grpo"
# Cycle through the task catalog in a seeded shuffled order.
[orchestrator.train.select]
shuffle = true
seed = 0
[orchestrator.train.sampling]
temperature = 1.0
top_p = 1.0
max_completion_tokens = 16384
[orchestrator.train.sampling.extra_body]
min_p = 0.0
top_k = -1
return_token_ids = true
[trainer.loss]
type = "ipo"
eps = 0.3
adv_tau = 1.0
max_importance_ratio = 10000.0
# Replace color-codeword with your multimodal environment and compatible harness.
[[orchestrator.train.source]]
name = "color-codeword"
select.include.idx = ["0:1024"]
env.taskset.id = "primeintellect/color-codeword@0.1.0"
env.agent.harness.id = "null"
env.agent.harness.compaction.summarize_at_tokens = 184320
[orchestrator.eval]
interval = 10
group_size = 2
skip_first_step = false
retrigger_on_resume = true
[orchestrator.eval.sampling]
temperature = 1.0
top_p = 1.0
max_tokens = 16384
[[orchestrator.eval.source]]
name = "color-codeword-eval"
select.include.idx = ["1024:1152"]
env.taskset.id = "primeintellect/color-codeword@0.1.0"
env.agent.harness.id = "null"
env.agent.harness.compaction.summarize_at_tokens = 184320
+1 -1
View File
@@ -8,7 +8,7 @@ from prime_rl.multimodal.base import ForwardPolicy, MaterializedMM, required_ten
class QwenVLAdapter:
model_types = frozenset({"qwen3_vl", "qwen3_vl_moe", "qwen3_5", "qwen3_5_moe"})
model_types = frozenset({"qwen3_vl", "qwen3_vl_moe", "qwen3_5", "qwen3_5_moe", "qwen4_exp"})
forward_policy = ForwardPolicy(
pass_position_ids=False,
requires_mm_token_type_ids=True,
@@ -2,17 +2,19 @@ from prime_rl.trainer.models.qwen3_8_flash_next.attention import IndexedGatedAtt
from prime_rl.trainer.models.qwen3_8_flash_next.configuration_qwen3_8_flash_next import (
Qwen3_8FlashNextConfig,
Qwen3_8FlashNextTextConfig,
Qwen3_8FlashNextVisionConfig,
)
from prime_rl.trainer.models.qwen3_8_flash_next.hyper_connection import ExpandedRMSNorm, HyperConnection
from prime_rl.trainer.models.qwen3_8_flash_next.modeling_qwen3_8_flash_next import (
Qwen3_8FlashNextDecoderLayer,
Qwen3_8FlashNextForCausalLM,
Qwen3_8FlashNextModel,
Qwen3_8FlashNextTextModel,
Qwen3_8FlashNextVLMModel,
)
from prime_rl.trainer.models.qwen3_8_flash_next.ngram_embedding import NGramEmbedding
from prime_rl.trainer.models.qwen3_8_flash_next.position_learning import PositionLearningEnhancement
from prime_rl.trainer.models.qwen3_8_flash_next.rotary_embedding import RotaryEmbedding
from prime_rl.trainer.models.qwen3_8_flash_next.vision import Qwen3_8FlashNextVisionModel
__all__ = [
"ExpandedRMSNorm",
@@ -23,8 +25,10 @@ __all__ = [
"Qwen3_8FlashNextConfig",
"Qwen3_8FlashNextDecoderLayer",
"Qwen3_8FlashNextForCausalLM",
"Qwen3_8FlashNextModel",
"Qwen3_8FlashNextTextConfig",
"Qwen3_8FlashNextTextModel",
"Qwen3_8FlashNextVisionConfig",
"Qwen3_8FlashNextVisionModel",
"Qwen3_8FlashNextVLMModel",
"RotaryEmbedding",
]
@@ -125,25 +125,67 @@ class Qwen3_8FlashNextTextConfig(PretrainedConfig):
)
class Qwen3_8FlashNextVisionConfig(PretrainedConfig):
model_type = "qwen4_exp_vision"
base_config_key = "vision_config"
def __init__(
self,
depth: int = 27,
hidden_size: int = 1152,
hidden_act: str = "gelu_pytorch_tanh",
intermediate_size: int = 4304,
num_heads: int = 16,
in_channels: int = 3,
patch_size: int = 16,
spatial_merge_size: int = 2,
temporal_patch_size: int = 2,
out_hidden_size: int = 2560,
num_position_embeddings: int = 2304,
initializer_range: float = 0.02,
**kwargs,
) -> None:
self.depth = depth
self.hidden_size = hidden_size
self.hidden_act = hidden_act
self.intermediate_size = intermediate_size
self.num_heads = num_heads
self.in_channels = in_channels
self.patch_size = patch_size
self.spatial_merge_size = spatial_merge_size
self.temporal_patch_size = temporal_patch_size
self.out_hidden_size = out_hidden_size
self.num_position_embeddings = num_position_embeddings
self.initializer_range = initializer_range
super().__init__(**kwargs)
class Qwen3_8FlashNextConfig(PretrainedConfig):
"""Vision-language composite: a Qwen3.8 Flash Next language model fed by a vision encoder."""
model_type = "qwen4_exp"
sub_configs = {"text_config": Qwen3_8FlashNextTextConfig}
sub_configs = {"text_config": Qwen3_8FlashNextTextConfig, "vision_config": Qwen3_8FlashNextVisionConfig}
def __init__(
self,
text_config: Qwen3_8FlashNextTextConfig | dict | None = None,
vision_config: Qwen3_8FlashNextVisionConfig | dict | None = None,
image_token_id: int = 248056,
vision_start_token_id: int = 248053,
vision_end_token_id: int = 248054,
tie_word_embeddings: bool = False,
**kwargs,
) -> None:
if isinstance(text_config, dict):
text_config = Qwen3_8FlashNextTextConfig(**text_config)
self.text_config = text_config or Qwen3_8FlashNextTextConfig()
if isinstance(vision_config, dict):
vision_config = Qwen3_8FlashNextVisionConfig(**vision_config)
self.vision_config = vision_config or Qwen3_8FlashNextVisionConfig()
self.image_token_id = image_token_id
self.vision_start_token_id = vision_start_token_id
self.vision_end_token_id = vision_end_token_id
kwargs.pop("vision_config", None)
kwargs.pop("image_token_id", None)
kwargs.pop("video_token_id", None)
kwargs.pop("vision_start_token_id", None)
kwargs.pop("vision_end_token_id", None)
kwargs.pop("language_model_only", None)
kwargs.setdefault("pad_token_id", self.text_config.pad_token_id)
kwargs.setdefault("bos_token_id", self.text_config.bos_token_id)
@@ -151,4 +193,4 @@ class Qwen3_8FlashNextConfig(PretrainedConfig):
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
__all__ = ["Qwen3_8FlashNextConfig", "Qwen3_8FlashNextTextConfig"]
__all__ = ["Qwen3_8FlashNextConfig", "Qwen3_8FlashNextTextConfig", "Qwen3_8FlashNextVisionConfig"]
@@ -54,10 +54,7 @@ def is_prime_state_dict(state_dict: dict[str, Tensor]) -> bool:
def conversion_chain(config) -> list[ConvOp]:
text_config = getattr(config, "text_config", config)
model_prefix = "model.language_model" if hasattr(config, "text_config") else "model"
operations: list[ConvOp] = [
Drop("model.visual.", is_prefix=True),
Drop("mtp.", is_prefix=True),
]
operations: list[ConvOp] = [Drop("mtp.", is_prefix=True)]
for layer_index in range(text_config.num_hidden_layers):
prefix = f"{model_prefix}.layers.{layer_index}.mlp"
@@ -1,8 +1,9 @@
import torch
from torch import Tensor, nn
from transformers.modeling_outputs import BaseModelOutput
from transformers.utils import torch_compilable_check
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL, count_active_params
from prime_rl.trainer.models.layers.gated_delta_net import GatedDeltaNet
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, VanillaOutputLinear
from prime_rl.trainer.models.layers.moe import MoE
@@ -21,7 +22,9 @@ from prime_rl.trainer.models.qwen3_8_flash_next.hyper_connection import Expanded
from prime_rl.trainer.models.qwen3_8_flash_next.moe import SigmoidOutputGatedMoE
from prime_rl.trainer.models.qwen3_8_flash_next.ngram_embedding import NGramEmbedding
from prime_rl.trainer.models.qwen3_8_flash_next.position_learning import PositionLearningEnhancement
from prime_rl.trainer.models.qwen3_8_flash_next.rotary_embedding import RotaryEmbedding
from prime_rl.trainer.models.qwen3_8_flash_next.rotary_embedding import RotaryEmbedding, build_mrope_position_ids
from prime_rl.trainer.models.qwen3_8_flash_next.vision import Qwen3_8FlashNextVisionModel
from prime_rl.utils.cp import CPContext, shard_for_cp, shard_position_ids_for_cp
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
@@ -176,12 +179,17 @@ class Qwen3_8FlashNextTextModel(Qwen3_8FlashNextPreTrainedModel):
self,
input_ids: torch.LongTensor,
position_ids: torch.LongTensor | None = None,
inputs_embeds: torch.Tensor | None = None,
routed_experts: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> BaseModelOutput:
inputs_embeds = self.embed_tokens(input_ids)
"""``input_ids`` are always required, image placeholders included: PLE hashes their n-grams even when
``inputs_embeds`` carries the image embeddings. ``position_ids`` is ``[batch, seq]`` or ``[3, batch, seq]``
MRoPE positions."""
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)
@@ -206,10 +214,16 @@ class Qwen3_8FlashNextTextModel(Qwen3_8FlashNextPreTrainedModel):
return BaseModelOutput(last_hidden_state=hidden_states)
class Qwen3_8FlashNextModel(nn.Module):
class Qwen3_8FlashNextVLMModel(nn.Module):
"""Composite (``qwen4_exp``) model: image embeddings replace the image placeholder embeddings, while PLE keeps
hashing the raw placeholder ids."""
def __init__(self, config: Qwen3_8FlashNextConfig) -> None:
super().__init__()
self.config = config
self.visual = Qwen3_8FlashNextVisionModel(config.vision_config)
self.language_model = Qwen3_8FlashNextTextModel(config.text_config)
self.cp_context = CPContext()
def get_input_embeddings(self) -> nn.Embedding:
return self.language_model.get_input_embeddings()
@@ -217,18 +231,89 @@ class Qwen3_8FlashNextModel(nn.Module):
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
self.language_model.set_input_embeddings(embeddings)
def prepare_inputs(
self,
input_ids: torch.LongTensor,
position_ids: torch.LongTensor | None,
pixel_values: torch.Tensor | None,
image_grid_thw: torch.LongTensor | None,
mm_token_type_ids: torch.LongTensor | None,
seq_lens: torch.LongTensor,
) -> tuple[torch.Tensor, torch.LongTensor]:
vision_config = self.config.vision_config
inputs_embeds = self.language_model.embed_tokens(input_ids)
has_images = pixel_values is not None
vision_grid = image_grid_thw
if has_images:
pixel_values = pixel_values.to(self.visual.dtype)
else:
merge_size = vision_config.spatial_merge_size
patch_dim = vision_config.in_channels * vision_config.temporal_patch_size * vision_config.patch_size**2
pixel_values = torch.zeros(merge_size**2, patch_dim, device=inputs_embeds.device, dtype=self.visual.dtype)
vision_grid = torch.tensor([[1, merge_size, merge_size]], device=inputs_embeds.device)
image_embeds = self.visual(pixel_values, vision_grid).pooler_output.to(inputs_embeds.dtype)
if has_images:
image_mask = input_ids == self.config.image_token_id
torch_compilable_check(
image_mask.sum() * inputs_embeds.shape[-1] == image_embeds.numel(),
"Image features and image tokens do not match",
)
inputs_embeds = inputs_embeds.masked_scatter(
image_mask.unsqueeze(-1).expand_as(inputs_embeds), image_embeds
)
else:
# Every rank must retain the vision graph so FSDP collectives stay symmetric.
inputs_embeds = inputs_embeds + image_embeds.sum() * 0.0
if position_ids is None:
if image_grid_thw is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
else:
if mm_token_type_ids is None:
raise ValueError("mm_token_type_ids are required with Qwen3.8 Flash Next image inputs")
position_ids = build_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=vision_config.spatial_merge_size,
seq_lens=seq_lens,
)
return inputs_embeds, position_ids
def forward(
self,
input_ids: torch.LongTensor,
position_ids: torch.LongTensor | None = None,
pixel_values: torch.Tensor | None = None,
image_grid_thw: torch.LongTensor | None = None,
mm_token_type_ids: torch.LongTensor | None = None,
routed_experts: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
) -> BaseModelOutput:
inputs_embeds, position_ids = self.prepare_inputs(
input_ids,
position_ids,
pixel_values,
image_grid_thw,
mm_token_type_ids,
seq_lens,
)
if image_grid_thw is not None and self.cp_context.cp_enabled:
rank, world_size = self.cp_context.cp_rank, self.cp_context.cp_world_size
inputs_embeds = shard_for_cp(inputs_embeds, cp_rank=rank, cp_world_size=world_size)
input_ids = shard_for_cp(input_ids, cp_rank=rank, cp_world_size=world_size)
position_ids = shard_position_ids_for_cp(position_ids, cp_rank=rank, cp_world_size=world_size)
if routed_experts is not None:
routed_experts = shard_for_cp(routed_experts, cp_rank=rank, cp_world_size=world_size)
seq_lens_are_pre_shard = True
return self.language_model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
@@ -241,10 +326,10 @@ class Qwen3_8FlashNextForCausalLM(Qwen3_8FlashNextPreTrainedModel):
def __init__(self, config: Qwen3_8FlashNextConfig) -> None:
super().__init__(config)
text_config = getattr(config, "text_config", config)
self.model = (
Qwen3_8FlashNextModel(config) if hasattr(config, "text_config") else Qwen3_8FlashNextTextModel(config)
)
self.is_vlm = hasattr(config, "vision_config")
text_config = config.text_config if self.is_vlm else config
self.model = Qwen3_8FlashNextVLMModel(config) if self.is_vlm else Qwen3_8FlashNextTextModel(config)
self.supports_packed_multimodal_training = self.is_vlm
self.vocab_size = text_config.vocab_size
self.num_experts = text_config.num_experts
self.num_experts_per_tok = text_config.num_experts_per_tok
@@ -257,6 +342,11 @@ class Qwen3_8FlashNextForCausalLM(Qwen3_8FlashNextPreTrainedModel):
def set_input_embeddings(self, embeddings: nn.Embedding) -> None:
self.model.set_input_embeddings(embeddings)
def num_active_params(self) -> int:
if not self.is_vlm:
return super().num_active_params()
return super().num_active_params() - count_active_params(self, self.model.visual.parameters())
def forward(
self,
input_ids: torch.LongTensor,
@@ -266,18 +356,33 @@ class Qwen3_8FlashNextForCausalLM(Qwen3_8FlashNextPreTrainedModel):
temperature: torch.Tensor | None = None,
sampling_mask: torch.Tensor | None = None,
routed_experts: torch.LongTensor | None = None,
pixel_values: torch.Tensor | None = None,
image_grid_thw: torch.LongTensor | None = None,
mm_token_type_ids: torch.LongTensor | None = None,
*,
seq_lens: torch.LongTensor,
seq_lens_are_pre_shard: bool = False,
**kwargs,
) -> PrimeLmOutput:
outputs = self.model(
input_ids=input_ids,
position_ids=position_ids,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
if self.is_vlm:
outputs = self.model(
input_ids=input_ids,
position_ids=position_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
else:
outputs = self.model(
input_ids=input_ids,
position_ids=position_ids,
routed_experts=routed_experts,
seq_lens=seq_lens,
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
)
if isinstance(logits_to_keep, int):
slice_indices = slice(-logits_to_keep, None) if logits_to_keep > 0 else slice(None)
else:
@@ -290,8 +395,10 @@ class Qwen3_8FlashNextForCausalLM(Qwen3_8FlashNextPreTrainedModel):
)
def init_buffers_post_meta(self) -> None:
language_model = getattr(self.model, "language_model", self.model)
language_model = self.model.language_model if self.is_vlm else self.model
language_model.rotary_emb.reset_parameters()
if self.is_vlm:
self.model.visual.rotary_pos_emb.reset_parameters()
for module in self.modules():
if isinstance(module, NGramEmbedding):
module.reset_parameters()
@@ -305,7 +412,7 @@ class Qwen3_8FlashNextForCausalLM(Qwen3_8FlashNextPreTrainedModel):
__all__ = [
"Qwen3_8FlashNextDecoderLayer",
"Qwen3_8FlashNextForCausalLM",
"Qwen3_8FlashNextModel",
"Qwen3_8FlashNextPreTrainedModel",
"Qwen3_8FlashNextTextModel",
"Qwen3_8FlashNextVLMModel",
]
@@ -1,3 +1,5 @@
import itertools
import torch
from torch import nn
@@ -55,4 +57,90 @@ class RotaryEmbedding(nn.Module):
return embeddings.cos().to(hidden_states.dtype), embeddings.sin().to(hidden_states.dtype)
__all__ = ["RotaryEmbedding", "apply_rotary_embedding"]
def get_vision_position_ids(
*,
start_position: int,
grid_thw: torch.Tensor,
spatial_merge_size: int,
device: torch.device | None = None,
) -> torch.LongTensor:
grid_t = int(grid_thw[0].item())
grid_h = int(grid_thw[1].item()) // spatial_merge_size
grid_w = int(grid_thw[2].item()) // spatial_merge_size
temporal = torch.arange(grid_t, device=device) + start_position
height = torch.arange(grid_h, device=device) + start_position
width = torch.arange(grid_w, device=device) + start_position
return torch.stack(
[
temporal.repeat_interleave(grid_h * grid_w),
height.repeat_interleave(grid_w).repeat(grid_t),
width.repeat(grid_h * grid_t),
],
dim=0,
)
def build_mrope_position_ids(
*,
input_ids: torch.LongTensor,
mm_token_type_ids: torch.LongTensor,
image_grid_thw: torch.LongTensor | None,
spatial_merge_size: int,
seq_lens: torch.Tensor,
) -> torch.LongTensor:
"""``[3, 1, seq]`` MRoPE positions for a packed row: text advances all three axes together, each image spans
its (temporal, height, width) grid from the current position, and positions restart at every sequence."""
seq_lens = seq_lens.to(device=input_ids.device, dtype=torch.long)
image_grids = iter(image_grid_thw) if image_grid_thw is not None else None
position_ids = torch.empty(3, 1, input_ids.shape[1], dtype=input_ids.dtype, device=input_ids.device)
offset = 0
for sequence_length_tensor in seq_lens:
sequence_length = int(sequence_length_tensor)
token_types = mm_token_type_ids[0, offset : offset + sequence_length]
current_position = 0
sequence_positions = []
for modality, indexed_group in itertools.groupby(enumerate(token_types.tolist()), lambda item: item[1]):
group = list(indexed_group)
group_length = group[-1][0] - group[0][0] + 1
if modality == 0:
text_positions = torch.arange(group_length, device=input_ids.device) + current_position
sequence_positions.append(text_positions.unsqueeze(0).expand(3, -1))
current_position += group_length
continue
if modality != 1:
raise ValueError(f"Unsupported Qwen3.8 Flash Next multimodal token type: {modality}")
if image_grids is None:
raise ValueError("image_grid_thw is required for image tokens")
remaining = group_length
while remaining:
grid = next(image_grids, None)
if grid is None:
raise ValueError("Not enough image_grid_thw rows for the image tokens")
image_positions = get_vision_position_ids(
start_position=current_position,
grid_thw=grid,
spatial_merge_size=spatial_merge_size,
device=input_ids.device,
)
if image_positions.shape[1] > remaining:
raise ValueError("Image token group length does not match image_grid_thw")
sequence_positions.append(image_positions)
current_position += max(int(grid[1]), int(grid[2])) // spatial_merge_size
remaining -= image_positions.shape[1]
positions = torch.cat(sequence_positions, dim=1)
if positions.shape[1] != sequence_length:
raise ValueError("Built MRoPE positions do not match the packed sequence length")
position_ids[:, 0, offset : offset + sequence_length] = positions
offset += sequence_length
if image_grids is not None and next(image_grids, None) is not None:
raise ValueError("image_grid_thw contains unused rows")
return position_ids
__all__ = ["RotaryEmbedding", "apply_rotary_embedding", "build_mrope_position_ids", "get_vision_position_ids"]
@@ -0,0 +1,274 @@
import math
import torch
import torch.nn.functional as F
from torch import nn
from transformers.modeling_outputs import BaseModelOutputWithPooling
from prime_rl.trainer.models.layers.attn import (
flash_attn_2_varlen_op,
flash_attn_3_varlen_op,
flash_attn_4_varlen_op,
)
from prime_rl.trainer.models.layers.rotary_emb import rotate_half
from prime_rl.trainer.models.qwen3_8_flash_next.configuration_qwen3_8_flash_next import Qwen3_8FlashNextVisionConfig
class VisionRotaryEmbedding(nn.Module):
def __init__(self, dim: int, theta: float = 10_000.0) -> None:
super().__init__()
self.dim = dim
self.theta = theta
self.register_buffer("inv_freq", torch.empty(dim // 2), persistent=False)
self.reset_parameters()
def reset_parameters(self) -> None:
positions = torch.arange(0, self.dim, 2, dtype=torch.float32, device=self.inv_freq.device)
self.inv_freq.copy_(1.0 / (self.theta ** (positions / self.dim)))
def forward(self, sequence_length: int) -> torch.Tensor:
positions = torch.arange(sequence_length, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
return torch.outer(positions, self.inv_freq)
class VisionPatchEmbed(nn.Module):
def __init__(self, config: Qwen3_8FlashNextVisionConfig) -> None:
super().__init__()
self.in_channels = config.in_channels
self.temporal_patch_size = config.temporal_patch_size
self.patch_size = config.patch_size
kernel_size = (self.temporal_patch_size, self.patch_size, self.patch_size)
self.proj = nn.Conv3d(
self.in_channels,
config.hidden_size,
kernel_size=kernel_size,
stride=kernel_size,
bias=True,
)
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
patch_width = self.in_channels * self.temporal_patch_size * self.patch_size**2
pixel_values = pixel_values.view(-1, patch_width).to(self.proj.weight.dtype)
return F.linear(
pixel_values,
self.proj.weight.view(self.proj.out_channels, patch_width),
self.proj.bias,
)
class VisionMLP(nn.Module):
def __init__(self, config: Qwen3_8FlashNextVisionConfig) -> None:
super().__init__()
self.linear_fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=True)
self.linear_fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=True)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
return self.linear_fc2(F.gelu(self.linear_fc1(hidden_states), approximate="tanh"))
class VisionAttention(nn.Module):
FLASH_ATTENTION_FUNCTIONS = {
"flash_attention_2": flash_attn_2_varlen_op,
"flash_attention_3": flash_attn_3_varlen_op,
"flash_attention_4": flash_attn_4_varlen_op,
}
def __init__(self, config: Qwen3_8FlashNextVisionConfig) -> None:
super().__init__()
self.num_heads = config.num_heads
self.head_dim = config.hidden_size // config.num_heads
self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=True)
self.proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
self.attention_implementation = config._attn_implementation
self.flash_attention = self.FLASH_ATTENTION_FUNCTIONS[self.attention_implementation]
def forward(
self,
hidden_states: torch.Tensor,
cu_seqlens: torch.IntTensor,
max_seqlen: int,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> torch.Tensor:
sequence_length = hidden_states.shape[0]
query, key, value = (
self.qkv(hidden_states).view(sequence_length, 3, self.num_heads, self.head_dim).unbind(dim=1)
)
cos, sin = position_embeddings
cos = cos.unsqueeze(1).float()
sin = sin.unsqueeze(1).float()
query_dtype = query.dtype
query = ((query.float() * cos) + (rotate_half(query.float()) * sin)).to(query_dtype)
key = ((key.float() * cos) + (rotate_half(key.float()) * sin)).to(query_dtype)
if self.attention_implementation == "flash_attention_4":
attention_output, _ = self.flash_attention(
query,
key,
value,
cu_seqlens_q=cu_seqlens,
cu_seqlens_k=cu_seqlens,
max_seqlen_q=max_seqlen,
max_seqlen_k=max_seqlen,
causal=False,
)
else:
attention_output = self.flash_attention(
query,
key,
value,
cu_seqlens,
cu_seqlens,
max_seqlen,
max_seqlen,
causal=False,
)
return self.proj(attention_output.reshape(sequence_length, -1))
class VisionBlock(nn.Module):
def __init__(self, config: Qwen3_8FlashNextVisionConfig) -> None:
super().__init__()
self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-6)
self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-6)
self.attn = VisionAttention(config)
self.mlp = VisionMLP(config)
def forward(
self,
hidden_states: torch.Tensor,
cu_seqlens: torch.IntTensor,
max_seqlen: int,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> torch.Tensor:
hidden_states = hidden_states + self.attn(
self.norm1(hidden_states), cu_seqlens, max_seqlen, position_embeddings
)
return hidden_states + self.mlp(self.norm2(hidden_states))
class VisionPatchMerger(nn.Module):
def __init__(self, config: Qwen3_8FlashNextVisionConfig) -> None:
super().__init__()
merged_hidden_size = config.hidden_size * config.spatial_merge_size**2
self.merged_hidden_size = merged_hidden_size
self.norm = nn.LayerNorm(config.hidden_size, eps=1e-6)
self.linear_fc1 = nn.Linear(merged_hidden_size, merged_hidden_size)
self.linear_fc2 = nn.Linear(merged_hidden_size, config.out_hidden_size)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.norm(hidden_states).view(-1, self.merged_hidden_size)
return self.linear_fc2(F.gelu(self.linear_fc1(hidden_states)))
class Qwen3_8FlashNextVisionModel(nn.Module):
def __init__(self, config: Qwen3_8FlashNextVisionConfig) -> None:
super().__init__()
self.config = config
self.spatial_merge_size = config.spatial_merge_size
self.patch_embed = VisionPatchEmbed(config)
self.pos_embed = nn.Embedding(config.num_position_embeddings, config.hidden_size)
self.num_grid_per_side = math.isqrt(config.num_position_embeddings)
self.rotary_pos_emb = VisionRotaryEmbedding(config.hidden_size // config.num_heads // 2)
self.blocks = nn.ModuleList(VisionBlock(config) for _ in range(config.depth))
self.merger = VisionPatchMerger(config)
@property
def dtype(self) -> torch.dtype:
return self.patch_embed.proj.weight.dtype
def rotary_embeddings(self, grid_thw: torch.Tensor) -> torch.Tensor:
grids = grid_thw.tolist()
frequency_table = self.rotary_pos_emb(max(max(height, width) for _, height, width in grids))
coordinates = []
merge_size = self.spatial_merge_size
for frames, height, width in grids:
block_rows = torch.arange(height // merge_size, device=frequency_table.device)
block_columns = torch.arange(width // merge_size, device=frequency_table.device)
intra_rows = torch.arange(merge_size, device=frequency_table.device)
intra_columns = torch.arange(merge_size, device=frequency_table.device)
rows = block_rows[:, None, None, None] * merge_size + intra_rows[None, None, :, None]
columns = block_columns[None, :, None, None] * merge_size + intra_columns[None, None, None, :]
rows = rows.expand(height // merge_size, width // merge_size, merge_size, merge_size).reshape(-1)
columns = columns.expand(height // merge_size, width // merge_size, merge_size, merge_size).reshape(-1)
coordinates.append(torch.stack((rows, columns), dim=-1).repeat(frames, 1))
return frequency_table[torch.cat(coordinates)].flatten(1)
def interpolated_position_embeddings(self, grid_thw: torch.Tensor) -> torch.Tensor:
embeddings = []
merge_size = self.spatial_merge_size
for frames, height, width in grid_thw.tolist():
row_positions = torch.arange(height, dtype=torch.float32, device=self.pos_embed.weight.device)
column_positions = torch.arange(width, dtype=torch.float32, device=self.pos_embed.weight.device)
row_scale = torch.tensor(
(self.num_grid_per_side - 1) / (height - 1) if height > 1 else 0.0,
dtype=torch.float32,
device=self.pos_embed.weight.device,
)
column_scale = torch.tensor(
(self.num_grid_per_side - 1) / (width - 1) if width > 1 else 0.0,
dtype=torch.float32,
device=self.pos_embed.weight.device,
)
row_floor = (row_positions * row_scale).floor().long()
column_floor = (column_positions * column_scale).floor().long()
row_ceil = (row_floor + 1).clamp_max(self.num_grid_per_side - 1)
column_ceil = (column_floor + 1).clamp_max(self.num_grid_per_side - 1)
row_fraction = torch.addcmul(-row_floor.float(), row_positions, row_scale)[:, None]
column_fraction = torch.addcmul(-column_floor.float(), column_positions, column_scale)[None, :]
weight11 = row_fraction * column_fraction
weight10 = torch.addcmul(row_fraction, -row_fraction, column_fraction)
weight01 = torch.addcmul(column_fraction, -row_fraction, column_fraction)
weight00 = 1 - row_fraction - weight01
indices = torch.stack(
[
(row_floor[:, None] * self.num_grid_per_side + column_floor[None, :]).flatten(),
(row_floor[:, None] * self.num_grid_per_side + column_ceil[None, :]).flatten(),
(row_ceil[:, None] * self.num_grid_per_side + column_floor[None, :]).flatten(),
(row_ceil[:, None] * self.num_grid_per_side + column_ceil[None, :]).flatten(),
]
)
weights = torch.stack([weight00.flatten(), weight01.flatten(), weight10.flatten(), weight11.flatten()]).to(
self.pos_embed.weight.dtype
)
corner_embeddings = self.pos_embed(indices)
# Match inference's fused-add order and rounding after each stage.
position_embedding = corner_embeddings[0] * weights[0, :, None]
for corner in range(1, 4):
position_embedding = torch.addcmul(
position_embedding, corner_embeddings[corner], weights[corner, :, None]
)
position_embedding = position_embedding.repeat(frames, 1)
position_embedding = (
position_embedding.view(
frames,
height // merge_size,
merge_size,
width // merge_size,
merge_size,
-1,
)
.permute(0, 1, 3, 2, 4, 5)
.flatten(0, 4)
)
embeddings.append(position_embedding)
return torch.cat(embeddings)
def forward(self, pixel_values: torch.Tensor, grid_thw: torch.Tensor) -> BaseModelOutputWithPooling:
hidden_states = self.patch_embed(pixel_values)
hidden_states = hidden_states + self.interpolated_position_embeddings(grid_thw)
rotary = self.rotary_embeddings(grid_thw)
rotary = torch.cat((rotary, rotary), dim=-1)
position_embeddings = (rotary.cos().to(hidden_states.dtype), rotary.sin().to(hidden_states.dtype))
sequence_lengths = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0])
cu_seqlens = F.pad(sequence_lengths.cumsum(dim=0, dtype=torch.int32), (1, 0))
max_seqlen = int(sequence_lengths.max())
for block in self.blocks:
hidden_states = block(hidden_states, cu_seqlens, max_seqlen, position_embeddings)
return BaseModelOutputWithPooling(
last_hidden_state=hidden_states,
pooler_output=self.merger(hidden_states),
)
__all__ = ["Qwen3_8FlashNextVisionModel"]
@@ -6,9 +6,10 @@ from prime_rl.trainer.models.qwen3_8_flash_next import (
Qwen3_8FlashNextConfig,
Qwen3_8FlashNextForCausalLM,
Qwen3_8FlashNextTextConfig,
Qwen3_8FlashNextVisionConfig,
)
from prime_rl.trainer.perf import FlopCounter
from prime_rl.utils.vlm import get_language_model
from prime_rl.utils.vlm import get_language_model, get_vision_encoder
@pytest.fixture(params=[False, True], ids=["text", "composite"])
@@ -37,7 +38,17 @@ def config(request, layer_type):
make_ngram_vocab_size_divisible_by=8,
split_ngram_parts=3,
)
return Qwen3_8FlashNextConfig(text_config=text) if request.param else text
if not request.param:
return text
vision = Qwen3_8FlashNextVisionConfig(
depth=1,
hidden_size=16,
intermediate_size=16,
num_heads=2,
out_hidden_size=16,
num_position_embeddings=16,
)
return Qwen3_8FlashNextConfig(text_config=text, vision_config=vision, image_token_id=30)
@pytest.fixture(params=["linear_attention", "full_attention"])
@@ -47,6 +58,7 @@ def layer_type(request):
def test_meta_flop_count_without_cuda(config, monkeypatch):
monkeypatch.setattr(torch.cuda, "is_available", lambda: False)
config = type(config).from_dict(config.to_dict(), attn_implementation="flash_attention_2")
with torch.device("meta"):
model = Qwen3_8FlashNextForCausalLM(config)
assert all(parameter.is_meta for parameter in model.parameters())
@@ -56,10 +68,15 @@ def test_meta_flop_count_without_cuda(config, monkeypatch):
@pytest.mark.parametrize("shard_count", [3, 128])
def test_config_and_checkpoint_roundtrip(config, shard_count):
getattr(config, "text_config", config).split_ngram_parts = shard_count
restored = type(config).from_dict(config.to_dict())
restored = type(config).from_dict(config.to_dict(), attn_implementation="flash_attention_2")
model = Qwen3_8FlashNextForCausalLM(restored)
model.init_buffers_post_meta()
assert len(get_language_model(model).layers) == 1
assert model.supports_packed_multimodal_training == model.is_vlm
assert (get_vision_encoder(model) is not None) == model.is_vlm
if model.is_vlm:
text_model = Qwen3_8FlashNextForCausalLM(restored.text_config)
assert model.num_active_params() == text_model.num_active_params()
original = {
name: torch.randn_like(value) if value.is_floating_point() else value.clone()
for name, value in model.state_dict().items()
@@ -68,6 +85,7 @@ def test_config_and_checkpoint_roundtrip(config, shard_count):
operations = model.conversion_chain(restored)
apply_prime_to_hf(converted, operations)
assert model.is_hf_state_dict(converted)
assert any(name.startswith("model.visual.") for name in converted) == model.is_vlm
apply_hf_to_prime(converted, operations)
assert converted.keys() == original.keys()
for name, value in original.items():
@@ -0,0 +1,369 @@
import pytest
import torch
from prime_rl.configs.trainer import ModelConfig
from prime_rl.trainer.model import resolve_auto_attn
from prime_rl.trainer.models import AutoModelForCausalLMPrimeRL
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.qwen3_8_flash_next import (
Qwen3_8FlashNextConfig,
Qwen3_8FlashNextTextConfig,
Qwen3_8FlashNextVisionConfig,
)
from prime_rl.trainer.models.qwen3_8_flash_next.rotary_embedding import build_mrope_position_ids
def get_vlm_config():
return Qwen3_8FlashNextConfig(
text_config=Qwen3_8FlashNextTextConfig(
vocab_size=256,
bos_token_id=255,
eos_token_id=255,
hidden_size=256,
num_hidden_layers=2,
layer_types=["linear_attention", "full_attention"],
num_attention_heads=4,
num_key_value_heads=2,
head_dim=64,
linear_key_head_dim=32,
linear_value_head_dim=32,
linear_num_key_heads=4,
linear_num_value_heads=8,
indexer_n_heads=4,
indexer_head_dim=64,
indexer_budget=128,
indexer_compress_ratio=4,
hc_count=2,
hc_lowrank=32,
ple_layer_ids=[1],
ple_embed_dim=64,
heads_per_ngram=2,
ngram_vocab_size_base=1024,
make_ngram_vocab_size_divisible_by=8,
split_ngram_parts=4,
moe_intermediate_size=128,
shared_expert_intermediate_size=128,
num_experts=4,
num_experts_per_tok=2,
rope_parameters={
"rope_type": "default",
"rope_theta": 10_000_000.0,
"partial_rotary_factor": 0.25,
"mrope_section": [3, 3, 2],
},
),
vision_config=Qwen3_8FlashNextVisionConfig(
depth=2,
hidden_size=128,
intermediate_size=256,
num_heads=4,
out_hidden_size=256,
),
image_token_id=250,
vision_start_token_id=252,
vision_end_token_id=253,
)
def get_model(config, device="cuda"):
runtime_config = ModelConfig()
resolve_auto_attn(runtime_config)
with torch.device(device):
model = AutoModelForCausalLMPrimeRL.from_config(
config, attn_implementation=runtime_config.attn, dtype=torch.bfloat16
)
inject_prime_lm_head(model)
return model
def get_image_inputs(config, device="cuda", dtype=torch.bfloat16, image_grid=(1, 2, 2)):
"""Create minimal image inputs matching the vision config."""
vc = config.vision_config
patch_dim = vc.in_channels * vc.temporal_patch_size * vc.patch_size * vc.patch_size
image_grid_thw = torch.tensor([image_grid], device=device)
num_patches = int(image_grid_thw.prod().item())
pixel_values = torch.randn(num_patches, patch_dim, device=device, dtype=dtype)
num_image_tokens = num_patches // (vc.spatial_merge_size**2)
return pixel_values, image_grid_thw, num_image_tokens
def get_mm_token_type_ids(input_ids, image_token_id):
mm_token_type_ids = torch.zeros_like(input_ids)
mm_token_type_ids[input_ids == image_token_id] = 1
return mm_token_type_ids
def get_seq_lens(input_ids: torch.Tensor) -> torch.Tensor:
return torch.tensor([input_ids.shape[1]], device=input_ids.device)
@pytest.mark.gpu
def test_vlm_forward():
"""Custom VLM produces logits for both text-only and multimodal inputs."""
config = get_vlm_config()
model = get_model(config)
vocab = config.text_config.vocab_size
# Text-only (avoid the image token 250 and the eos token 255)
input_ids = torch.randint(0, 200, (1, 20), device="cuda")
position_ids = torch.arange(1, 21, device="cuda").unsqueeze(0)
out_text = model(input_ids=input_ids, position_ids=position_ids, seq_lens=get_seq_lens(input_ids))
assert out_text["logits"].shape == (1, 20, vocab)
# Multimodal
pixel_values, image_grid_thw, n_img_tokens = get_image_inputs(config)
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids_mm = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
mm_token_type_ids = get_mm_token_type_ids(input_ids_mm, config.image_token_id)
out_mm = model(
input_ids=input_ids_mm,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
seq_lens=get_seq_lens(input_ids_mm),
)
assert out_mm["logits"].shape == (1, input_ids_mm.shape[1], vocab)
@pytest.mark.gpu
@pytest.mark.parametrize("num_image_tokens", [0, 2])
def test_vlm_rejects_image_feature_count_mismatch(num_image_tokens):
config = get_vlm_config()
model = get_model(config)
pixel_values, image_grid_thw, _ = get_image_inputs(config)
input_ids = torch.tensor([[10, *([config.image_token_id] * num_image_tokens), 11]], device="cuda")
with pytest.raises(ValueError, match="Image features and image tokens do not match"):
model(
input_ids=input_ids,
position_ids=torch.arange(input_ids.shape[1], device="cuda").unsqueeze(0),
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=get_mm_token_type_ids(input_ids, config.image_token_id),
seq_lens=get_seq_lens(input_ids),
)
@pytest.mark.gpu
@pytest.mark.parametrize("compile_vision", [False, True])
def test_vlm_backward(compile_vision):
"""Gradients flow through both vision scatter and text model."""
config = get_vlm_config()
model = get_model(config)
if compile_vision:
for index, block in enumerate(model.model.visual.blocks):
model.model.visual.blocks[index] = torch.compile(block, backend="eager", fullgraph=True)
pixel_values, image_grid_thw, n_img_tokens = get_image_inputs(config, image_grid=(1, 4, 6))
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
mm_token_type_ids = get_mm_token_type_ids(input_ids, config.image_token_id)
out = model(
input_ids=input_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
seq_lens=get_seq_lens(input_ids),
)
out["logits"].sum().backward()
assert model.model.language_model.embed_tokens.weight.grad is not None
assert model.model.visual.patch_embed.proj.weight.grad is not None
position_gradient = model.model.visual.pos_embed.weight.grad
assert position_gradient is not None
assert torch.isfinite(position_gradient).all()
assert torch.count_nonzero(position_gradient) > 0
@pytest.mark.gpu
def test_vlm_router_replay():
"""routed_experts bypasses router computation in VLM multimodal forward."""
config = get_vlm_config()
model = get_model(config)
vocab = config.text_config.vocab_size
pixel_values, image_grid_thw, n_img_tokens = get_image_inputs(config)
text_part = torch.randint(0, 200, (1, 10), device="cuda")
img_part = torch.full((1, n_img_tokens), config.image_token_id, device="cuda")
input_ids = torch.cat([text_part[:, :5], img_part, text_part[:, 5:]], dim=1)
mm_token_type_ids = get_mm_token_type_ids(input_ids, config.image_token_id)
seq_len = input_ids.shape[1]
num_layers = config.text_config.num_hidden_layers
topk = config.text_config.num_experts_per_tok
routed_experts = torch.randint(0, config.text_config.num_experts, (1, seq_len, num_layers, topk), device="cuda")
out = model(
input_ids=input_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_token_type_ids=mm_token_type_ids,
routed_experts=routed_experts,
seq_lens=get_seq_lens(input_ids),
)
assert out["logits"].shape == (1, seq_len, vocab)
out["logits"].sum().backward()
assert model.model.language_model.embed_tokens.weight.grad is not None
@pytest.mark.gpu
def test_vlm_meta_device_and_buffer_reinit():
"""Model can be created on meta device and buffers reinitialized."""
config = get_vlm_config()
model = get_model(config, device="meta")
model.to_empty(device="cuda")
model.init_buffers_post_meta()
lm_inv = model.model.language_model.rotary_emb.inv_freq
vis_inv = model.model.visual.rotary_pos_emb.inv_freq
assert lm_inv.device.type == "cuda"
assert vis_inv.device.type == "cuda"
assert lm_inv.abs().sum() > 0
assert vis_inv.abs().sum() > 0
def test_mrope_text_only_positions():
input_ids = torch.tensor([[10, 11, 12, 13]])
mm_token_type_ids = torch.zeros_like(input_ids)
position_ids = build_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=None,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)
expected = torch.arange(4).view(1, 1, -1).expand(3, 1, -1)
torch.testing.assert_close(position_ids, expected)
def test_mrope_single_image_with_surrounding_text():
input_ids = torch.tensor([[10, 11, 99, 99, 99, 99, 12]])
mm_token_type_ids = torch.tensor([[0, 0, 1, 1, 1, 1, 0]])
image_grid_thw = torch.tensor([[1, 4, 4]])
position_ids = build_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)
expected = torch.tensor(
[
[[0, 1, 2, 2, 2, 2, 4]],
[[0, 1, 2, 2, 3, 3, 4]],
[[0, 1, 2, 3, 2, 3, 4]],
]
)
torch.testing.assert_close(position_ids, expected)
def test_mrope_adjacent_images_consume_multiple_grids():
input_ids = torch.tensor([[10, 99, 99, 99, 99, 99, 99, 99, 99, 11]])
mm_token_type_ids = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 0]])
image_grid_thw = torch.tensor([[1, 4, 4], [1, 4, 4]])
position_ids = build_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)
expected = torch.tensor(
[
[[0, 1, 1, 1, 1, 3, 3, 3, 3, 5]],
[[0, 1, 1, 2, 2, 3, 3, 4, 4, 5]],
[[0, 1, 2, 1, 2, 3, 4, 3, 4, 5]],
]
)
torch.testing.assert_close(position_ids, expected)
def test_mrope_packed_segments_reset_independently():
input_ids = torch.tensor([[10, 99, 99, 99, 99, 11, 99, 99, 99, 99]])
mm_token_type_ids = torch.tensor([[0, 1, 1, 1, 1, 0, 1, 1, 1, 1]])
image_grid_thw = torch.tensor([[1, 4, 4], [1, 4, 4]])
seq_lens = torch.tensor([5, 5])
position_ids = build_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=seq_lens,
)
expected_segment = torch.tensor(
[
[0, 1, 1, 1, 1],
[0, 1, 1, 2, 2],
[0, 1, 2, 1, 2],
]
)
torch.testing.assert_close(position_ids[:, 0, :5], expected_segment)
torch.testing.assert_close(position_ids[:, 0, 5:], expected_segment)
def test_mrope_packed_matches_standalone_segments():
segment_input_ids = torch.tensor([[10, 99, 99, 99, 99, 11]])
segment_token_types = torch.tensor([[0, 1, 1, 1, 1, 0]])
image_grid_thw = torch.tensor([[1, 4, 4]])
standalone = build_mrope_position_ids(
input_ids=segment_input_ids,
mm_token_type_ids=segment_token_types,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=torch.tensor([segment_input_ids.shape[1]]),
)
packed = build_mrope_position_ids(
input_ids=torch.cat([segment_input_ids, segment_input_ids], dim=1),
mm_token_type_ids=torch.cat([segment_token_types, segment_token_types], dim=1),
image_grid_thw=torch.cat([image_grid_thw, image_grid_thw], dim=0),
spatial_merge_size=2,
seq_lens=torch.tensor([segment_input_ids.shape[1], segment_input_ids.shape[1]]),
)
torch.testing.assert_close(packed[:, :, : segment_input_ids.shape[1]], standalone)
torch.testing.assert_close(packed[:, :, segment_input_ids.shape[1] :], standalone)
def test_mrope_rejects_image_length_grid_mismatch():
input_ids = torch.tensor([[10, 99, 99]])
mm_token_type_ids = torch.tensor([[0, 1, 1]])
image_grid_thw = torch.tensor([[1, 4, 4]])
with pytest.raises(ValueError, match="Image token group length"):
build_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=image_grid_thw,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)
def test_mrope_rejects_unsupported_modalities():
input_ids = torch.tensor([[10, 99]])
mm_token_type_ids = torch.tensor([[0, 2]])
with pytest.raises(ValueError, match="Unsupported Qwen3.8 Flash Next multimodal token type: 2"):
build_mrope_position_ids(
input_ids=input_ids,
mm_token_type_ids=mm_token_type_ids,
image_grid_thw=None,
spatial_merge_size=2,
seq_lens=torch.tensor([input_ids.shape[1]]),
)