Repository navigation
[rl] Muse Spark image prompts and a SLAKE LoRA GRPO recipe for Muse Spark 816B - #6025
Conversation
| # attention_metadata slot and break the maskless SDPA backend). | ||
| # passthrough for nonexistent layers, allows easy configuration of pipeline parallel stages | ||
| h = self.tok_embeddings(tokens) if self.tok_embeddings is not None else tokens | ||
| return self.forward_embeddings( |
There was a problem hiding this comment.
Why having this new API?
| aux_loss_denominators=aux_loss_denominators, | ||
| ) | ||
|
|
||
| def forward_embeddings( |
There was a problem hiding this comment.
We need this new API because vLLM need to feed the embedding (instead of token ids) to the model
| # TorchTitan's MRoPE takes (num_tokens, 3). | ||
| positions = positions.transpose(0, 1) | ||
| with self.parallelism_context.activate_spmd(): | ||
| # Mirrors the model's forward after embedding (layers, then the final norm). |
There was a problem hiding this comment.
Instead of keep another copy of Decoder.forward(), adding a API in Decoder and unify these APIs is cheaper
|
@claude review |
06ecd17 to
bc3efd8
Compare
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The design holds up: forward_embeddings deletes the generator's copied layer loop instead of adding a model-specific hook, and Muse Spark image RL builds on the existing renderer, batcher and vLLM wrapper paths. This touches models/common/decoder.py, so a maintainer still needs to review.
What this PR does.
- The Muse Spark renderer renders file-backed image parts as
<|patch|>runs. Image tokens in the generator get 1D positions, and the HF config gets anmrope_sectiononly forMRoPE.Configmodels. Decoder.forwardis split so the vLLM multimodal wrapper calls the model's own post-embedding loop. For Muse Spark that loop keeps its residual and final-norm dtypes.- Also added: a SLAKE example, a Muse Spark 816B LoRA GRPO recipe, and a vLLM workaround for preempted image requests.
Example. One SLAKE prompt [image(100x60), "Is this a CT?"] on Muse Spark:
before: renderer -> ValueError("reads no image files")
generator HF config -> ValueError (needs MRoPE.Config)
wrapper.forward -> own layer loop + model.norm(h), no Muse Spark residual/norm dtypes
after: tokens ... <|image_start|> <|patch|> x 6 <|image_end|> Is this a CT? ...
positions 1D (no mrope_section; positions.ndim == 1, not transposed)
wrapper.forward -> model.forward_embeddings(...) # same loop the trainer runs
Must fix
torchtitan/rl/generator/vllm/multimodal_wrapper.py:108-- the process-wide replacement of vLLM's privatestrip_covered_mm_datahas a TODO with no upstream issue link (see inline).- Merge order: the recipe needs #5982, which is still open and not in this stack. Without it, the generator's lm_head is silently corrupted from the third adapter sync on. Land #5982 first, or put it under this PR in the stack.
Should consider
torchtitan/models/muse_spark/renderer.py:214--_imagecopiesQwen35ImageRefRenderer._process_image; move it next tohash_image_file. Also, each image file is read and hashed twice per render (see inline).- The preemption workaround (second commit) isn't specific to Muse Spark: Qwen3.5 image RL hits the same crash. It could be its own PR, per "one concern per PR".
torchtitan_recipes/rl/slake.py:102-- the docstring cites a PR that has already landed (see inline).
Details
forward_embeddings. The old wrapper loop passedattention_metadata=Noneandpadding_maskto each layer, then appliedmodel.norm.Decoder.forward_embeddingsdoes the same withattention_metadata=None. The generator sets_skip_lm_head = True(rl/generator/model.py:130), so the lm_head is still skipped. Qwen3.5 behaves the same as before. Muse Spark now gets its bf16 residual cast and final-norm dtype, which the old copied loop dropped. The Muse Spark override is the loop moved out of itsforwardunchanged.- Bank-index rename.
image_bank_indices_T->image_vision_bank_indices_Tcovers every caller (the RL batcher, Qwen3.5 and the Muse Spark GPU test). The SFT path still builds the rows inpreprocess_inputs, since only the RL batcher puts them in the batch. - Bridge.
token_env.py:334passesprevious_multi_modal_dataonly when the previous turn had images, which matches the renderer's new kwarg. Placeholder offsets stay valid because the bridged ids extendprevious_ids. - "Costs no memory". The claim holds for the
external_launcherin-process engine core:engine.pyreachesengine_core.engine_core.schedulerdirectly.
Not verified: that vLLM's scheduler reaches strip_covered_mm_data only through the patched module attribute (vLLM source wasn't readable here; the new unit test covers NewRequestData.from_request). Also not verified: the GPU numerics and the throughput numbers in the description.
| TODO: remove once vLLM resends a resumed request's dropped image data. | ||
| """ | ||
| import vllm.v1.core.sched.output as vllm_scheduler_output | ||
|
|
||
| vllm_scheduler_output.strip_covered_mm_data = _keep_mm_features |
There was a problem hiding this comment.
This replaces a private vLLM module function (vllm.v1.core.sched.output.strip_covered_mm_data) for the whole process, and the TODO doesn't link an upstream issue. CLAUDE.md principle 3 asks for an issue link on every workaround for an upstream gap. As written, nobody can tell when the workaround can go, or whether vLLM knows about the bug. The bug is in vLLM: a preempted request resumes from features whose data the scheduler has already dropped. So the fix should land upstream.
Fix: file the vLLM issue (the PR description already has the repro: preemption plus prefix-block eviction, then "Encoder cache miss") and link it here, e.g. TODO(https://github.com/vllm-project/vllm/issues/NNNN): remove once ....
The bug isn't specific to Muse Spark. Any image-serving generator hits it, including Qwen3.5 on Geometry3K. So this commit could be its own PR under #5824's generator code, which would also make it easier to revert once vLLM fixes it.
| def _image(self, part: dict[str, Any]) -> _ImageFile: | ||
| path = part.get("path") | ||
| if path is None: | ||
| raise ValueError( | ||
| "Muse Spark image parts need a 'path' to an image file, got keys " | ||
| f"{sorted(part)}." | ||
| ) | ||
| with open(path, "rb") as f: | ||
| data = f.read() | ||
| # The header gives the stored size; decoding applies no EXIF rotation either. | ||
| width, height = Image.open(io.BytesIO(data)).size | ||
| grid_thw = self._vision_processor.grid_thw(height, width) | ||
| return _ImageFile( | ||
| hash_image_file(data), | ||
| grid_thw, | ||
| self._vision_processor.num_placeholder_tokens(grid_thw), | ||
| ) |
There was a problem hiding this comment.
_image copies Qwen35ImageRefRenderer._process_image (torchtitan/models/qwen3_5/renderer.py:117-130) nearly line for line: the path check, the file read, the header size without decoding, grid_thw, num_placeholder_tokens and hash_image_file. With a second consumer, this belongs next to hash_image_file in torchtitan/components/renderer.py. For example, read_image_file_ref(path, vision_processor) -> (hash, grid_thw, num_tokens), which both renderers call. The two copies can't drift that way. Drift would be silent: the renderer's placeholder count has to equal the generator's and the trainer's.
Also, render calls _image twice per image part: once through span() while building the text, then again in multi_modal_data. Each image file is read, opened and SHA-256 hashed twice per render, and a GRPO group renders once per sample. Compute each part's _ImageFile once per render, e.g. collect them in span() and hand them to multi_modal_data.
| fp32 master weights and AdamW states and compute in bf16. The frozen base needs #5894 | ||
| (frozen parameters stored in ``param_dtype``, here bf16): in fp32 the 816B base does not | ||
| fit the 8-GPU trainer. The generators load the base from the HF checkpoint, so every |
There was a problem hiding this comment.
Nit: #5894 is on main, so the docstring is narrating history. Docs should describe the current state, e.g. "The frozen base is stored in param_dtype (bf16); in fp32 the 816B base does not fit the 8-GPU trainer."
tianyu-l
left a comment
There was a problem hiding this comment.
please address feedback before merge
| return float(is_correct(response_text, env_input.answer)) | ||
|
|
||
|
|
||
| def is_correct(response_text: str, expected: str) -> bool: |
There was a problem hiding this comment.
should this be private? I might missed other callsites
| return gold in ("yes", "no") and predicted.split(" ", 1)[0] == gold | ||
|
|
||
|
|
||
| def normalize_answer(text: str) -> str: |
There was a problem hiding this comment.
other than qwen3.5 and muse_spark did we check all the multimodal models? Maybe they are all of them.
| vLLM drops the data of the images a request's prefix-cache hit covers before | ||
| sending the request to the worker (`strip_covered_mm_data` in | ||
| ``NewRequestData.from_request``): those images need no encoder run, unless the request | ||
| is preempted. With the V1 model runner, a preempted request resumes from the worker's |
There was a problem hiding this comment.
I didn't understand this issue.
I'm OK to rush this in, if you could link a vllm / titan issue in the code.
Also, it says here it's a problem for v1, would it be a problem for v2 which we have to migrate to soon?
There was a problem hiding this comment.
Short answer: v2 doesn't have this issue, so long term I think moving to V2 soon is the right solution.
From agent:
Here is the sequence with an example. The 16 samples of a GRPO group share a prompt [128 text tokens][image: 391 tokens][50 text tokens]:
Sample A (first of the group)
prefills the whole prompt and runs the vision encoder; the KV goes into the prefix cache
Sample B (same prompt)
its prefix-cache hit covers tokens 0..569, image included
scheduler -> worker: NewRequestData with the image's pixels dropped
(strip_covered_mm_data: the image's KV is cached, so it needs no encoder run)
the V1 worker stores this pixel-less copy of the request
... decoding ...
KV pressure: B is preempted, and its prefix blocks are evicted before it resumes
B resumes
scheduler: the prefix-cache hit is now only 0..128
-> the image (128..519) must be recomputed -> schedules its encoder run
V1 worker: resumes B from its stored copy (CachedRequestData carries no image data)
-> no pixels -> skips the encoder run
forward: _gather_mm_embeddings finds no embedding for the image
-> RuntimeError "Encoder cache miss" -> the engine loop dies
The scheduler decides "no pixels needed" against the cache hit when the request is admitted, and V1 keeps that decision after a preemption even though the cache has changed. GRPO makes this likely: every sample after the first in a group gets its pixels stripped, and preemption is common under KV pressure. The Muse Spark 816B SLAKE run crashed this way at step 4: a resumed request with num_computed_tokens 128 and the image's encoder run scheduled.
The patch makes strip_covered_mm_data keep the data, so the worker always has the pixels. It costs no memory: the engine core and the worker run in one process, so the worker's features are the scheduler's own objects.
V2 does not have this bug. It resends a resumed request as a new one (in Scheduler.schedule: if self.use_v2_model_runner: scheduled_new_reqs.extend(scheduled_resumed_reqs)), so the stripping is redone against the cache hit at resume, and the pixels are kept when the image is no longer cached. So the long-term solution is to migrate the generator to the V2 model runner and drop this patch.
bc3efd8 to
e19cb1a
Compare
72bdfb4 to
40fd6f8
Compare
40fd6f8 to
b83bf69
Compare
… only the adapters (#5844) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> **Stack** (image RL; review bottom up, each PR is one commit on the one below): 0. #5873 [multimodal] VisionProcessor: one per-model image and video processor (merged) 1. #5823 [multimodal] Image-reference Qwen3.5 renderer and shared M-RoPE positions (merged) 2. #5824 [rl] Image prompts through rollouts and the vLLM generator (merged) 3. #5825 [rl] Train on image prompts, with a Geometry3K recipe (merged) 4. **→** #5844 [rl] LoRA RL: generators load the base checkpoint, weight syncs carry only the adapters 5. #6025 [rl] Muse Spark image prompts and a SLAKE LoRA GRPO recipe for Muse Spark 816B 6. #5845 [rl] CUDA graphs for the generator's vision encoder ## Why A LoRA run trains a few adapters on a frozen base, but every weight sync sent the whole model (Qwen3.5-27B in bf16: ~54 GB per sync, for ~0.3% trainable parameters at rank 32). Generators can already load the HF checkpoint (`Generator.Config.checkpointer`, `ModelStateDictLoader`'s initial load), but the RL loop forbade it, so every sync, the initial one included, carried the whole model. **Example.** Geometry3K, Qwen3.5-0.8B, rank-32 LoRA (measured below): ``` before: every weight sync = the whole model 2.2 GB (Qwen3.5-27B in bf16: ~54 GB) after: generators load the base from the HF checkpoint once, every weight sync = lora_a + lora_b + buffers 38 MB ``` ## What changed - Every weight sync (the initial one, which also covers resume, included) carries the trainable parameters and the buffers: `Trainer.push_model_state_dict` leaves out the parameters with `requires_grad=False`. For LoRA that leaves `lora_a` and `lora_b`. Since #5730 RL recipes freeze nothing else (the router gate trains), so every other recipe still sends the whole model. No flag, no new config field. - Generators load the frozen parameters from `generator.checkpointer`, which the controller no longer rejects. Loads leave them out, and they keep their weight: the load reallocates each FSDP group's sharded storage, and `_restore_sharded_params` refills the frozen parameters' shards from the unsharded storage (which CUDA graphs read) before the group's unshard. Groups of only frozen parameters (e.g. `tok_embeddings`, the vision tower) are skipped. This lives in the engine-agnostic `ModelStateDictLoader` (`rl/generator/model.py`, #5811). - The generator freezes every parameter, so `build_inference_model` reads `requires_grad` right after the build, before freezing, and passes the frozen keys to `ModelStateDictLoader`. They are passed because the model cannot tell afterwards: a module does not record whether its config froze it. Inferring them from the module structure (every parameter but the LoRA adapters) breaks with `LoRATransform.trainable_modules` (#6003), which keeps any module trainable. - With frozen parameters but no generator checkpointer, the loader raises at setup, since no sync would fill them; so does a quantized frozen parameter (its unsharded weight cannot refill its shard). A load that misses any other parameter still raises. The `cpu_prefetch` path's pinned receive buffers cover only what the trainer pushes. The generator's HF load defaults to the model's HF assets, like the trainer's, for vLLM and SGLang (SGLang passes its `model_path`). - `rl_grpo_qwen3_5_0_8b_geometry3k_lora`: rank-32 LoRA on the language model's attention, GatedDeltaNet and MLP projections (vision tower frozen), lr 10x the full fine-tuning one, generators loading the HF checkpoint. At step 0 the generator's adapters are its own random `lora_a` with `lora_b = 0`, so its policy equals the trainer's; the first sync after an optimizer step sends both. ## Numerics / performance Geometry3K, Qwen3.5-0.8B on 4 GB300 (trainer FSDP=2 + 2 generators at TP=1), 30 steps: `rl_grpo_qwen3_5_0_8b_geometry3k_lora` vs the full fine-tuning recipe (TensorBoard logger; FA4 with `num_splits=1` for head_dim 256, a separate fix). Sync numbers are TorchStore's own timings, rank 0; later syncs are the median over syncs 2-31. | | full fine-tuning | LoRA, generators load the base | |---|---|---| | initial weight sync | 2.21 GB | 38 MB | | later weight syncs: bytes | 2,215 MB | 38 MB | | later weight syncs: generator pull / trainer put | 1.02 s / 0.089 s | 0.30 s / 0.026 s | | generator blocked on the pull, mean per step | 0.85 s | 0.16 s | | step time, steps 2-30, mean | 10.4 s | 8.6 s | | validation reward (601 test problems), start -> end | 0.263 -> 0.384 | 0.291 -> 0.371 | | trainer-generator logprob difference, mean per token | -0.0009 | -0.0006 | The generators' own HF load gives the trainer's frozen weights: the logprob agreement matches a run whose base came through the weight sync (-0.0007). At 38 MB a pull is bound by per-tensor overhead (~0.13 GB/s); with larger models the bytes dominate (a full Qwen3.5-27B sync in bf16 is ~54 GB). Step-0 validation differs by 0.02 between runs with the same weights, so the reward rows are within run-to-run noise. ## Testing Unit tests: a push carries the trainable parameters and the buffers (a LoRA base or a `freeze_gate` gate is left out); a load leaves out only frozen parameters, which keep their weight (one rank, and two ranks with uneven shards), and a missing trainable parameter raises; frozen parameters without a generator checkpointer raise at setup. ## Known issues / follow-ups - TODO in `ModelStateDictLoader`: every generator replica reads the checkpoint from storage at once (80 reads with 10 nodes x 8 GPUs at DP=1). A follow-up sends the frozen parameters once through the initial weight sync instead (drafted on top of this PR). - Not in this PR: adapters-only checkpoints and HF export. (The trainer already stores the frozen base in `precision.param_dtype`, #5894.)
b83bf69 to
00f9a1c
Compare
…park 816B
Image RL ran only Qwen3.5: the Muse Spark renderer rejected image parts, the generator
assumed M-RoPE positions, and the generator kept its own copy of the layer loop.
- Muse Spark renderer: built with a vision processor, an image part
`{"type": "image", "path": ...}` renders as <|image_start|> + N x <|patch|> +
<|image_end|> (Muse Spark's multimodal SFT expansion), N from the patch grid of the size
in the file header, and `multi_modal_data` carries each image's file hash, grid and
<|patch|> run, as `Qwen35ImageRefRenderer` does; `bridge_to_next_turn` places later turns'
images after the previous prompt's. Without a vision processor image parts still raise.
- Models: `Decoder.forward_embeddings` runs `forward` after the token embedding; Muse
Spark overrides it with its residual and final-norm dtypes, gets `get_vision_embeds`, and
takes RL microbatches' bank rows (`image_vision_bank_indices_T`, the Qwen3.5 name).
`Qwen35Model.forward` ends with it too, so each model has one layer loop that the trainer
and the generator share (Qwen3.5 debug model on cc12m-test, FSDP=2, 20 steps, seed 42,
deterministic: loss and grad norm bitwise identical to before).
- Generator: image tokens of a model without M-RoPE (Muse Spark) take 1D positions: no
mrope_section in the HF config (`get_mrope_config`, which the controller's batcher check
uses too), positions transposed only when 3D; the multimodal wrapper runs
`forward_embeddings` instead of copying the layer loop.
- The SLAKE recipe leaves `Batcher.Config.build_mrope_positions` False: Muse Spark's image
tokens take the 1D positions.
- SLAKE example (`torchtitan/rl/examples/slake`): the English release, closed and open
questions without knowledge-graph ones, the Muse Spark SLAKE SFT recipe's short-answer
instruction, reward by exact match after normalization.
- `rl_muse_spark_816b_a42b_slake_lora_gb300`: LoRA r8/a16 on wqkv, wo and output_gate,
generators loading the HF base (adapter-only syncs), fixed to the measured 32-GPU
configuration (8-GPU trainer, three 8-GPU generators, 32 x 16, 8K tokens per microbatch,
low reasoning effort, 4K response tokens, zero-std groups dropped); only the paths are
arguments. Needs #5894 (frozen
parameters stored in param_dtype) for the bf16 base to fit the 8-GPU trainer.
…est needs on resume vLLM drops the data of the images a new request's prefix-cache hit covers before sending the request to its worker (`strip_covered_mm_data`). With the V1 model runner a preempted request resumes from the worker's copy of its features, so when its prefix blocks were evicted meanwhile, the scheduler schedules the image's encoder run, the worker skips it for lack of data, and `_gather_mm_embeddings` raises "Encoder cache miss", killing the engine loop. GRPO samples of a group share a prompt, so all but the first hit the prefix cache over their images. Muse Spark 816B on SLAKE (32 x 16, zero-std groups dropped) crashed at step 4 on a resumed request (num_computed_tokens 128, encoder input scheduled). `keep_prefix_cached_image_data` makes the scheduler send every new request's features whole when the engine serves images. The engine core and worker run in the generator's process, so the worker's features are the scheduler's objects: no extra memory. Test: test_scheduler_sends_prefix_cached_image_data_to_the_worker fails without the change (the worker's feature data is None).
With zero-std groups dropped (the recipe default), the learning run needs ~118 generated groups per step for 32 kept ones, so rollout supply is capped by the controller's active groups, `(target_offpolicy_steps + 1) x num_prompts_per_train_step`, not by generator count. Muse Spark 816B on SLAKE, 32 GB300 GPUs (8-GPU trainer + three 8-GPU generators), 32 x 16, medians of steps 5-10: | target_offpolicy_steps | step | trainer waits | mean / max policy age | reward | |---|---|---|---|---| | 3 | 36.0 s | 14.6 s | 1.4 / 3 | 0.511 | | 5 | 24.0 s (mean 26.9 s) | 10-15 s at 2 of 6 steps | 3.0 / 5 | 0.518 | | 7 | 24.0 s (mean 23.6 s) | 0.002 s at every step | 4.0 / 7 | 0.526 | At 3, two more generators (48 GPUs) only reach 29.4 s per step. At 7 the trainer never waits. The cost is staler samples; the trainer/generator logprob diff is -0.005 at every setting, and all rollouts completed with none truncated. The effect on learning past 10 steps is not measured, so the recipe takes `target_offpolicy_steps` as an argument.
00f9a1c to
687fe43
Compare
Decoder.forward now embeds and calls forward_embeddings (the layers, final norm and LM head), with the same signature and docstring as #6025. Models override forward_embeddings where their tail differs (Muse Spark residual and final-norm dtypes, Kimi K3 attention-residual blocks with a keyword-only block_residual_TND, Muse Glimmer blocks without padding mask or aux-loss denominator), and the multimodal forwards end with self.forward_embeddings. This replaces the _forward_layers helpers in Muse Spark and Kimi K3 and the copied layer loops in Qwen3.5 and Muse Glimmer. Loss and grad_norm stay bitwise identical to the base on all five families' text and multimodal debug flavors.
…del classes (#6084) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why Whether a model has a vision encoder is decided in three places: the flavor (`vision_encoder=None`), the RL generator (`keep_vision_encoder` in `build_inference_model`, which raises if a text-only engine gets a config with an encoder), and runtime `vision_encoder is None` branches inside every multimodal model. `MultimodalModel` doesn't mean "has encoders": on main, the Qwen3.5, Kimi K3/K2.x and Muse Glimmer text flavors are `MultimodalModel`s with their encoders set to None, and the Muse Spark text flavors build both encoders and skip them with `dataset_modalities=()`. So callers fall back to `getattr(config, "vision_encoder", None)`. **Example.** ```python # Before (main) build_model_config("9B") # Qwen35Model.Config(vision_encoder=None) -- a MultimodalModel build_model_config("9B_mm") # Qwen35Model.Config(vision_encoder=...) build_inference_model(cfg, ..., keep_vision_encoder=supports_multimodal(wrapper)) # After build_model_config("9B") # Qwen35Model.Config -- Decoder, no encoder field build_model_config("9B_mm") # Qwen35MultimodalModel.Config -- vision_encoder required build_inference_model(cfg, ...) # builds exactly what the config says replace(build_model_config("9B_mm"), vision_encoder=None) # ValueError ``` ## What changed - **Two classes per family with encoders**: a text-only `Decoder` subclass and a multimodal subclass of it and `MultimodalModel` whose config requires its encoders. Text flavors build the text class, multimodal flavors the multimodal one. The text class is listed first in both the model and `Config` bases, because dataclass fields resolve over the reversed MRO (documented in `torchtitan/models/README.md`). Kimi K2.5 is the exception, see follow-ups. | Family | Text class | Multimodal class | | --- | --- | --- | | Qwen3.5 (+ qwen3_6 / qwen3_8 flavors) | `Qwen35Model` | `Qwen35MultimodalModel` | | Kimi K3 | `KimiK3Model` | `KimiK3MultimodalModel` | | Kimi K2.x | `KimiK2Model` (new; Moonlight) | `KimiK25Model` | | Muse Glimmer | `MuseGlimmerModel` | `MuseGlimmerMultimodalModel` | | Muse Spark | `MuseSparkModel` | `MuseSparkMultimodalModel` | Flavor names are unchanged. For Qwen3.5, Kimi K3, Muse Glimmer and Muse Spark, the plain flavors are text-only and `_mm` adds the encoders. The qwen3_6 / qwen3_8 flavors already carried a vision encoder by default and stay multimodal. - `MultimodalModel.Config.__post_init__` raises when no encoder is set. Config-driven `vision_encoder is None` branches are removed, including the ones guarding main's explicit TP collectives around the vision scatter (`maybe_gather_tp_input`, `replicate_to_residual`). Runtime None handling stays where pipeline stages after the first drop the encoders. - Text classes reuse `Decoder.forward` / `Decoder.preprocess_inputs` where numerically identical. Where the tail after the embedding differs, the model overrides `Decoder.forward_embeddings`: Kimi K3 (attention-residual blocks, keyword-only `block_residual_TND`) and Muse Glimmer (blocks without padding mask or aux-loss denominator) are new, and Muse Spark's override (from #6025) moves to the text class. Multimodal forwards end with `self.forward_embeddings(...)`. - `annotate_input_spmd_types` (shared, so it applies to every model) now calls `annotate_spmd_types()` on non-tensor inputs, or the values of a mapping input such as `attention_metadata`, that implement the new runtime-checkable `SpmdAnnotatedInput` protocol. This replaces the per-model GDN/KDA metadata annotation (`annotate_linear_attention_metadata`, deleted), and also types full-attention varlen offsets. Checked with spmd typechecking (see Testing). - Kimi K3 drops its `parallelize` override. `MultimodalModel.parallelize` already applies activation remat to the encoder, and the override's `annotate_replicated_parameters` call had nothing left to annotate: every Kimi K3 parameter's module has a `ShardingConfig`. Typechecked runs pass without it. - State dict adapters choose the vision mapping by config type. A text flavor still loads the decoder from the multimodal HF checkpoint. - RL: `keep_vision_encoder` is deleted from `build_inference_model`. The Controller check is two-way: `vision_processor` set requires a multimodal generator model with a vision encoder, and a multimodal generator model requires `vision_processor`. - Kimi K2.x: Moonlight builds the new `KimiK2Model(DeepSeekV3Model)` instead of `KimiK25Model(vision_encoder=None)`. It keeps Kimi's QK-clip optimizer hook and HF adapter (plain `DeepSeekV3Model` would silently drop both), and pins `local_compile` to empty to keep Moonlight's current regions (see follow-ups). Moonlight's code path changes: it now runs `MTPDecoder.preprocess_inputs` / `forward` (with no MTP layers, the plain `Decoder` path) instead of `KimiK25Model`'s, and it no longer rejects CP, since `KimiK25Model`'s CP rejection is for the vision scatter. Loss and grad_norm are unchanged (the Kimi K2 text row below); CP on Moonlight is not tested. `KimiK25Model` now inherits `DeepSeekV3Model` through `KimiK2Model` (main: `MTPDecoder`). Its config already derived from `DeepSeekV3Model.Config`, and `KimiK2Model` overrides both class attributes `DeepSeekV3Model` adds (`state_dict_adapter_cls`, `_register_optimizer_hooks`), so behavior is unchanged. - **Muse Spark behavior change**: plain flavors (`debugmodel`, `816B-A42B`) no longer build the vision/audio encoders, so checkpoints saved from text runs have no encoder weights, the same trade-off Qwen3.5/Kimi text flavors make. `dataset_modalities` moves to `MuseSparkMultimodalModel`, where it is required and must list at least one modality, so text-only training always means `MuseSparkModel`. - graph_trainer Muse Glimmer: the text-only check moves from its `Config.__post_init__` to its `build_model_config`, which raises for multimodal flavors. - `scripts/checkpoint_conversion/numerical_tests_{qwen3_5,kimi_k3}.py` compare vision parity and now raise a `ValueError` for text-only flavors. - Mechanical (skim): flavor files, `__init__` exports, READMEs, the `numerical_tests_qwen3_5_shard.py` script, recipes, and test updates that follow the class names. ## Alternatives considered - `isinstance(config, MultimodalModel.Config)` without the split: text flavors are `MultimodalModel`s today, so it can't tell them apart. - Keep `vision_encoder: X | None` and check it everywhere: that's the status quo this removes. - Keep Muse Spark text flavors carrying unused encoders: two ways to be text-only, and the generator would build and sync a 1.85B-parameter vision encoder it never runs. ## User-facing changes | Before | After | | --- | --- | | Text flavor config is the family's multimodal class with encoders None | Text flavor config is the text class (no encoder fields) | | `replace(mm_config, vision_encoder=None)` allowed | Raises `ValueError`; use the text flavor | | `build_inference_model(..., keep_vision_encoder=...)` | Argument removed | | Multimodal generator model without `vision_processor` raises in `build_inference_model` | `Controller.Config` raises at config time | | Muse Spark `816B-A42B` / `debugmodel` build encoders, skipped via `dataset_modalities=()` | No encoders; `dataset_modalities` only on `_mm` flavors, and empty raises | ## Numerics Bitwise-identical loss and grad_norm on all 10 steps vs. main `a1f6dcd25` (seed 42, deterministic, flex attention, `scripts/loss_compare.py --export-result` / `--import-result --assert-equal`, grad_norm compared from TensorBoard at full precision). GB300, attn-gym 0.0.18; the four Qwen3.5 configs were rerun on the pinned attn-gym 0.0.20 and are also bitwise equal. | Config | Layout | GPUs | Result | | --- | --- | --- | --- | | Qwen3.5 `debugmodel` | single GPU | 1 | bitwise equal | | Qwen3.5 `debugmodel` | FSDP2 + TP2 + SP | 4 | bitwise equal | | Qwen3.5 `debugmodel_mm` | single GPU | 1 | bitwise equal | | Qwen3.5 `debugmodel_mm` | FSDP2 + TP2 + SP | 4 | bitwise equal | | Kimi K3 `debugmodel` | single GPU | 1 | bitwise equal | | Kimi K3 `debugmodel_mm` | single GPU | 1 | bitwise equal | | Kimi K2.5 `debugmodel` (multimodal) | FSDP 4 | 4 | bitwise equal | | Kimi K2 text: K2.5 `debugmodel` without its encoder (main: `KimiK25Model(vision_encoder=None)`, as Moonlight; here: `KimiK2Model`) | FSDP 4 | 4 | bitwise equal | | Muse Glimmer `debugmodel` | single GPU | 1 | bitwise equal | | Muse Glimmer `debugmodel_mm` | single GPU | 1 | bitwise equal | | Muse Spark `debugmodel` | FSDP2 + TP2 + EP2 + SP | 4 | bitwise equal | | Muse Spark `debugmodel_mm` | TP2 + EP2 + CP2 + SP | 4 | bitwise equal | Muse Spark `debugmodel` matches even though it no longer builds encoders: they were skipped in forward before, received no gradients, and the decoder's init is unchanged on the meta-device build path. Not run: Moonlight 16B itself (adapter mapping verified on synthetic state dicts), CP on Kimi K2 (main rejects it), GPU unit tests. ## Testing - spmd typechecking (`debug.spmd_typechecking`, 3 steps) passes on Llama 3 varlen Ulysses CP2 and TP2 + Ulysses CP2; Qwen3.5 and Kimi K3 multimodal with all-gather-KV CP2 and Ulysses CP2; Qwen3.5 and Kimi K3 text varlen; Kimi K3 text TP2 + EP2 + SP; Kimi K3 multimodal FSDP2 + TP2 + EP2 + SP. - CPU unit + RL suites (`tests/unit_tests/cpu`, `tests/rl/unit_tests/cpu`): no new failures vs. main. - Every flavor of the five families builds as config + meta model with the expected class; `dataclasses.fields` defaults of each multimodal `Config` match the pre-split class. - New `tests/unit_tests/cpu/models/common/test_multimodal.py`: catches a multimodal config with no encoder being accepted. It sets Kimi K3 `debugmodel_mm`'s `vision_encoder=None`, where `MultimodalModel.Config` is the only check (with the check removed, the config is accepted). - `test_vllm_multimodal_wrapper.py`: the Controller test now covers both directions. - Deleted `test_shared_model_builds_without_vision_encoder` (qwen3_8): it built a multimodal flavor with `vision_encoder=None`, which now raises (`test_multimodal.py` covers that). No CPU unit test builds the text-only Qwen3.5 model; the Qwen3.5 text numerics runs above and the RL debug recipes (`rl_grpo_qwen3_5_debug_varlen`) build it. ## Known issues / follow-ups - `KimiK25Model.Config(MultimodalModel.Config, DeepSeekV3Model.Config)` (on main) loses `DeepSeekV3Model.Config`'s `local_compile` default, so Kimi K2.x flavors run with no compiled regions. Left as is (fixing it changes compiled regions); `KimiK2Model.Config` carries a TODO. - `tests/unit_tests/cpu/models/qwen3_5/test_qwen3_5.py` is always skipped by `pytest.importorskip("fla")` (`fla` is in no requirements file). With the guard stubbed out, the same 5 tests fail on main and on this branch (`test_qwen35_always_calls_vision_encoder_twice` x4, `test_qwen35_vision_projections_are_not_dense_tp_boundaries`); the rest pass. - These CPU tests fail on aarch64 on both main and this branch (inductor CPU flex_attention): `test_qwen3_5_mrope_positions.py` (3), `test_lora_forward`, `test_lora_head_only_matches_cross_entropy`.
Based on main, outside the image RL stack. The image rows name recipes from #5825 and #6025, so merge it after those. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why The Model support table in `torchtitan/rl/README.md` lags behind main and the image RL stack: - DeepSeek V3 and Kimi K3 have run RL end to end in CI since #5556 (2026-10-29) and #4680 (2026-10-02), but are listed as "Not supported" and "Support coming soon". Their tests, `rl_grpo_deepseek_v3_debug` and `rl_grpo_kimi_k3_debug_batch_invariant`, run in the RL H100 Integration Tests on every push to main and every 12 hours. - Muse Spark and Qwen 3.5/3.6/3.8 are listed as "text only", but both run image prompts end to end with the image RL stack: `rl_grpo_qwen3_5_0_8b_geometry3k` (Qwen3.5-0.8B on Geometry3K, #5825) and `rl_muse_spark_816b_a42b_slake_lora_gb300` (Muse Spark 816B-A42B on SLAKE, 32 GB300 GPUs, #6025). **Example.** | Model | Before | After | |---|---|---| | Muse Spark | ✅ Supported (text only) | ✅ Supported (text and image) | | Qwen 3.5/3.6/3.8 | ✅ Supported (text only) | ✅ Supported (text and image) | | DeepSeek V3 | Not supported | ✅ Supported (SM90+) | | Kimi K3 | Support coming soon | ✅ Supported (SM90+) | ## What changed - The four rows above. - The intro says how DeepSeek V3 and Kimi K3 were tested, since it differs from the other entries (generator DP and TP at degree 2, EP at degree 4): 3 steps with a debug model on H100, trainer FSDP=2, two generators at TP=1, no EP. Their MLA decode and KDA kernels need SM90+. It also names the two image recipes. - Qwen 3.6 and 3.8 build `Qwen35Model` and share Qwen3.5's vision processor config, so they take the same image path; the image recipe runs Qwen3.5. - The CI table gets the RL H100 Integration Tests badge, the workflow that runs the DeepSeek V3 and Kimi K3 tests. - Unchanged: GPT-OSS (supported; debug RL recipe and bitwise parity test), DeepSeek V4 (no RL code yet), FLUX (diffusion model, no generator path), Kimi K2.7 (no RL recipe or test). ## Testing Docs only. `pre-commit run --files torchtitan/rl/README.md` passes locally without the lychee link check, which needs GitHub access; CI runs it. The new badge points at the existing `integration_test_rl_h100.yaml` workflow.
Replaces #5998, which GitHub closed as merged when a stack reorder pushed its base branch (#5845's) on top of it. Nothing reached main, and a merged PR cannot be reopened. Review comments so far are on #5998.
Summary (human-written)
Stack (image RL; review bottom up, each PR is one commit on the one below):
0. #5873 [multimodal] VisionProcessor: one per-model image and video processor (merged)
This PR has three commits: Muse Spark image RL and the SLAKE recipe; a generator fix for preempted image requests; the recipe's
target_offpolicy_stepsdefault.Why
Image RL runs only Qwen3.5. The Muse Spark renderer rejects image parts.
The generator assumes M-RoPE: the vLLM HF config always gets an
mrope_section. Muse Spark uses 1D positions for image tokens.The generator's multimodal wrapper keeps its own copy of the decoder layer loop, which skips Muse Spark's residual and final-norm dtypes.
A preempted image request can crash the generator. vLLM drops the data of images that a new request's prefix-cache hit covers before sending the request to the worker (
strip_covered_mm_data). With the V1 model runner, a preempted request resumes from the worker's copy of its features. If its prefix blocks were evicted in the meantime:_gather_mm_embeddingsraises "Encoder cache miss" and the engine loop dies.GRPO samples share their group's prompt, so all but the first hit the prefix cache over their images. The first Muse Spark 816B SLAKE validation run crashed this way at step 4, twice, each time on a resumed request (128 prefix-cached tokens, encoder run scheduled). That run lacked [rl] Generator weight loads: finish the lm_head group's forward before resharding it #5982, so the preemption came from max-length garbage rollouts. Any preemption with eviction hits this bug, though.
Example. A SLAKE prompt with one image, rendered for Muse Spark:
What changed
Muse Spark renderer: built with a vision processor, an image part
{"type": "image", "path": ...}renders as<|image_start|>+ N x<|patch|>+<|image_end|>, as in Muse Spark's multimodal SFT data. N comes from the patch grid of the size in the file header.multi_modal_datacarries each image's file hash, grid and<|patch|>run, asQwen35ImageRefRendererdoes, andbridge_to_next_turnplaces a later turn's images after the previous prompt's. Without a vision processor, an image part still renders as one<|patch|>, which the multimodal SFT data expands ([data] Multimodal chat SFT: image in the user turn, loss on the answer only #5885).Models:
Decoder.forward_embeddingsruns the decoder after the token embedding, andforwardcalls it (mechanical split);Qwen35Model.forwardends with it too, so each model has one layer loop that the trainer and the generator share (bitwise-identical loss, see Numerics). Muse Spark overrides it with its residual and final-norm dtypes, addsget_vision_embeds, and takes the RL microbatch's bank rows (image_vision_bank_indices_T, the Qwen3.5 name).Generator: image tokens of a model without M-RoPE get 1D positions. The HF config gets
mrope_sectiononly forMRoPE.Config(get_mrope_config, which [rl] Train on image prompts, with a Geometry3K recipe #5825's controller check ofbuild_mrope_positionsuses too), and positions are transposed only when they are 3D. The multimodal wrapper callsforward_embeddingsinstead of copying the layer loop.Batcher: unchanged. The SLAKE recipe leaves
Batcher.Config.build_mrope_positions([rl] Train on image prompts, with a Geometry3K recipe #5825) False, as Muse Spark's SFT recipe leaves the collator's;Controller.Configchecks it against the trainer model.SLAKE example (
torchtitan/rl/examples/slake): the English release, closed and open questions, with knowledge-graph questions dropped; the short-answer instruction from Muse Spark's SLAKE SFT recipe; reward by exact match after normalization.Recipe
rl_muse_spark_816b_a42b_slake_lora_gb300:wqkv,woandoutput_gate, with the generators loading the HF base (adapter-only syncs, [rl] LoRA RL: generators load the base checkpoint, weight syncs carry only the adapters #5844);target_offpolicy_steps(7, third commit) are arguments.The frozen bf16 base needs [distributed] Store frozen parameters in param_dtype #5894 (frozen parameters stored in
param_dtype, now on main) to fit the 8-GPU trainer. Adapter-only syncs need [rl] Generator weight loads: finish the lm_head group's forward before resharding it #5982 (generator weight loads finish the lm_head group's forward before resharding it). Without [rl] Generator weight loads: finish the lm_head group's forward before resharding it #5982 the generator's lm_head is corrupted from the third sync on.Generator, second commit:
keep_prefix_cached_image_datamakes the scheduler send every new request's image data when the engine serves images. The engine core and its worker run in the generator's process, so the worker's features are the scheduler's own objects and keeping the data costs no memory.Recipe, third commit:
target_offpolicy_stepsdefaults to 7. With zero-std groups dropped, the run needs ~118 generated groups per step for 32 kept ones, so rollout supply is capped by the controller's active groups,(target_offpolicy_steps + 1) x P, not by the number of generators.Unchanged: Qwen3.5's M-RoPE path (3D positions,
mrope_section), and text-only rendering for Muse Spark.Alternatives considered
target_offpolicy_steps: at 3, two more generators (48 GPUs) only reach 29.4 s per step, vs 24.0 s at 7 on 32 GPUs.Numerics / performance
Muse Spark Open 816B-A42B on SLAKE, 32 GB300 GPUs (8-GPU trainer, three 8-GPU generators), the recipe's defaults before the third commit (32 x 16,
target_offpolicy_steps3, 10 steps), with #5894 and #5982. The comparison run uses the same configuration on the development branch this PR was ported from. Medians are over steps 5-10.All 2,602 rollouts completed, none truncated. Prompt lengths match, so the Muse Spark image renderer emits the same tokens as the development branch's. Time per request outside the generator (router hop and payload): 13 ms.
target_offpolicy_stepson the same 32 GPUs and tree (medians of steps 5-10):target_offpolicy_stepsAt 7 the trainer never waits: 1.5x the samples per second of 3. All rollouts completed, none truncated.
Qwen35Model.forwardending withforward_embeddings(no computation change):scripts/loss_compare.pybefore vs after on the Qwen3.5 debug model (qwen35_debugmodel, cc12m-test with M-RoPE positions, FSDP=2, 20 steps, seed 42, deterministic, accelerator graphs off since the multimodal batches change shape each step): loss and grad norm bitwise identical at every step (TensorBoard values, max difference 0.0).Testing
<|patch|>run with the file hash; a bridge places new images after the previous ones;test_scheduler_sends_prefix_cached_image_data_to_the_worker: a request whose prefix-cache hit covers its image still sends the image data to the worker. Fails without the second commit (the data is None).pytest tests/rl/unit_tests/cpu tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/models/common: 1009 passed.pytest tests/rl/unit_tests/cpu/test_slake.py: 18 passed. The 5 failures (test_dapo_mathMath-Verify worker start,test_lora_forwardinductor ABI) fail the same way on the base branch in this environment.Known issues / follow-ups
target_offpolicy_steps7 (mean policy age 4 instead of 1.4). The effect on learning past 10 steps is not measured; the recipe takestarget_offpolicy_stepsas an argument, so a long run that suffers from staleness can lower it.keep_prefix_cached_image_datais a workaround (TODO in code): remove it once vLLM resends a resumed request's dropped data.