Repository navigation
Conversation
This was referenced Nov 5, 2026
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
from
November 6, 2026 07:22
7ce1d2d to
bb25357
Compare
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
from
November 8, 2026 06:07
bb25357 to
21bf0db
Compare
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
2 times, most recently
from
November 8, 2026 06:15
110a2c3 to
379ae9b
Compare
wwwjn
added a commit
that referenced
this pull request
Nov 8, 2026
…#5873) **Stack** (image RL for Qwen3.5; review bottom up, each PR is one commit on the one below): 0. **→** #5873 [multimodal] VisionProcessor: one per-model image and video processor 1. #5823 [multimodal] Image-reference Qwen3.5 renderer and shared M-RoPE positions 2. #5824 [rl] Image prompts through rollouts and the vLLM generator 3. #5825 [rl] Train on image prompts, with a Geometry3K recipe 4. #5844 [rl] LoRA RL: generators load the base checkpoint, weight syncs carry only the adapters 5. #5845 [rl] CUDA graphs for the generator's vision encoder --- ## Summary TorchTitan has no image processor object. A model's image preprocessing is spread over two configs and a set of free functions in `multimodal/utils/`, glued together with keyword arguments: ``` today: VisionProcessor.Config (mm_datasets.py) one per dataset entry, 11 image fields; it is the Grain row processor, not an image processor | each model recipe replace()s them with its values (Muse, Kimi, Glimmer); | Qwen relies on the defaults v 11 kwargs into every sample_processor hook utils/image.py, utils/video.py free functions: process_image / process_video (decode, resize, normalize), smart_resize, calculate_vision_tokens, vision_to_patches MultiModalCollator.Config second copy of patch_size / temporal / merge / patch_order v collate_images: vision_to_patches per item, in the collator ``` Image preprocessing is fixed by the model, like the tokenizer: the patch and merge sizes are the shapes of the vision encoder's patch embedding and merger, and the resize rule and normalization are how the encoder was trained. Hugging Face ships it per checkpoint (`preprocessor_config.json`, `video_preprocessor_config.json`), next to `tokenizer.json`. This PR makes it one object per model, placed and passed like the tokenizer: ``` Trainer.Config tokenizer = MultiModalTokenizer.Config(**QWEN3_5_SPECIAL_TOKENS) vision_processor = VisionProcessor.Config(**QWEN3_5_VISION_PROCESSOR_KWARGS) Trainer builds it once -> DatasetBuildContext(tokenizer=..., vision_processor=...) |-- Grain VisionSampleProcessor -> hook(sample, tokenizer, vision_processor) | resize_and_normalize(image) / resize_and_normalize_video(frames): decode, resize, normalize, per item | -> float32 (T, H, W, C) pixels; num_placeholder_tokens(grid_thw) placeholders |-- MultiModalCollator.collate_images: patchify(pixels) per item (as main's collator does) -> concatenated float32 patches + stacked grid_thw ``` ### `VisionProcessor` (`components/data/multimodal/vision_processor.py`) - One config for a model's images and video frames: patch, temporal-patch and merge sizes, mean/std, the resize rules, the patch order and the interpolation mode. - The two steps main already splits between the sample processor and the collator: - `resize_and_normalize(image)`: decode, resize, normalize one image on the CPU -> float32 `(1, H, W, C)` pixels and the `(3,)` patch grid they will have; `resize_and_normalize_video(frames)` does the same for decoded frames; - `patchify(pixels)`: cut them into float32 `(num_patches, patch_dim)` patches -> `(pixel_values, grid_thw)`. - `num_placeholder_tokens(grid_thw)` gives the placeholder count. - Resize rules are `Function` configs (`config/function.py`), each with only its own budget fields: ```python VisionProcessor.Config( ..., # patch sizes, mean/std, patch order: describe the encoder, shared by images and frames resize=PixelBudgetResize.Config(min_pixels=65_536, max_pixels=16_777_216), # images video_resize=PixelBudgetResize.Config(min_pixels=65_536, max_pixels=16_777_216), # every video frame ) ``` `PixelBudgetResize(min_pixels, max_pixels)` (Qwen-VL), `NaViTPatchGridResize(max_patches, max_patches_per_side)` (Kimi) and Muse Spark's `MuseGlimmerPatchGridResize(max_image_tokens)`. `video_resize=None` means the model takes no video (Kimi, Muse Glimmer): `resize_and_normalize_video` raises. - Decoding and resizing are private methods (`_decode_image`, `_resize`). A model whose preprocessing does not fit a resize rule (tiling, cropping) overrides `resize_and_normalize`, the way a Hugging Face processor overrides `_preprocess`. - torchvision stays optional: `vision_processor.py` imports it only inside the methods that decode and resize. So model flavors configure the resize rules, and `trainer.py`, `loader.py`, `types.py` and `validator.py` import and type the processor directly, without torchvision; text-only configs load with torchvision and av blocked. - The Grain row processor `mm_datasets.VisionProcessor` becomes `VisionSampleProcessor` (like `FluxSampleProcessor`), which frees the name. ### Why one processor for images and video A video is a stack of frames the encoder patches like images, so the patch sizes, mean/std and patch order must be the same for both; only the resize budget can differ. Two configs would be two copies that have to stay equal: both in-tree video configs were `dict(..._IMAGE_PROCESSOR_KWARGS)`. vLLM (`Qwen2VLMultiModalProcessor`), SGLang (`QwenVLImageProcessor`), qwen-vl-utils, LLaMA-Factory and verl also keep one processor per model with a separate video budget. Hugging Face splits the classes because its video processor also decodes the video and samples frames; here the dataset does that, and timestamps and prompt expansion stay in the sample hook. Qwen3.5's Hugging Face `video_preprocessor_config.json` budgets the whole clip (4,096 to 25,165,824 pixels), while the dataloader has used the per-frame image budget for video. This PR keeps the current values (TODO at `video_resize` in `QWEN3_5_VISION_PROCESSOR_KWARGS`); a clip-wide rule is another `video_resize` rule. ### Per-model settings, next to the special tokens Each model keeps a dict of `VisionProcessor.Config` keyword arguments where it keeps its special tokens, and recipes build the config the way they build the tokenizer's: | settings | where (next to) | users | |---|---|---| | `QWEN3_5_VISION_PROCESSOR_KWARGS`; `QWEN3_6_VISION_PROCESSOR_KWARGS` / `QWEN3_8_VISION_PROCESSOR_KWARGS` = `dict(QWEN3_5_VISION_PROCESSOR_KWARGS)` | `models/qwen3_*/flavors.py` (`QWEN3_*_SPECIAL_TOKENS`) | 9 Qwen recipes, HF numerical test | | `KIMI_K2_5_VISION_PROCESSOR_KWARGS`, `KIMI_K3_VISION_PROCESSOR_KWARGS` (images only) | `models/kimi_*/flavors.py` | Kimi recipes, HF numerical tests | | `MUSE_SPARK_VISION_PROCESSOR_KWARGS`, `MUSE_GLIMMER_VISION_PROCESSOR_KWARGS` (images only) | the Muse recipe files (`MUSE_*_SPECIAL_TOKENS`) | Muse recipes | The Qwen values match the Hugging Face `preprocessor_config.json`, which is identical across all 11 Qwen3.5 / 3.6 / 3.8 vision checkpoints (0.8B to 397B-A17B), as are their special tokens. Recipes that tune the budget `replace` the resize rule on the built config (the Kimi K3 debug recipe keeps its small `max_patches=256`). The patch sizes are written in the dict and in the encoder config, as in Hugging Face's `preprocessor_config.json` and `config.json`; a test checks every multimodal recipe's processor against its vision encoder. The dicts are typed `dict[str, Any]`: Pyrefly cannot type-check a heterogeneous dict unpacked into keyword arguments. ### Why an object and not `process_image()` RL on images (#5823-#5825) needs the same preprocessing in three processes: the rollout worker's renderer (placeholder count only), the generator and the trainer (pixels). A function does not fit: 1. **Settings.** `process_image` takes 11 keyword arguments. Every process would need them from somewhere: one config passed to each is a config plus a function, i.e. an object; loose kwargs are N copies. 2. **Errors.** `process_image` turns every exception into `None`, the pretraining dataset's skip-the-sample policy. In RL a bad image should fail that rollout with the real error (the rollouter records it as an errored rollout), not disappear. `resize_and_normalize` raises; the dataset hook keeps the skip policy around it. With the object, every process builds its own instance from the one config and calls `resize_and_normalize` + `patchify` (generator, trainer) or only counts placeholder tokens (renderer). ### Other changes - The data flow is main's: the sample processor emits resized, normalized float32 pixels (`pixel_values` / `pixel_values_videos`, so packing buffers hold the same bytes as on main) and `collate_images` patchifies each item, now with `processor.patchify` instead of the collator's own patch fields. - Removed: `multimodal/utils/image.py`, `utils/resize.py` (both now in `vision_processor.py`) and `utils/video.py` (`load_npy_video_frames` moved to the synthetic test dataset that reads `.npy` frames; `load_video` had no callers); `process_image`, `process_video`, `smart_resize`, `calculate_vision_tokens`; the 11 image fields of the Grain `VisionProcessor.Config`, the 4 patch fields of `MultiModalCollator.Config`, the recipes' `replace(processor, ...)` blocks and `_multimodal_collator_config` helpers. - The M-RoPE collator rejects a non-block patch order when it is built instead of on every microbatch, and `VisionProcessor.Config` rejects an unknown one. - The validator, the torchft trainer and the checkpoint-conversion numerical tests use the processor. ## Evidence Not a numerics change: on 6842fdd3f (this PR before its rebase onto 879aad3), the first microbatches of every multimodal recipe's dataloader are bitwise equal to main (c2579f7), all tensors (`input`, `labels`, `positions`, `padding_mask`, `pixel_values`, `grid_thw`, `pixel_values_videos`, `grid_thw_videos`, `mrope_positions`, `waveforms`): | recipe | microbatches | media | |---|---|---| | `qwen35_debugmodel` | 4 | images, M-RoPE | | `qwen35_debugmodel_video` | 4 | videos, M-RoPE | | `qwen36_debugmodel`, `qwen38_debugmodel` | 2 each | images, M-RoPE | | `kimi_k2_5_debugmodel`, `kimi_k3_debugmodel` | 4 each | images, NaViT resize, raster order | | `muse_glimmer_debugmodel_mm` | 4 | images, raster order | | `muse_spark_debugmodel_mm` | 8 | 5 with images, 3 with videos, 3 with audio | Loss and `grad_norm` are bitwise equal to main for 20 steps on an earlier revision (85a08a8) whose dataloader output this revision matches bitwise (`scripts/loss_compare.py c2579f7 85a08a8 --assert-equal --metrics=loss,grad_norm`; 8 GPUs, FSDP, seed 42, deterministic, seed checkpoint), with accelerator graphs off as the multimodal integration tests run (media shapes change every step): | config | step 1 | step 10 | step 20 | |---|---|---|---| | `qwen35_debugmodel` on `cc12m-test` | 12.88083 / 1.4373 | 2.33800 / 1.6869 | 1.80099 / 1.0610 | | `qwen35_debugmodel_video` on `synthetic-video-text` | 12.87572 / 2.5192 | 0.15311 / 0.4581 | 0.12245 / 0.1759 | | `kimi_k2_5_debugmodel` on `cc12m-test` (DistMuon, no seed checkpoint: DistMuon needs DTensor parameters, so both runs start from the seed-42 init) | 7.97354 / 8.1438 | 4.72706 / 4.5614 | 3.94997 / 2.8333 | (loss / grad_norm.) NOTE: on main, the first launch on a cold compile cache differs from later launches from step 2 (main run 2 vs main run 1 mismatch at step 2, the same way); the runs above use a warm cache for both sides. Against Hugging Face, `scripts/checkpoint_conversion/numerical_tests_qwen3_5.py` (Qwen3.5-0.8B, 10 image samples) preprocesses with the Qwen3.5 processor config; on the previous revision (a37b3f7, same preprocessing), 0 of 1,966,080 pixels differ from Hugging Face's image processor (max diff 1.2e-7), and the logits match (top-1 100%, mean KL 2.5e-5). The output is identical to main's. ## Test GPU integration tests (8x A100, `--test_suite models` and `h100` multimodal entries) pass on an earlier revision (c85334b) whose dataloader output this revision matches bitwise: `qwen3_5_moe` FSDP+TP+EP(+PP), `qwen3_5` FSDP+TP+varlen+per-op SAC, `kimi_k2_5_muon` FSDP+EP and PP+FSDP+EP, `muse_glimmer_mm` FSDP+TP+SP and TP+CP+PP+SP, `muse_spark_mm` FSDP+TP+CP+EP+SP, `qwen3_5_mm` all-gather-KV CP and Ulysses CP, with losses decreasing over their steps. The two `kimi_k3_mm` CP entries need sm90 (`gate_transform`) and were not run. CPU unit tests on 6842fdd3f (full `tests/unit_tests/cpu`, no GPU visible): 1,948 passed; the 5 failures (2 LoRA tests, 3 Qwen3.5 M-RoPE routing tests) fail the same way on main (Inductor C++ build in the local env), and `tests/unit_tests/cpu/quantization` needs torchao. Updated tests: - `test_mm_dataset_preprocessing.py`: `patchify(resize_and_normalize(...))` equals step-by-step decode -> resize -> normalize -> patchify bitwise (block and raster order), and `resize_and_normalize`'s grid equals `patchify`'s; the NaViT resize rule's geometry and padding, interpolation mode, video frames resized by `video_resize` (not `resize`) with padding, video rejected without `video_resize`, placeholder counts, patch order permutation, an unknown patch order rejected; an unreadable image drops its sample; a missing processor raises. - `test_qwen_multimodal_data.py`: the Grain `VisionSampleProcessor` passes the trainer's processor and requires one; every multimodal recipe's processor matches its vision encoder (Qwen3.5/3.6/3.8 including the 27B and 35B-A3B recipes, Kimi K2.5, Kimi-VL, Kimi K3, Muse Glimmer, Muse Spark); the M-RoPE collator rejects a raster patch order when built. - Collator, checkpoint-resume and synthetic video tests use the processor; the `.npy` frame loader's test moved with it to `test_synthetic_multimodal_data.py`.
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
from
November 8, 2026 08:22
379ae9b to
9deec77
Compare
wwwjn
added a commit
that referenced
this pull request
Nov 8, 2026
…ions (#5823) **Stack** (image RL for Qwen3.5; review bottom up, each PR is one commit on the one below): 0. #5873 [multimodal] VisionProcessor: one per-model image and video processor 1. **→** #5823 [multimodal] Image-reference Qwen3.5 renderer and shared M-RoPE positions 2. #5824 [rl] Image prompts through rollouts and the vLLM generator 3. #5825 [rl] Train on image prompts, with a Geometry3K recipe 4. #5844 [rl] LoRA RL: generators load the base checkpoint, weight syncs carry only the adapters 5. #5845 [rl] CUDA graphs for the generator's vision encoder --- ## Summary RL on image prompts needs each image's placeholder count at render time, and the same pixels the model was trained on in the generator and the trainer. Today the only path is the renderers library's Qwen3.5 renderer, which runs the Hugging Face image processor inside `render()` and returns float32 `pixel_values`. In RL that costs ~9 ms per prompt for every sample of every group, ships megabytes of pixels per prompt between processes, and is a second preprocessing implementation next to the trainer's. On top of #5873's per-model `VisionProcessor` (`VisionProcessor.Config(**QWEN3_5_VISION_PROCESSOR_KWARGS)`), this PR adds: - **`VisionProcessor.grid_thw(height, width)`**: the patch grid `resize_and_normalize` gives a `height x width` image, without decoding it. A renderer that reads the size from the file header gets the grid and `num_placeholder_tokens(grid)` from it. - **`Qwen35ImageRefRenderer`** (`models/qwen3_5/renderer.py`): the library's `Qwen35Renderer` with only `_process_image` replaced, so rendering emits the same placeholder runs and a hash per image, but no `pixel_values`: ``` image file --read once--> bytes --hash_image_file--> hash (mm_hashes entry, same from any path) \--PIL header size--> grid_thw(h, w) --> grid (1, H/16, W/16) --> num_placeholder_tokens(grid) ``` - **`RendererConfig.build(tokenizer=..., vision_processor=...)`**: the vision processor is a build argument, like the tokenizer, so TitanRL (#5824) passes the one it builds from `Controller.Config.vision_processor` to the renderer, the generator and the trainer. `RenderersConfigAdapter.build` sets it on an in-tree renderer's config (`CustomRendererConfig`), and raises for a library renderer or when the renderer config already sets one; `MuseSparkRendererConfig.build` takes it too and raises (it reads no image files). - **`get_mrope_positions(num_tokens, vision_items)`** (`multimodal/mrope.py`): 3D M-RoPE positions from placeholder offsets and token grids, now the one implementation. `MultiModalCollator._build_mrope_positions` finds each packed document's placeholder runs and calls it, merging each grid with its modality's processor (`spatial_merge_size`). RL takes the offsets from the renderer, because a placeholder id the policy samples in a completion is text, not an image. ## Evidence - Dataloader microbatches, `mrope_positions` included, are bitwise equal to main for 8 multimodal recipes (Qwen3.5 image and video, Qwen3.6, Qwen3.8, Kimi K2.5, Kimi K3, Muse Glimmer, Muse Spark). - On Geometry3K's 2,101 train prompts, `Qwen35ImageRefRenderer` gives the library renderer's token ids and placeholders (0 mismatches), at 1.2 ms vs 9.4 ms per prompt (devvm CPU). Measured with the previous revision's `resized_size`; `grid_thw` computes the same grid from the same resize rule. ## Test - `tests/unit_tests/cpu/components/data/test_mm_dataset_preprocessing.py`: `grid_thw` equals the grid `resize_and_normalize` gives (Qwen-style, and Kimi-style NaViT with padding). - `test_mrope_positions.py`: direct, and through the collator across packed documents; the collator raises when a microbatch has more placeholder runs than grids (a bare `StopIteration` there would end Grain's batch iterator, i.e. the data, silently). - `tests/unit_tests/cpu/models/qwen3_5/test_qwen3_5_renderer.py`: token ids, placeholders and grids equal the library renderer's with the HF processor Qwen3.5 ships, and `patchify(resize_and_normalize(...))` equals its pixel values; hashes independent of the path; needs a vision processor; built through `from_renderers(...).build(vision_processor=...)`. Downloads the `Qwen/Qwen3.5-0.8B` tokenizer, so it runs in CPU CI; `QWEN3_5_TOKENIZER` points it at a local copy. - `tests/unit_tests/cpu/components/test_renderer.py`: `build` rejects a vision processor for a library renderer, and one set twice.
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
from
November 8, 2026 09:42
9deec77 to
f730673
Compare
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
from
November 9, 2026 04:30
f730673 to
af6082a
Compare
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
2 times, most recently
from
November 10, 2026 00:25
0465b3f to
e28710b
Compare
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
2 times, most recently
from
November 10, 2026 18:52
281c9fc to
0f4373e
Compare
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
2 times, most recently
from
November 11, 2026 01:17
db50202 to
80d9d72
Compare
wwwjn
changed the base branch from
wwwjn/image-rl/4-rl-lora-adapter-sync
to
wwwjn/image-rl/4b-muse-slake-recipe
November 11, 2026 01:27
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
2 times, most recently
from
November 11, 2026 05:44
b7f6be5 to
b06ebad
Compare
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
from
November 11, 2026 07:22
b06ebad to
570b0f1
Compare
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
from
November 12, 2026 02:22
570b0f1 to
8b4914d
Compare
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
2 times, most recently
from
November 12, 2026 05:40
134212a to
3b766e8
Compare
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
from
November 12, 2026 05:57
3b766e8 to
d008d6b
Compare
fegin
pushed a commit
that referenced
this pull request
Nov 12, 2026
… 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.)
wwwjn
added a commit
that referenced
this pull request
Nov 13, 2026
…park 816B (#6025) 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) <!-- 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 (merged) 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 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_steps` default. ## Why 1. Image RL runs only Qwen3.5. The Muse Spark renderer rejects image parts. 2. The generator assumes M-RoPE: the vLLM HF config always gets an `mrope_section`. Muse Spark uses 1D positions for image tokens. 3. The generator's multimodal wrapper keeps its own copy of the decoder layer loop, which skips Muse Spark's residual and final-norm dtypes. 4. 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: - the scheduler schedules the image's encoder run; - the worker skips the run for lack of data; - `_gather_mm_embeddings` raises "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 #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: ``` prompt: [{"type": "image", "path": "<image file>"}, {"type": "text", "text": "Which organ is shown?"}] before: Muse Spark renderer -> one <|patch|> per image (the SFT dataset expands it) generator HF config -> always mrope_section after: tokens <|image_start|> <|patch|> x N <|image_end|> Which organ is shown? ... positions 1D, like text: no mrope_section; the recipe leaves build_mrope_positions False, so no mrope_positions N the patch grid of the image size in the file header ``` ## 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_data` carries each image's file hash, grid and `<|patch|>` run, as `Qwen35ImageRefRenderer` does, and `bridge_to_next_turn` places 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 (#5885). - **Models**: `Decoder.forward_embeddings` runs the decoder after the token embedding, and `forward` calls it (mechanical split); `Qwen35Model.forward` ends 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, adds `get_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_section` only for `MRoPE.Config` (`get_mrope_config`, which #5825's controller check of `build_mrope_positions` uses too), and positions are transposed only when they are 3D. The multimodal wrapper calls `forward_embeddings` instead of copying the layer loop. - **Batcher**: unchanged. The SLAKE recipe leaves `Batcher.Config.build_mrope_positions` (#5825) False, as Muse Spark's SFT recipe leaves the collator's; `Controller.Config` checks 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`: - LoRA r8/a16 on `wqkv`, `wo` and `output_gate`, with the generators loading the HF base (adapter-only syncs, #5844); - Dist-MoE on both roles, without in-place WGRAD accumulation into the frozen experts; - the measured 32-GPU configuration, fixed in the recipe: an 8-GPU trainer and three 8-GPU generators, 32 prompts x 16 samples, 8K tokens per microbatch, low reasoning effort, 4K response tokens, zero-std groups dropped. Only the paths and `target_offpolicy_steps` (7, third commit) are arguments. The frozen bf16 base needs #5894 (frozen parameters stored in `param_dtype`, now on main) to fit the 8-GPU trainer. Adapter-only syncs need #5982 (generator weight loads finish the lm_head group's forward before resharding it). Without #5982 the generator's lm_head is corrupted from the third sync on. - **Generator, second commit**: `keep_prefix_cached_image_data` makes 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_steps` defaults 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 - More generators instead of a higher `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_steps` 3, 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. | | this PR | development branch | |---|---|---| | step time | 36.0 s | 36.7 s | | trainer forward/backward | 20.8 s | 20.3 s | | trainer waiting for a batch (zero-std groups dropped) | 14.6 s | 16.3 s | | trainer/generator logprob diff, steps 1-10 | -0.004 to -0.006 | -0.004 to -0.005 | | prompt / response tokens | 726 / 224 | 731 / 223 | | reward | 0.511 | 0.504 | | trainer peak reserved memory | 258.8 GiB | 257.8 GiB | 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_steps` on the same 32 GPUs and tree (medians of steps 5-10): | `target_offpolicy_steps` | step | trainer waits | mean / max policy age | reward | logprob diff | |---|---|---|---|---|---| | 3 | 36.0 s | 14.6 s | 1.4 / 3 | 0.511 | -0.005 | | 5 | 24.0 s (mean 26.9 s) | 10-15 s at 2 of 6 steps | 3.0 / 5 | 0.518 | -0.005 | | **7 (default)** | 24.0 s (mean 23.6 s) | 0.002 s at every step | 4.0 / 7 | 0.526 | -0.005 | At 7 the trainer never waits: 1.5x the samples per second of 3. All rollouts completed, none truncated. `Qwen35Model.forward` ending with `forward_embeddings` (no computation change): `scripts/loss_compare.py` before 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 - New CPU tests: - renderer: an image renders as a `<|patch|>` run with the file hash; a bridge places new images after the previous ones; - vLLM wrapper: the HF config keeps 1D positions for Muse Spark images; - SLAKE dataset, env and rubric; - the recipe puts LoRA on wqkv, wo and output_gate of all 62 layers; - `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. - After the third commit, on the rebased base: `pytest tests/rl/unit_tests/cpu/test_slake.py`: 18 passed. The 5 failures (`test_dapo_math` Math-Verify worker start, `test_lora_forward` inductor ABI) fail the same way on the base branch in this environment. ## Known issues / follow-ups - Staler samples at `target_offpolicy_steps` 7 (mean policy age 4 instead of 1.4). The effect on learning past 10 steps is not measured; the recipe takes `target_offpolicy_steps` as an argument, so a long run that suffers from staleness can lower it. - `keep_prefix_cached_image_data` is a workaround (TODO in code): remove it once vLLM resends a resumed request's dropped data. - The recipe needs #5982 (see What changed); #5894 is on main.
The generator's vision encoder ran eagerly on every call: TitanRL never set vLLM's `cudagraph_mm_encoder`, and the multimodal wrapper did not implement vLLM's `SupportsEncoderCudaGraph`, so only the language model was graphed. On an A100 the eager Qwen3.5-0.8B encoder takes ~20 ms per call for one 64-token image, almost all launch overhead. - `Qwen35VisionEncoder.forward_padded`: the encoder on inputs padded to a fixed patch count, with positions computed beforehand and `segment_ids` (-1 for padding); it reads nothing back to the host. `create_padded_block_diagonal_mask` lets padding attend only to itself. `forward` shares the body and is otherwise unchanged. - `VLLMMultimodalModelWrapper` implements `SupportsEncoderCudaGraph`: token budgets from the vision processor's smallest image to `max_num_batched_tokens`, replay buffers with the batch's patches, position embeddings (from the current weights), RoPE cache and segment ids. - `VLLMEngine.Config.cuda_graph.vision_encoder` (default False) turns it on; the engine raises if it is set without `Controller.Config.vision_processor`, and the wrapper raises at startup for a vision encoder other than Qwen3.5's (e.g. Muse Spark's NaViT, which has no padded forward yet). Local A100, Qwen3.5-0.8B, 48 Geometry3K images x 2 samples, greedy: every encode hit one of the 6 captured graphs; encoder time after warmup 287 ms -> 90 ms (max call 37 -> 13 ms). Graph vs eager outputs differ as much as eager vs eager with different request batching (mean |logprob diff| 0.0169 vs 0.0168).
wwwjn
force-pushed
the
wwwjn/image-rl/5-vision-encoder-cudagraph
branch
from
November 17, 2026 20:13
d008d6b to
87358cc
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary (human-written)
Human note
Stack (image RL; every PR below this one has merged, so this PR is one commit on main):
0. #5873 [multimodal] VisionProcessor: one per-model image and video processor (merged)
Why
The generator's vision encoder ran eagerly on every call: TitanRL never set vLLM's
cudagraph_mm_encoder, and the multimodal wrapper did not implement vLLM'sSupportsEncoderCudaGraph, so only the language model was graphed. On an A100 the eager Qwen3.5-0.8B encoder takes ~20 ms per call for one 64-token image, almost all launch overhead, and each call holds up request admission.Example. Opt in with
VLLMEngine.Config(cuda_graph=VLLMCudaGraphConfig(vision_encoder=True)); on an A100 with Qwen3.5-0.8B (measured below):What changed
Qwen35VisionEncoder.forward_padded: the encoder on inputs padded to a fixed patch count, with positions computed beforehand andsegment_ids(-1 for padding); it reads nothing back to the host, so a graph captured per padded size replays for any images that fit.create_padded_block_diagonal_masklets padding attend only to itself (no fully masked rows, no work added to the images' blocks).forwardshares the body and is otherwise unchanged, so the trainer path does not change.VLLMMultimodalModelWrapperimplementsSupportsEncoderCudaGraph: token budgets from the vision processor's smallest image tomax_num_batched_tokens(vLLM captures powers of 2 in between and runs larger images eagerly); replay buffers hold the batch's patches, position embeddings computed from the current weights, the RoPE cache and segment ids. The vision encoder's FSDP group is unsharded explicitly (a no-op in the generator, which never reshards).VLLMEngine.Config.cuda_graph.vision_encoder(default False) setscudagraph_mm_encoder; it raises withmode="NONE", and the engine raises if it is set withoutController.Config.vision_processor.Numerics / performance
Measured at d0c2b0287: this PR on main 9ea1ef0, before a conflict-free rebase. One A100 node, Qwen3.5-0.8B.
Image features, 8 Geometry3K images, real weights:
forward_paddedvs eagerforward_padded: bitwise equal for 1, 2, 4 and 8 images;forwardvsforward_padded: bitwise equal for 1, 2 and 8 images; for 4 images, at most 1 bf16 ulp on 0.08% of elements;Geometry3K RL (
rl_grpo_qwen3_5_0_8b_geometry3k, 4 GPUs, 20 steps, seed 42), encoder eager vs graph. Medians of steps 5-20, permutation test over the 16 steps:Earlier measurements:
Measured on bb25357, before this PR moved onto #5824's current inputs (vLLM now passes the images' pixel values, not decoded images, so selection and replay buffers read
pixel_values); the capture path is unchanged.Testing
A GPU test that a graph-replayed
forward_paddedmatchesforwardand that garbage in the padded patches changes no image's features; CPU tests for the wrapper's item specs, selection, budget range and segment-id padding, and for the config checks.After the rebase onto 49dbf7a:
pytest tests/rl/unit_tests/cpu/test_vllm_multimodal_wrapper.py tests/rl/unit_tests/cpu/test_generator.py tests/unit_tests/cpu/models/qwen3_5: 86 passed. The 3test_qwen3_5_mrope_positionsfailures (Inductor:undefined symbol ParallelGuard) fail the same way on main in this environment.Known issues / follow-ups