Repository navigation
[multimodal] Image-reference Qwen3.5 renderer and shared M-RoPE positions - #5823
Conversation
|
@claude review this PR |
|
Claude finished @wwwjn's task in 5m 32s —— View job Approve, but please fix one thing before merging: |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The design holds up: the RL path ships file bytes plus a content key, and the trainer and generator each decode with one shared spec. The one blocking issue is that the PR's main equivalence test never runs in CI. This PR touches core data code, so a maintainer still needs to review.
What this PR does. It splits process_image into decode_and_resize_image (uint8) and normalize_image (float32). On top of those it adds the RL steps, all driven by an ImageSpec:
lookup_image: reads the patch grid from the image header and hashes the file into a content key.decode_image_files[_flat]: decode and resize to uint8.patchify[_flat]: normalize and cut into patches, on any device.
It also adds get_mrope_positions, which computes positions from placeholder offsets instead of scanning token ids, and Qwen35ImageRefRenderer, which overrides only _process_image so a render emits placeholders and a key but no pixel_values.
Example.
msg = [{"role": "user", "content": [{"type": "image", "path": "00000_0.png"}, {"type": "text", "text": "Find x."}]}]
Qwen35Renderer.render(msg) -> token_ids, mm_items[0]["pixel_values"] = float32 (N, 1536), ~7.5 ms
Qwen35ImageRefRenderer.render(msg) -> same token_ids, pixel_values=None, mm_hashes=[sha256(file)[:32]], ~1.1 ms
# later, on the generator/trainer:
patchify(decode_image_files([file_bytes], spec), spec) == vision_to_patches(process_image(path, ...)) # bitwise
Must fix
tests/unit_tests/cpu/models/qwen3_5/test_qwen3_5_renderer.py:40: always skipped in CI. Core CPU CI never setsQWEN3_5_TOKENIZER, and the export in #5825 only coverstests/rl/unit_tests/cpu. Thetests/utils.pydocstring claiming the RL CPU CI job sets it is also wrong. Fix: move the file totests/rl/unit_tests/cpu/and move the CI export into this PR, or fall back to the Hub as the muse_glimmer renderer test does.
Should consider
torchtitan/components/data/multimodal/mrope.py:34: this is a second M-RoPE implementation next to the collator's. Merging them now looks like about -70 LoC in the collator, and the equivalence can be checked exactly because the positions are integers.torchtitan/components/data/multimodal/utils/image.py:467:ImageSpecduplicatesVisionProcessor.Config's image fields, and renamesspatial_merge_sizetomerge_size.torchtitan/components/data/multimodal/utils/image.py:551:read_image_file(TokenEnv-only) andlargest_image_grid(vLLM-only) are RL helpers living in the shared data module.tests/unit_tests/gpu/components/data/test_image_patchify.py:39: this test is covered by the second GPU test; delete it.- Low-value tests: in
test_mrope_positions.py,test_docstring_exampleandtest_text_only_positions_repeat_the_token_indexadd nothing overtest_matches_collator_for_one_document.test_rejects_image_cache_maxonly re-checks a config validator. utils/image.py:223:decode_and_resize_imagerepeatsprocess_image's defaults. Both callers pass every argument they care about, so the defaults (or the public name) can go.
Details
- Necessity: the problem is real. Today the only Qwen3.5 image renderer runs the HF processor and returns float32 pixels per sample, and that is a second preprocessing path next to torchtitan's
process_image. Moving only bytes plus a key, with every side decoding using the same spec, is the right layer. The consumers oflargest_image_grid,read_image_file,*_flatandget_mrope_positionsare in #5824 and #5825, which is fine if the stack lands together. - Header grid vs decoded grid:
_grid_thwand_decode_and_resize_image_fileboth go throughresize_to_pixel_budgetwith the same inputs.Image.open().sizeandtorchvision.io.decode_image(no EXIF rotation by default) agree on the stored size.decode_image_files_flatalso raises on a mismatch. - M-RoPE equivalence: the vision offset is the previous max + 1, and text resumes at
next_position + max(t, h//m, w//m), which matches the collator's per-document logic. - CPU/GPU bitwise claim:
to_dtype(scale=True)andnormalizeare IEEE elementwise ops, so the claim is plausible. - The vLLM encoder cache is keyed by content key and could go stale across weight updates; #5824 handles this with
reset_encoder_cache.
Not verified: the renderers==0.1.12 _process_image return contract and the pydantic handling of image_spec (I could not inspect the installed library), and the GPU test results.
| @pytest.fixture(scope="module") | ||
| def tokenizer(): | ||
| return qwen3_5_tokenizer() |
There was a problem hiding this comment.
This file never runs in CI, so its main check (token ids and placeholders equal the library Qwen35Renderer, patches equal the HF processor) is never exercised. unit_test_cpu.yaml runs pytest tests/unit_tests/cpu without setting QWEN3_5_TOKENIZER, so qwen3_5_tokenizer() skips. The snapshot_download that #5825 adds to unit_test_cpu_rl.yaml only covers tests/rl/unit_tests/cpu. The docstring in tests/utils.py ("the RL CPU CI job sets it") is wrong here, and stays wrong for this file after the whole stack lands.
This renderer is only used by RL, so the smallest fix is to move this file to tests/rl/unit_tests/cpu/, and move the QWEN3_5_TOKENIZER export from #5825 into this PR so the test runs at the commit that adds it. The other option is the muse_glimmer renderer test's approach: fall back to downloading Qwen/Qwen3.5-0.8B from the Hub when the variable is unset.
| TODO: make the collator build each document's positions with this, so pretraining and | ||
| RL share one implementation. Changing the pretraining path needs multi-document and | ||
| video equivalence tests and a Qwen3.5 loss comparison against main (cc12m-test). |
There was a problem hiding this comment.
Should consider: this adds a second M-RoPE position implementation next to MultiModalCollator._build_mrope_positions, and the TODO puts off merging them. Merging looks cheap now. The collator already splits each sample into doc_ranges and finds doc_vision_starts, so its per-document body could become get_mrope_positions(doc_end - doc_start, [(s - doc_start, grid) for s, grid in ...], spatial_merge_size=...). That deletes about 70 lines of collator code (the text/vision arange stacking and grid_cache).
The outputs are integer positions, so equivalence can be checked exactly against the existing collator tests (multi-document, video) without a loss run: equal positions mean equal loss. If you keep two implementations, please say in the TODO what actually blocks merging them.
| @dataclass(frozen=True, kw_only=True, slots=True) | ||
| class ImageSpec: | ||
| """The model's image preprocessing; defaults match Qwen3-VL / Qwen3.5. | ||
|
|
||
| The arguments of ``process_image`` + ``vision_to_patches`` for the model's | ||
| vision encoder. It must match the model's vision encoder and the SFT data | ||
| pipeline of the same model, so the generator and the trainer see the pixels | ||
| the model was trained on. | ||
| """ | ||
|
|
||
| patch_size: int = 16 | ||
| temporal_patch_size: int = 2 | ||
| merge_size: int = 2 | ||
| """Patches merged per side into one placeholder token (``spatial_merge_size``).""" |
There was a problem hiding this comment.
Should consider: ImageSpec repeats the image fields of VisionProcessor.Config (mm_datasets.py:423): patch_size, temporal_patch_size, min_pixels, max_pixels, image_mean, image_std, with the same defaults. It also renames one of them: merge_size here, spatial_merge_size there. In the same PR, get_mrope_positions uses spatial_merge_size too. The docstring says it "must match ... the SFT data pipeline of the same model", but nothing ties the two together. A Qwen3.5 recipe that changes max_pixels for SFT can silently disagree with RL.
Two options: use one name per concept (spatial_merge_size, as the SFT config and the vision encoder do), or go further and have VisionProcessor.Config hold an ImageSpec, so SFT and RL share one type. Note that ImageSpec also hardcodes resize_to_pixel_budget and bicubic (_grid_thw, _decode_and_resize_image_file). It is Qwen-VL only by construction, and the docstring could say so.
| @functools.lru_cache(maxsize=64) | ||
| def read_image_file(path: str, key: str) -> bytes: | ||
| """Return the bytes of the image file at ``path``, which must hash to ``key``. | ||
|
|
||
| The renderer read them in `lookup_image`, but the renderers library keeps only | ||
| ``pixel_values`` and the grid of what `_process_image` returns, so `TokenEnv` reads | ||
| the file again for the prompt. Cached: the samples of a GRPO group render together in one | ||
| process, so they share one bytes object, and a message that holds several of them | ||
| pickles the bytes once. |
There was a problem hiding this comment.
Should consider: read_image_file exists only for TokenEnv (#5824). Its docstring is about the renderers library, GRPO groups, and pickling messages, and the lru_cache(maxsize=64) sizing is an RL rollout choice. largest_image_grid is in the same position: its only consumer is vLLM profiling (rl/generator/vllm/multimodal.py). Both are single-consumer RL/vLLM helpers sitting in the shared SFT data module. Moving them next to their consumers in #5824 would keep utils/image.py about image preprocessing.
| on_gpu = patchify([image.cuda() for image in images], _SPEC) | ||
|
|
||
| assert torch.equal(on_gpu.cpu(), patchify(images, _SPEC)) | ||
|
|
||
|
|
||
| def test_trainer_decode_then_gpu_patchify_matches_cpu(tmp_path) -> None: | ||
| # The trainer decodes the shipped files on the CPU and patchifies on the GPU | ||
| # (`TrainingMicrobatch.to_input_dict`). |
There was a problem hiding this comment.
Should consider: test_trainer_decode_then_gpu_patchify_matches_cpu already covers this test. patchify_flat on CUDA calls patchify on CUDA tensors and is compared bitwise with CPU patchify. Delete this one and keep the second; it is the harder path and saves a GPU test.
| def qwen3_5_tokenizer(): | ||
| """The Qwen3.5 tokenizer at ``QWEN3_5_TOKENIZER`` (the RL CPU CI job sets it). | ||
|
|
||
| Skips when the variable is unset; fails when it is set but does not load. | ||
| """ | ||
| path = os.environ.get("QWEN3_5_TOKENIZER") | ||
| if path is None: | ||
| pytest.skip("set QWEN3_5_TOKENIZER to a Qwen3.5 tokenizer directory") | ||
| import transformers | ||
|
|
||
| return transformers.AutoTokenizer.from_pretrained(path) |
There was a problem hiding this comment.
this looks sloppy and doesnt generalize across models
There was a problem hiding this comment.
what is now done on GPU, and why?
in general need better documentation, in the PR summary and in the code (docstring / .md file)
There was a problem hiding this comment.
Patchify being fast on GPU doesn't justify putting it on GPU
- GPU has other important model work to do. Does patchify contend with them?
- what if we do prefetching of multimodal data, does it make things worse? where is the H2D sync?
- before your refactor, is pretraining patchify happening on CPU or GPU? My impression was it happens on CPU, but I could be wrong
- I didn't see the flow of moving things from CPU to GPU. Could you point me to that?
There was a problem hiding this comment.
- Valid concerns: If we put the patchify on CPU we can overlap with previous model training; I want to try running both and see which is faster.
- The image is part of the input, so it must be copies to GPU before being consumed, so before patchify or after patchify, we don't introduce extra copy/H2D sync
- Before the refactor and after the refactor, all of the precessing steps (including resize, normalize, patchify) they all happen on CPU, the refactor PR [multimodal] VisionProcessor: one per-model image and video processor #5873 only defines the 2 APIs
decode_and_resizeandnormalize_and_patchifyto make it easier for caller to decide where - This PR didn't put it on GPU yet, it's the caller's decision whether it should be put on CPU or GPU. The Caller do it in later PRs (Trainer as the caller in [rl] Train on image prompts, with a Geometry3K recipe #5825; Generator call it in [rl] Image prompts through rollouts and the vLLM generator #5824
There was a problem hiding this comment.
And I think overall patchify is a small /tiny ops, and from simplicity, putting pachify on CPU is more easy to reason and aligns with SFT. Let me update.
Edit: and also consolidated the ImageProcessor's current 2 seperate APIs into 1
There was a problem hiding this comment.
The image is part of the input, so it must be copies to GPU before being consumed, so before patchify or after patchify, we don't introduce extra copy/H2D sync
The work being small and not introducing extra sync is important, but more important could be the timing -- we don't want to move around a sync so that it slows down GPU work.
aa5dcb4 to
d50798a
Compare
| _SIDE_ABOVE_EVERY_RESIZE_BUDGET = 1 << 20 | ||
|
|
||
|
|
||
| class VisionProcessorBase(Configurable): |
There was a problem hiding this comment.
Extract shared config for SFT image processor and RL image processor
| def to_dict(self) -> dict[str, Any]: | ||
| return {"renderers_config": self.renderers_config.model_dump(mode="json")} | ||
|
|
||
| def with_vision_processor( |
There was a problem hiding this comment.
What does this function do?
There was a problem hiding this comment.
This seems replace the render_config's vision_processor to be real vision_processor
7566e9c to
961f83f
Compare
| 0. read the header rollout worker CPU (renderer) grid (1, 16, 16): 64 placeholder | ||
| `read_image_info`, tokens in the prompt, which carries | ||
| `num_placeholder_tokens` the 6,102-byte file, not pixels | ||
| 1. decode generator TP ranks and uint8 (3, 247, 252), the file's |
There was a problem hiding this comment.
In image processing, the process or read JPEG image and turn it into a pixel tensor is usually called decode .
|
@claude review again, especially about the image processor design @tianyu-l @felipemello1 I changed the image preprocessing design, put all the image processing step into The difference between SFT image processor and RL image processor:
|
|
Claude finished @wwwjn's task in 3m 54s —— View job Approve -- please address the items before merging: the processor design holds up, but SFT's patch settings are still repeated on |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The new processor design holds up: one RLVisionProcessor.Config drives the renderer, the generator and the trainer, and its settings now come from the same base as SFT's. The one gap is that SFT's half of the settings still lives in two configs, so the description overstates the sharing. This PR touches core data code, so a maintainer still needs to review.
What this PR does. It replaces ImageSpec with VisionProcessorBase.Config, which holds the resize, patch and normalize settings. SFT's VisionProcessor inherits those settings instead of declaring them itself. RLVisionProcessor adds patch_order and splits the work by process. get_mrope_positions is now the collator's only M-RoPE implementation (collator +37/-127).
Example.
vp = qwen35_vision_processor().build() # one config for renderer, generator, trainer
info = vp.read_image_info("00000_0.png") # renderer: key + grid (1, 16, 16), header only
vp.num_placeholder_tokens(info.grid_thw) # 64 image-pad tokens
imgs = vp.to_resized_images([file_bytes]) # generator/trainer CPU: uint8 (3, 256, 256)
vp.to_pixel_values([i.cuda() for i in imgs]) # GPU: float32 (256, 1536)
# == vision_to_patches(process_image(path, ...)) # SFT path, same settings, bitwise
On the design question. Splitting by consumer is the right call. SFT preprocesses a row inside one dataloader process. RL ships file bytes, and three processes each run one step, so they need one object with step-shaped methods. A shared settings base is the right amount of sharing: the RL methods have no SFT caller, so putting them on the base would only add unused methods to SFT's processor.
Must fix
vision_processor.py:125-- The settings are only half shared. SFT's patchify settings (patch_size,temporal_patch_size,spatial_merge_size,patch_order) are still repeated onMultiModalCollator.Config(mm_collator.py:40-44). Fix the description and add a TODO at the collator; the unification can be a follow-up (details inline).
Should consider
test_qwen3_5_renderer.py:37,62--importorskip("transformers")guards a package that requirements-dev already installs (inline).- Still open from the last review: the low-value tests
test_docstring_example,test_text_only_positions_repeat_the_token_indexandtest_rejects_image_cache_max. Also,load_resized_imageandnormalize_image(utils/image.py:202,251) repeatprocess_image's defaults, and both callers pass every argument.
Questions
renderer.py:83--with_vision_processorputs a dataclass holding a function (resize_fn) and an enum into the pydanticmodel_extra. The rollouter sendsget_renderers_config()to Verifiers workers (rl/examples/verifiers/rollouter.py:210). If that path serializes to JSON, does it survive? The in-process test (create_renderer(tokenizer, config.get_renderers_config())) doesn't cover serialization.
Details
Earlier findings, checked at HEAD:
- Renderer test always skipped in CI: resolved. It falls back to downloading
Qwen/Qwen3.5-0.8Bfrom the Hub, and thetests/utils.pyhelper is gone (which also covers @felipemello1's comment). - Second M-RoPE implementation: resolved by the merge. Equivalence: a vision run gets offset
next_position, and text resumes at+ max(t, h//m, w//m). The old code usedprev.max() + 1ongrid + text_len + offset, which is the same value. The image and video grids are still consumed in token order across documents. The newValueErrorfor an overlapping run is stricter than before, not a numerics change. ImageSpecduplication and themerge_sizerename: resolved.read_image_filewas removed andlargest_image_gridmoved onto the processor: resolved. Duplicate GPU test: resolved (one test left).- @tianyu-l's comments: the public names no longer say "decode", and the GPU step is documented in the
RLVisionProcessordocstring table and in the description. Both resolved. largest_patch_grid: checked the search bounds. With an area cap, no image reaches(side+1)^2tokens, so trying counts in(side^2, (side+1)^2)from the top and keeping the first grid the resize leaves unchanged is exact forresize_to_pixel_budget. Aspect ratios the resize rejects are caught.VisionProcessor.Config(VisionProcessorBase.Config, SampleProcessor.Config)withslots=True: no layout conflict, becauseSampleProcessor.Confighas no fields.read_image_infouses the PIL header size, andtorchvision.io.decode_imageapplies no EXIF rotation by default, so the two grids agree.
Not verified: the GPU bitwise test, and the Verifiers serialization path above (I couldn't run Python here).
| @dataclass(kw_only=True, slots=True) | ||
| class Config(VisionProcessorBase.Config): | ||
| patch_order: Literal["block", "raster"] = "block" | ||
| """Order of the patches in the pixel values (see `vision_to_patches`): | ||
| ``"block"`` keeps each ``spatial_merge_size x spatial_merge_size`` group of patches | ||
| adjacent (Qwen); ``"raster"`` is row-major (MoonViT, Kimi).""" |
There was a problem hiding this comment.
The settings are only half shared. VisionProcessorBase.Config covers what SFT's dataset-side VisionProcessor reads (resize, normalize, plus patch_size / temporal_patch_size / spatial_merge_size for the token count). SFT's patchify step still has its own copy of patch_size, temporal_patch_size, spatial_merge_size and patch_order on MultiModalCollator.Config (mm_collator.py:40-44). patch_order exists only here and on the collator. So an SFT recipe still states one model's preprocessing in two configs that can disagree: kimi_k2_7, kimi_k3, muse_glimmer and muse_spark set patch_order="raster" on the collator and the patch sizes on the processor. RL has it in one place. The description's "SFT and RL describe a model's preprocessing the same way" is therefore not true at HEAD.
Moving patch_order into the base on its own would leave it as an unused field on SFT's VisionProcessor.Config. The smallest honest fix for this PR is to correct the description and add a TODO at MultiModalCollator.Config saying its patch fields duplicate the processor's. The follow-up is to have the collator take them from the same config the dataset processor uses, so that VisionProcessorBase.Config is the model's complete preprocessing, including patch_order.
|
|
||
| @pytest.fixture(scope="module") | ||
| def tokenizer(): | ||
| transformers = pytest.importorskip("transformers") |
There was a problem hiding this comment.
transformers is in .ci/docker/requirements-dev.txt, so importorskip here and at line 62 can only turn a broken install into a silent skip (.claude/rules/tests.md: don't guard tests on packages already in requirements-dev). Import it at the top of the file and drop both guards.
| def to_dict(self) -> dict[str, Any]: | ||
| return {"renderers_config": self.renderers_config.model_dump(mode="json")} | ||
|
|
||
| def with_image_processor( |
There was a problem hiding this comment.
the method looks weird, as it replace itself with something else
I think we could do:
- modify
from_renderers()to takeimage_processoras an optional arg, and directly construct aRenderersConfigAdapterwith it.
There was a problem hiding this comment.
Patchify being fast on GPU doesn't justify putting it on GPU
- GPU has other important model work to do. Does patchify contend with them?
- what if we do prefetching of multimodal data, does it make things worse? where is the H2D sync?
- before your refactor, is pretraining patchify happening on CPU or GPU? My impression was it happens on CPU, but I could be wrong
- I didn't see the flow of moving things from CPU to GPU. Could you point me to that?
| data = f.read() | ||
| # The header gives the stored size; decoding applies no EXIF rotation either. | ||
| width, height = Image.open(io.BytesIO(data)).size | ||
| processor = self._image_processor |
c12749a to
f9837ae
Compare
| from torchtitan.config import Configurable | ||
|
|
||
|
|
||
| def hash_image_file(data: bytes) -> str: |
There was a problem hiding this comment.
not sure if renderer.py is the best place for it, but can revisit later.
|
@claude review again |
|
Claude finished @tianyu-l's task in 2m 52s —— View job Approve -- please address the item before merging: if a row has more placeholder runs than grids, the collator's |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. Every finding from the last review is resolved at HEAD. The collator rewrite gives the same M-RoPE positions as before, and the image processor is now a build argument like the tokenizer. That answers @tianyu-l's objection to with_image_processor. One new hazard: a malformed row could now end training silently instead of raising. This PR touches core data code, so a maintainer still needs to review.
What changed since the last review. The PR is rebased on #5873's per-model ImageProcessor, so ImageSpec, RLVisionProcessor and the GPU patchify test are gone. On top of that:
ImageProcessor.grid_thw(h, w)gives the patch grid from an image's size alone.RendererConfig.build(tokenizer=..., image_processor=...)replaceswith_image_processor.get_mrope_positionsnow takes token grids (already merged), and the collator merges each grid with its own modality'sspatial_merge_size.
Example.
proc = ImageProcessor.Config(**QWEN3_5_IMAGE_PROCESSOR_KWARGS).build()
r = from_renderers(CustomRendererConfig(import_path="...Qwen35ImageRefRenderer")).build(
tokenizer=tok, image_processor=proc)
r.render(msgs) # same token_ids as library Qwen35Renderer; pixel_values=None; mm_hashes=[sha256[:32]]
proc.grid_thw(480, 640) == (1, 30, 40); proc.num_placeholder_tokens((1, 30, 40)) == 300
Must fix
mm_collator.py:247-264--next(...)on exhausted grid iterators raisesStopIteration. Inside grain'sbatch_fnthat may silently end the data instead of failing (inline).
Should consider
- Still open from earlier reviews:
test_docstring_exampleandtest_text_only_positions_repeat_the_token_index(test_mrope_positions.py) add nothing overtest_matches_collator_for_one_documentandtest_collator_restarts_positions_per_packed_document.test_rejects_image_cache_maxonly re-checks a config validator.
Details
Earlier findings, checked at HEAD:
- SFT patch fields duplicated on
MultiModalCollator.Config: resolved in #5873.patch_orderand the patch sizes live only onImageProcessor.Config, and the collator reads them fromcontext.image_processor. importorskip("transformers"): removed;transformersis imported at the top of the test.- Verifiers serialization question: no longer applies. The renderer config carries no image processor, and #5824 makes the Verifiers rollouter raise
NotImplementedErrorwhenimage_processor_configis set. - @tianyu-l's comments:
with_image_processoris gone. The image processor goes tobuild, not tofrom_renderersas suggested; this matches how the tokenizer is passed. Patchify now runs on the CPU, the same as SFT, and the GPU test is gone.hash_image_fileplacement inrenderer.pyis deferred, as @tianyu-l agreed. The question about the relationship tomm_collator.pywas answered: the collator now callsget_mrope_positions. - @felipemello1's
tests/utils.pycomment: the helper is gone. The test downloadsQwen/Qwen3.5-0.8Bfrom the Hub, as the muse_glimmer renderer test does.
Checks on the new code:
- Collator equivalence. The new code advances text by its length, starts a vision run at
next_position, and then addsmax(t, h/m, w/m). The old code usedprev.max() + 1ongrid + text_len + offset, which gives the same value. Grids are still consumed in token order across documents, and each run takes its own processor's merge size. Documents cover[0, num_tokens), sotorch.emptyis fully written. grid_thwagrees withresize_and_normalize. Both call_resize_rule, andT = ceil(1 / temporal_patch_size) = 1for an image. The PIL header size andtorchvision.io.decode_image(no EXIF rotation) agree on the stored size.build(image_processor=...)rejects library renderers and an image processor that is also set on the config.MuseSparkRendererConfig.buildraises. Both are explicit, per principle 8.
Not verified: whether model_copy(update={"image_processor": ...}) on a CustomRendererConfig is re-validated by the custom renderer's config_class, as the comment at renderer.py:808 claims (I couldn't inspect the installed renderers library); and grain's batch_fn call path.
| image_grids = iter(grid_thw.tolist() if grid_thw is not None else []) | ||
| video_grids = iter( | ||
| grid_thw_videos.tolist() if grid_thw_videos is not None else [] | ||
| ) | ||
| batch_vision_starts = vision_mask & ~prev_vision # (batch, seq_len) | ||
| grid_cache: dict[tuple[int, int, int], torch.Tensor] = {} | ||
|
|
||
| image_index, video_index = 0, 0 | ||
| # With sample packing, each sample may contain multiple documents. | ||
| for sample_i in range(batch_size): | ||
| llm_pos_ids_list: list[torch.Tensor] = [] | ||
|
|
||
| if positions is not None: | ||
| # pyrefly: ignore [unbound-name] | ||
| reset_indices = torch.where(resets[sample_i])[0] + 1 | ||
| doc_starts = [0] + reset_indices.tolist() | ||
| doc_ranges = [ | ||
| ( | ||
| doc_starts[d], | ||
| doc_starts[d + 1] if d + 1 < len(doc_starts) else seq_len, | ||
| ) | ||
| for d in range(len(doc_starts)) | ||
| ] | ||
| else: | ||
| doc_ranges = [(0, seq_len)] | ||
|
|
||
| sample_tokens = tokens[sample_i] | ||
| sample_vision_starts = torch.where(batch_vision_starts[sample_i])[ | ||
| 0 | ||
| ].tolist() | ||
| vision_start_index = 0 | ||
|
|
||
| for doc_start, doc_end in doc_ranges: | ||
| doc_pos_ids_list: list[torch.Tensor] = [] | ||
|
|
||
| doc_vision_starts: list[int] = [] | ||
| while ( | ||
| vision_start_index < len(sample_vision_starts) | ||
| and sample_vision_starts[vision_start_index] < doc_end | ||
| ): | ||
| doc_vision_starts.append(sample_vision_starts[vision_start_index]) | ||
| vision_start_index += 1 | ||
|
|
||
| pair_cursor = doc_start | ||
| for vision_start in doc_vision_starts: | ||
| if sample_tokens[vision_start] == image_token_id: | ||
| # pyrefly: ignore [unsupported-operation] | ||
| t, h, w = grid_thw[image_index] | ||
| image_index += 1 | ||
| processor = self.image_processor | ||
| else: | ||
| # pyrefly: ignore [unsupported-operation] | ||
| t, h, w = grid_thw_videos[video_index] | ||
| video_index += 1 | ||
| processor = self.video_processor | ||
| assert processor is not None | ||
| spatial_merge_size = processor.config.spatial_merge_size | ||
|
|
||
| llm_grid_t, llm_grid_h, llm_grid_w = ( | ||
| int(t.item()), | ||
| int(h.item()) // spatial_merge_size, | ||
| int(w.item()) // spatial_merge_size, | ||
| ) | ||
| text_len = vision_start - pair_cursor | ||
|
|
||
| pos_id_offset = ( | ||
| doc_pos_ids_list[-1].max() + 1 | ||
| if len(doc_pos_ids_list) > 0 | ||
| else 0 | ||
| ) | ||
| # [text tokens] — sequential positions, identical on all 3 axes. | ||
| doc_pos_ids_list.append( | ||
| torch.arange(text_len).view(1, -1).expand(3, -1) + pos_id_offset | ||
| ) | ||
| # [vision tokens] — 3D grid positions (T, H, W). | ||
| grid_key = (llm_grid_t, llm_grid_h, llm_grid_w) | ||
| if grid_key not in grid_cache: | ||
| hw = llm_grid_h * llm_grid_w | ||
| t_index = ( | ||
| torch.arange(llm_grid_t) | ||
| .view(-1, 1) | ||
| .expand(-1, hw) | ||
| .flatten() | ||
| ) | ||
| h_index = ( | ||
| torch.arange(llm_grid_h) | ||
| .view(1, -1, 1) | ||
| .expand(llm_grid_t, -1, llm_grid_w) | ||
| .flatten() | ||
| ) | ||
| w_index = ( | ||
| torch.arange(llm_grid_w) | ||
| .view(1, 1, -1) | ||
| .expand(llm_grid_t, llm_grid_h, -1) | ||
| .flatten() | ||
| ) | ||
| grid_cache[grid_key] = torch.stack([t_index, h_index, w_index]) | ||
| doc_pos_ids_list.append( | ||
| grid_cache[grid_key] + text_len + pos_id_offset | ||
| ) | ||
| pair_cursor = vision_start + llm_grid_t * llm_grid_h * llm_grid_w | ||
|
|
||
| # Trailing [text tokens] after the last text/vision pair. | ||
| if pair_cursor < doc_end: | ||
| pos_id_offset = ( | ||
| doc_pos_ids_list[-1].max() + 1 | ||
| if len(doc_pos_ids_list) > 0 | ||
| else 0 | ||
| ) | ||
| text_len = doc_end - pair_cursor | ||
| doc_pos_ids_list.append( | ||
| torch.arange(text_len).view(1, -1).expand(3, -1) + pos_id_offset | ||
| ) | ||
|
|
||
| llm_pos_ids_list.extend(doc_pos_ids_list) | ||
|
|
||
| # llm_pos_ids_list is (3, segment_len); concat -> (3, seq), then transpose | ||
| mrope_positions[sample_i] = torch.cat(llm_pos_ids_list, dim=1).T | ||
|
|
||
| return mrope_positions.squeeze(0) | ||
| mrope_positions = torch.empty( | ||
| num_tokens, 3, dtype=tokens.dtype, device=tokens.device | ||
| ) | ||
| for doc_start, doc_end in zip(doc_starts, doc_ends): | ||
| vision_items = [] | ||
| for start in vision_starts: | ||
| if not doc_start <= start < doc_end: | ||
| continue | ||
| if tokens[start] == image_token_id: | ||
| t, h, w = next(image_grids) | ||
| processor = self.image_processor | ||
| else: | ||
| t, h, w = next(video_grids) |
There was a problem hiding this comment.
If a row has more placeholder runs than grids, next(image_grids) / next(video_grids) raises StopIteration. One way this happens: the raw text contains an <|image_pad|> that tokenizes to the image id. The old code raised IndexError here.
The loader passes the collator to grain as batch_fn (loader.py:157). If grain calls it from an iterator's __next__, the StopIteration will look like the end of the data, and training stops early without an error. I didn't check grain's call path, so this is unverified.
Smallest fix: give next a default and raise on it, e.g.
grid = next(image_grids, None)
if grid is None:
raise ValueError("More image placeholder runs than image grids in the microbatch.")
t, h, w = gridDo the same for the video grids.
f9837ae to
40b28c6
Compare
40b28c6 to
c60e542
Compare
…#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`.
…ions RL image prompts need each image's placeholder count at render time, and the same pixels in the generator and the trainer. This adds the pieces on top of the per-model `VisionProcessor`: - `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`: the renderers library's Qwen3.5 renderer with `_process_image` replaced, so rendering emits placeholder runs and image hashes but no pixel_values. It reads each image file once, hashes it (`hash_image_file`, so a file gets the same hash from any path) and computes the grid from the header. - `RendererConfig.build(tokenizer=..., vision_processor=...)`: the vision processor is a build argument, like the tokenizer, so TitanRL passes the one built from `Controller.Config.vision_processor`. `RenderersConfigAdapter` sets it on an in-tree renderer's config (`CustomRendererConfig`), and rejects it for library renderers or when the renderer config sets one too. - `get_mrope_positions(num_tokens, vision_items)`: 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 the processor's `spatial_merge_size`. RL takes the offsets from the renderer. Test: - Unit tests: `grid_thw` equals the grid `resize_and_normalize` gives (Qwen-style and Kimi-style NaViT resize with padding), M-RoPE positions (direct and through the collator across packed documents), the renderer (token ids, placeholders and grids equal the library renderer's with the HF processor Qwen3.5 ships; pixel values equal the HF processor's; hashes independent of the path; needs a vision processor; built through `from_renderers(...) .build(vision_processor=...)`), and `build` rejecting a vision processor for a library renderer or one set twice. The renderer test downloads the Qwen3.5 tokenizer, so it runs in CPU CI. - 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 the renderer's token ids and placeholders equal the library renderer's (0 mismatches), at 1.2 ms vs 9.4 ms per prompt.
c60e542 to
b324c19
Compare
## 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
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
6. #5998 [rl] Muse Spark image prompts and a SLAKE LoRA GRPO recipe for
Muse Spark 816B
7. #6016 [rl][docs] README: bring the RL model support table up to date
## Why
RL prompts are token ids only: the rollout worker, the router, the
generator and vLLM pass a bare `prompt_token_ids`, so an image prompt
from #5823's renderer has nowhere to carry its images, and the generator
has no way to run the TorchTitan vision encoder. This PR carries image
prompts from the renderer to vLLM (Qwen3.5); text runs are unchanged
apart from the `Prompt` wrapper.
**Example.** Before: `generate(prompt_token_ids=[...])`. After, an image
travels as file bytes plus where its placeholder run sits:
```
rollout worker generator (every TP rank) vLLM
-------------- ------------------------- ----
render() -> Prompt VisionProcessor (CPU): embed_multimodal: vision encoder,
token_ids (placeholder runs) -----> resize_and_normalize + patchify -----> once per mm hash while cached
images: PromptImage(hash_value, LRU cache of pixel values by hash embed_input_ids: image embeddings
grid_thw, data=file bytes) image_prompt_to_engine_input -> mm_input over the placeholders
image_placeholders forward(3D M-RoPE positions)
```
## What changed
**One generation input.** `Prompt(token_ids, images=(),
image_placeholders=())` replaces the bare `prompt_token_ids` everywhere
a prompt travels: `TokenEnvOutput.next_prompt`, `GenerateFn`, the
router, `Generator.generate` and `EngineRequest`. An image is a run of
placeholder tokens in `token_ids`; `Prompt.image_placeholders` says
where each run is, and its `PromptImage(hash_value, source_path,
grid_thw, data)` carries the image file's bytes (Geometry3K median 15
KB), so no process past the rollout worker needs the dataset's file
system. This is the shape vLLM (`mm_input`), SGLang and HF processors
take at the engine boundary, so no layer converts it.
**Rollouts store deltas.** A `RolloutTurn` stores only the images after
its shared prefix (`prompt_delta_images`,
`prompt_delta_image_placeholders`), like its tokens. `split_prompt` ends
the shared prefix at the first image that differs from the previous
turn's (another file with the same placeholder count, or a moved image),
so every changed image is in the delta. TokenEnv always calls
`render()`, passes the previous prompt's `multi_modal_data` to the
bridge when it has images, and reads the image files in a worker thread.
**One image preprocessing config.** `Controller.Config.vision_processor`
(the model's `VisionProcessor.Config` from #5873, next to `tokenizer`;
None = text only) is the only place image preprocessing is configured.
The controller and the rollout workers pass it to
`renderer.build(tokenizer=..., vision_processor=...)` (#5823), and the
generator takes it as a build argument. The controller requires a
generator model that is a `MultimodalModel` with a vision encoder. It
stays a config and not a property of the model type: every real Qwen3.5
flavor ships the vision encoder, and text RL recipes use them without
serving images.
**Generator.** With a vision processor, `VLLMEngine` turns each image
file into pixel values on the CPU, as the SFT dataloader does, keeps
them in an LRU cache by image hash (vLLM's `LRUCache`, 1 GiB:
preprocessing takes 6.5 ms per Geometry3K image on the engine loop
thread, and every sample of a group carries the same images), and
submits vLLM's `mm_input` directly, so vLLM's Hugging Face processor
never runs. vLLM still requires a registered multimodal processor for
the model class; it only sizes the encoder budget and profiles memory
with the vision processor's largest image (`_largest_patch_grid`, which
is not always square). A request whose image file does not decode is
rejected at admission like any request vLLM rejects: its rollout fails
and the engine keeps serving.
**Model wrapper.** `VLLMMultimodalModelWrapper` runs the model's
`get_vision_embeds` (made public) on the packed pixel values, writes the
image embeddings over the placeholder tokens, and computes M-RoPE
positions with `get_mrope_positions`, as the trainer does.
`model_config_to_hf_config_dict(serves_images=True)` declares M-RoPE to
vLLM and rejects a model whose attention is not `MRoPE.Config`. The
generator forward now returns plain tensors (spmd_types), so the DTensor
unwrap after it is gone. The generator's shared model build
(`build_inference_model`, #5811) drops the vision encoder unless the
wrapper serves images (`keep_vision_encoder`).
**Stale embeddings.** vLLM keeps an image's encoder output after its
requests finish (only `reset_encoder_cache` clears it), and the vision
weights train. Image mm hashes are therefore salted like the prefix
cache with the request's pinned policy version (`hash@version`). With
`reset_kv_cache_on_model_state_dict_load`, hashes are bare and the
engine resets the encoder cache on every load.
Until the trainer takes image inputs (next PR), the controller rejects
`vision_processor`, so image prompts never train on their placeholder
tokens alone. Verifiers environments reject it too (their env server
builds its own renderer).
### Why the deltas are safe
The generator always gets the full prompt; only stored turns are deltas,
and the trainer rebuilds exactly the input the generator saw:
1. Image offsets are full-prompt positions from the renderer
(`render()`; the Qwen3.5 bridge seeds its tokens with the previous
prompt, so its offsets are absolute too). TokenEnv copies them into the
delta unchanged: no offset arithmetic anywhere.
2. `split_prompt` keeps an image in the shared prefix only if it equals
the previous turn's image at the same index (hash, offset and length);
otherwise the prefix ends at its first placeholder. An identical image
has the same pad tokens at the same place, so the prefix never ends
inside an image.
3. So the previous turn's images inside the prefix are exactly this
turn's prefix images, and (previous images with offset < prefix) + delta
= the turn's full images, by induction from turn 0 (prefix 0). #5825's
`TrainingSampleBuilder` rebuilds them this way.
4. A training sample starts at a full prompt's first token, so
full-prompt offsets are sample offsets, and M-RoPE positions come from
the same `get_mrope_positions` over identical content on both sides.
5. A turn extends a training sample only when its prefix covers the
previous prompt + completion. A changed image shortens the prefix, so a
completion is never trained with an image it was not generated from.
Two things could break this, and each is caught: a rollout producer that
builds turns without TokenEnv (#5825's builder rejects a delta image
outside its delta), and a renderer bridge with tail-relative offsets
(generator and trainer would be wrong together; each image renderer
needs a multi-turn test like #5825's real-renderer
`test_multiturn_images.py` for Qwen3.5).
## Numerics / performance
- Text path: RL loss guard (`rl_grpo_qwen3_0_6b_varlen_batch_invariant`,
seed 42, deterministic, trainer TP4 + one generator TP4, on-policy, 10
steps) gives `loss/mean`, `trainer/grad_norm/mean` and the
generator-vs-trainer logprob diff (max 0) bitwise equal to the PR below
at all 10 steps (TensorBoard values, `scripts/rl/loss_compare.py`; on
b9b3620, this PR before the rename to `VisionProcessor`, which changes
no computation). This covers the `Prompt` wrapper and the generator
forward without the DTensor unwrap.
- Image path, measured on an earlier revision of this PR (SLAKE medical
VQA, Qwen3.5-0.8B): generator-only accuracy with images 0.81 vs 0.51
text-only (TP1 and TP2 identical); generator vs TorchTitan forward
logprobs on image prompts mean abs diff 0.0166 vs 0.0150 for the text
control; 128 requests over 4 images ran the vision encoder 4 times. The
end-to-end image run comes with #5825.
## Testing
- `test_vllm_multimodal_wrapper.py`: the engine input places each image
on its placeholders, with the pixel values whose patch count matches the
renderer's grid; M-RoPE input positions; the largest patch grid (square,
non-square, NaViT); profiling inputs; the HF config declares M-RoPE only
when serving images; the controller rejects a vision processor for a
model without a vision encoder; image embeddings land on the placeholder
tokens vLLM's mask marks, in order (`masked_scatter_`, which never syncs
the host).
- `test_generator.py`: admission salts image hashes with the pinned
version (bare in reset mode), preprocesses each file once while cached,
rejects image requests without a vision processor, and rejects only the
request whose image file does not decode; the encoder cache resets with
the KV cache.
- `test_token_env.py`, `test_rollout_utils.py`: images across turns, the
bridge extends earlier images, delta images, `split_prompt` ends the
prefix at a changed or moved image, rejection of pixels and non-image
modalities, a changed file.
- `test_rollout_worker.py`, `test_rollout_recorder.py`: the rollout
sends and records delta images, without their bytes.
- `pytest tests/rl/unit_tests/cpu`: 575 passed, 8 skipped.
## 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
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
6. #5998 [rl] Muse Spark image prompts and a SLAKE LoRA GRPO recipe for
Muse Spark 816B
7. #6016 [rl][docs] README: bring the RL model support table up to date
## Why
After #5824, rollouts carry image prompts and the generator serves them,
but the trainer cannot train on them: training samples have the
placeholder tokens without the images, so the controller rejects
`Controller.Config.vision_processor`. Training on image prompts needs
each sample's full images rebuilt from the turns' deltas, the images
moved from the batcher to the trainer and encoded there, and, for GRPO,
not encoding one image once per sample: the samples of a group show the
same images.
**Example.** Before: setting `vision_processor` raises at controller
setup. After:
```
RolloutTurn deltas --TrainingSampleBuilder--> TrainingSample(token_ids, images, image_placeholders)
--Batcher--> microbatches: each distinct image file once, every placeholder token's embedding row
--trainer, TrainingMicrobatch.preprocess_images--> pixel_values -> vision encoder -> embedding rows
```
How the same image is encoded once: 2 groups x 2 samples on 2 DP ranks,
image k in group g0 and image m in group g1, each placeholder token
drawn as its image's letter (also in `Batcher._pack_image_inputs`'s
docstring):
```
samples a0: t k k k t t a1: t k k k t t t (group g0)
b0: t m m t t b1: t m m t t t (group g1)
1. Batcher._pack_with_lpt picks each sample's microbatch, preferring one that already holds
the sample's image:
rank 0: [a0 a1] rank 1: [b0 b1] k and m each encoded once
instead of rank 0: [a0 b0] rank 1: [a1 b1] k and m each encoded on both ranks
2. Batcher._pack_image_inputs builds rank 0's image inputs. The image embeddings (the model's
"vision bank") are the vision encoder's output for the microbatch's distinct images,
stacked in order, one row per image token; each token gets its row:
tokens t k k k t t | t k k k t t t | pad
rows -1 0 1 2 -1 -1 |-1 0 1 2 -1 -1 -1 | -1 image_vision_bank_indices_T
image_files [file k] each distinct image (by hash) once, ~15 KB
grid_thw [grid of k]
3. TrainingMicrobatch.preprocess_images, on the trainer: file k -> resize_and_normalize
-> patchify_all -> pixel_values (~2.4 MB of float32), once per distinct image.
4. The model encodes k once into embedding rows [e0 e1 e2], and each placeholder token
takes its row: tokens 1 and 7 both take e0 (gather_vision_embeds, already on main).
In the backward, both runs' gradients add up into the one encoding.
```
## What changed
- **Training samples carry their images** (`TrainingSample.images` and
`image_placeholders`, aligned like `Prompt`'s). Rollout turns store only
their new images (#5824), so `TrainingSampleBuilder` rebuilds each
turn's full images like its tokens: the previous prompt's images inside
the shared prefix, then the turn's own. A turn that swaps an image in
place branches like a token edit, because `split_prompt` ends the shared
prefix at the changed image. The builder rejects a delta image outside
its delta (placeholders are full-prompt positions); otherwise a producer
that stored delta-relative offsets would put image embeddings on other
tokens without an error. Why the rebuild is exact: #5824, "Why the
deltas are safe".
- **The batcher ships files, the trainer preprocesses.** Per microbatch,
the batcher ships each distinct image file once (`image_files` +
`image_file_sizes`), each placeholder token's row in the image
embeddings (`image_vision_bank_indices_T`), `grid_thw`, and, with
`Batcher.Config.build_mrope_positions`, 3D M-RoPE positions from
`get_mrope_positions`, as the generator computes them. The recipe sets
the flag, as SFT's `MultiModalCollator.Config.build_mrope_positions`
does (Geometry3K: True); `Controller.Config` raises unless it matches
the trainer model's RoPE (`get_mrope_config`), since a Qwen3.5 run
without it would train image tokens on 1D positions while the generator
used M-RoPE. Packing prefers a microbatch that already holds a sample's
image. On the trainer, `TrainingMicrobatch.preprocess_images` (named
after the generator's `_preprocess_images`) turns each file into pixel
values on the CPU before the engine sees the microbatch, so
`as_input_dict` holds model inputs as for any other microbatch; with
RDMA it runs on the read-ahead thread, hidden behind training.
Placeholder counts are checked against the grids, and the decoded images
against the prompts' grids.
- **One config.** The batcher gets `Controller.Config.vision_processor`
at build time, as the renderer and the generator do (#5824), so all
three use one config and nothing has to be kept equal. This replaces the
previous PR's guard.
- **Qwen3.5 under CP** keeps the embedding rows the batch provides
(`image_vision_bank_indices_T`) instead of counting placeholder tokens:
several placeholder runs can share one encoded image, and a placeholder
id sampled in a completion is text.
- **Recipe.** `rl/examples/geometry3k` (Hugging Face
`hiyouga/geometry3k`; the dataset writes the parquet's images to files
once, since rendering reads image files) and
`torchtitan_recipes/rl/geometry3k.py::rl_grpo_qwen3_5_0_8b_geometry3k`
(4 GPUs), with
`vision_processor=VisionProcessor.Config(**QWEN3_5_VISION_PROCESSOR_KWARGS)`
next to the tokenizer. Rewards reuse the DAPO math Math-Verify grader on
the last `\boxed{}`.
- Mechanical: `VisionProcessor.patchify_all` (patchify and pack items)
is extracted from the SFT collator, which now calls it; the trainer uses
it too.
- CI: the RL CPU job fetches the Qwen3.5 tokenizer next to the Muse
Glimmer one; the RL multi-GPU job runs `test_cp_images.py` (fetches
Qwen3.5-0.8B).
## Alternatives considered
- Ship pixel values instead of files: ~2.4 MB instead of ~15 KB per
Geometry3K image over RPC or RDMA.
- Find images by scanning token ids for placeholder runs, as the SFT
collator does: the policy can sample the placeholder id in a completion.
- No dedup: simpler, but the trainer then encodes every sample's copy of
an image; on SLAKE (Qwen3.5-0.8B) packing by image cut the images
encoded per step from 109-128 to 26-48 (of 128) and the median step time
from 16.9 s to 14.9 s. The share is smaller for larger language models
(the vision encoder stays the same size).
## Numerics / performance
On 8e8950a93 (this PR before the rename to `VisionProcessor`, which
changes no computation), `rl_grpo_qwen3_5_0_8b_geometry3k` on 4 A100
(trainer FSDP=2 + 2 generators at TP=1, 16 prompts x 8 samples per
step), 30 steps:
- validation reward on the 601 test problems 0.285 -> 0.358 (truncation
rate 0.56 -> 0.18);
- rollout reward, mean of steps 1-10 vs 21-30: 0.15 -> 0.28;
- mean trainer-generator logprob difference -0.0003 to -0.0018 per
token;
- the trainer encoded 35-98 images per step for the samples' 128
(packing by image);
- the trainer waited ~7 ms per step for its batch; 30 steps plus both
validations took 14.5 min.
Measured on earlier revisions of this stack (same preprocessing
placement and packing):
- SLAKE (medical VQA): Qwen3.5-0.8B on-policy GRPO, reward 0.008 -> 0.85
in 12 steps; Qwen3.5-35B-A3B on 8 GB300, reward 0.31 -> 0.94 in 30
steps.
- Geometry3K on 4 GB300, 30 steps: validation reward 0.270 -> 0.361 with
the default RPC batcher path and 0.271 -> 0.351 with
`Batcher.Config(rdma_min_tensor_bytes=1024)` +
`preprocess_microbatch_groups_lazily=True`; steady-state step ~10 s.
## Testing
- `test_rollout_utils.py`: training samples rebuild their full images
from the turns' deltas (extend, then a new branch); an image swapped in
place branches; a delta image outside its delta raises.
- `test_multiturn_images.py`: a two-turn image rollout through the real
`Qwen35ImageRefRenderer`, TokenEnv, the rollout worker and
`TrainingSampleBuilder` (with and without thinking): the turns store [a]
then [b], the samples carry [a, b] (or [a] and [a, b]), and every image
sits on its placeholder run.
- `test_batcher.py`: embedding rows, one file per distinct image, pixel
values equal to `patchify(resize_and_normalize(file))`, packing by
image, placeholder and grid checks, text samples with a vision
processor.
- `test_trainer.py` / `test_rdma_microbatch.py`: the trainer
preprocesses images before training, on the read-ahead thread with RDMA.
- `test_qwen3_5_vision_bank.py`: the batch's rows place one encoding on
two placeholder runs, and both runs' gradients add up into it (equal to
encoding the image twice; fails if a run's gradient is dropped).
- `test_cp_images.py` (GPU, RL multi-GPU CI): Qwen3.5-0.8B through
`Trainer.forward_backward` without CP (FSDP=2) and with CP=2
(AllGatherKV with head-tail balancing, and Ulysses), on microbatches
with an image split by the CP boundary, one image shared by samples on
both ranks, an image longer than a head-tail chunk, sampled placeholder
ids and a text sample. The decoder's input embeddings and M-RoPE
positions must equal the no-CP ones bit for bit, and the vision
encoder's gradient must match (norm ratio 0.85-1.15, cosine > 0.98).
Catches a CP shard that puts image rows or positions on the wrong
tokens, or a vision gradient not summed over the CP ranks (half the norm
at CP=2).
- `test_geometry3k.py`: dataset, env, grading, and the recipe's vision
processor matches the generator's and the trainer's vision encoder.
- Broader CP check run locally on the same trainer path (bf16,
deterministic; seven microbatches, adding an image longer than a CP=4
shard and DP ranks where one trains images and the other text): CP=2
(AllGatherKV contiguous and head-tail, Ulysses), CP=4 (contiguous and
head-tail), CP=2 x FSDP=2, and mixed DP ranks. Input embeddings and
positions are bitwise equal to no CP everywhere; the vision gradient's
norm ratio is 0.91-1.08 and its cosine >= 0.987. With one image's rows
reversed (a negative control), the embeddings differ by 1.6-2.8 and the
cosine drops to 0.08-0.96.
- `pytest tests/rl/unit_tests/cpu tests/unit_tests/cpu/components
tests/unit_tests/cpu/models/qwen3_5/test_qwen3_5_vision_bank.py`: 1129
passed, 9 skipped; 1 failed
(`test_lora_head_only_matches_cross_entropy`, a local Inductor C++ build
error that main has too). `pytest
tests/rl/unit_tests/gpu/test_cp_images.py` on 2 A100: 4 passed (2m43s);
with this PR's Qwen3.5 CP change reverted, its launches fail
(`pixel_values require special_tokens with an 'image_id' entry`).
## Known issues / follow-ups
- Rank balancing counts attention work, not vision-encoder work, which
packing by image concentrates (TODO in `Batcher._attention_workload`).
- Images are deduplicated within a microbatch only; a group split across
microbatches encodes its image once per microbatch.
… 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.)
…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.
…er override; agent self-review; rl/transport (#6407) ## 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 Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it approved, 30 then got a formal "request changes" from a maintainer, and about 20 more got substantive inline asks. In nearly all of them the bot either saw the problem and approved anyway, or never asked the questions maintainers ask most ("does the repo already do this?", "who should own this?"). The opposite failure, the bot blocking something a maintainer was fine with, is rare: in the PRs we sampled, 2 of its 81 must-fix items were wrong and about a third were minor (the empty human-written summary was the biggest source). **Example** (#6112, controller sizes the rollout worker pool): ``` before: bot approved 10 times; tianyu-l then blocked: "the controller reads rollouter.rollouts_per_worker to compute a count it hands back to the Rollouter -- violates encapsulation" after: same commit, new skill -> Request changes, must-fix #1: "controller.py:589 -- wrong owner for the worker count ..." ``` There was also no way for a code owner to overrule the bot except dismissing its review in the GitHub UI, and a later `@claude review again` would block again. ## What changed **Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`): - Verdict rules: Approve only when every remaining item is an edit the bot could write itself. Anything the author still owes (a design change, an unexplained golden change, evidence the PR rests on) is Request changes; anything only a maintainer can decide is Needs discussion. A hedge like "a maintainer should decide" can't come with Approve. - Always must-fix: a violated written rule, a silent wrong result, a second definition of an existing concept, a gate finding. - Design gate: new questions for the existing counterpart, in-repo ownership, and the design behind a bug; "ban only what doesn't work on main"; read the numbers behind a claim. The overlapping-PR search is mandatory and reported. - Re-review covers every commit since the last full review, including code taken from the bot's own suggestions. A scoped question gets a `COMMENT`, not a whole-PR verdict. - The bot fact-checks its own proposed fixes, and cites a source for claims about external tools or marks them unverified (never must-fix). - An empty "Summary (human-written)" is a one-line "Before merge" note that never affects the verdict. - Checklist: config ownership direction, general shared wrappers, dead code the PR creates, model variants as flavors, a mechanical pass over every new or changed function. **Code owner override** (`SKILL.md`, `claude-code.yml`, `CONTRIBUTING.md`): a code owner comments `@claude override` (optionally `@claude override 2,3: <reason>`); the bot approves if nothing else is open and doesn't re-raise the overridden items. A code owner's GitHub approval or "LGTM" is not an override, so a teammate can approve without the bot dropping its findings. Dismissing the bot's review still unblocks the PR, but isn't an override: the bot can't tell who dismissed it. **Agent self-review** (`CLAUDE.md`, `pr-description`): an agent preparing a PR runs `pr-review` in branch mode first and records unaddressed items in an optional "Self-review" section. PRs written without an agent are unaffected; a missing section is never a finding. Where each new rule comes from (maintainer asks the bot missed): | Change | PRs | | --- | --- | | No Approve with open design/evidence items or a "maintainer should decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 | | Author waiver can't clear a must-fix | #6201, #6202, #6203 | | Existing counterpart; one source of truth | #5228, #6169, #5881, #5823, #5824, #6059, #5812 | | Responsibility owner; config ownership direction | #6112, #6332, #5802, #5803, #6325 | | Fix the design behind the bug; a TODO doesn't justify a workaround | #5572, #5689, #5657 | | Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819, #5543 | | Re-review covers all new commits; scoped asks don't approve | #5824, #5842 | | Mandatory overlap search | #5885, #6248 | | Ban only what doesn't work on main | #5543 | | Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868 | **Rules**: `design.md` gets the one-general-wrapper rule (moved from `models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the consumer owning its values; `config.md` gets ownership direction and "a Config doesn't read runtime state"; `direction.md` calls all-to-all the MoE reference implementation, so a new vendor-specific dispatch path (e.g. #6242) needs a reason the existing backends can't serve. **Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/` -> d4l3k. **Mechanical, skim**: `torchtitan/rl/transport/` holds data movement between RL actors. - `rl/model_state_dict_transport.py` -> `rl/transport/model_state_dict.py` - `rl/MODEL_STATE_DICT_TRANSPORT.md` -> `rl/transport/MODEL_STATE_DICT_TRANSPORT.md` - `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py` - tests: `tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py` -> `tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py` - imports, READMEs and `scripts/install_rl_env.sh` updated; no code changes. ## User-facing changes | Before | After | | --- | --- | | Overrule the bot: dismiss its review in the UI, and it blocks again on the next run | `@claude override [items]: <reason>`; the bot approves and doesn't re-raise them | | Empty human-written summary: bot must-fix | One "Before merge" line, no effect on the verdict | | `from torchtitan.rl.model_state_dict_transport import ...` | `from torchtitan.rl.transport.model_state_dict import ...` | | `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from torchtitan.rl.transport.rdma_microbatch import ...` | ## Testing Backtest: the new skill run locally (nothing posted) on each PR at the commit and thread state the bot originally saw. | PR | Bot then | New skill | What the maintainer asked | | --- | --- | --- | --- | | #6112 | Approve | Request changes | worker-count ownership (caught) | | #5837 | Approve | Request changes | apply to `dp_shard` too (caught) | | #5572 | Approve | Request changes | delete the injection design (caught) | | #6201 | Approve after author waived pins | Request changes, waiver ignored | pins broke GPU tests after merge (caught) | | #6007 | Approve | Request changes | fold K3.1 into K3 (caught) | | #5543 | Request changes: "ban it" | Request changes: keep main's path | don't break gpt-oss + DeepEP (fixed) | | #6144, #5905 (controls) | Approve | Approve | -- | | #6137 (control) | Approve | Needs discussion | -- (merge gate on an upstream API) | Code owner override, simulated on #6201: override by a code owner lifts the named item; `@claude override` from the author changes nothing; a code owner's "LGTM" approval followed by "review again" keeps Request changes. Transport move: 83 RL CPU unit tests pass locally (`transport/test_model_state_dict.py`, `test_trainer.py`, `test_engine_loop.py`). `transport/test_rdma_microbatch.py`, `test_generator.py` and `test_batcher_actor.py` fail to collect in my env on `origin/main` too (stale attention-gym / Monarch), so CI is the check for those. ## Known issues / follow-ups - Open PRs that edit the moved files rebase cleanly (git follows the renames), but new imports of the old module paths will break: #6309 (adds a delta transport that should live in `rl/transport/`), #6237, #6176, #6177, #5862, and drafts #6127, #6393, #6163, #5764. - The Actions bot can't read dependency source (e.g. SGLang); follow-up for the workflow. ## Self-review pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch mode diffs against `origin/main` and skips description findings before a description exists; the "Config doesn't read runtime state" rule no longer contradicts hardware validation; dismissal dropped as an override form (the bot can't tell who dismissed); `test_rdma_microbatch.py` added to the transport area. Not addressed: - One concern per PR -- the five changes ship together at the maintainer's request. - Open PRs touching the moved files -- listed above; the maintainer will coordinate.

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
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 float32pixel_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 gridresize_and_normalizegives aheight x widthimage, without decoding it. A renderer that reads the size from the file header gets the grid andnum_placeholder_tokens(grid)from it.Qwen35ImageRefRenderer(models/qwen3_5/renderer.py): the library'sQwen35Rendererwith only_process_imagereplaced, so rendering emits the same placeholder runs and a hash per image, but nopixel_values:RendererConfig.build(tokenizer=..., vision_processor=...): the vision processor is a build argument, like the tokenizer, so TitanRL ([rl] Image prompts through rollouts and the vLLM generator #5824) passes the one it builds fromController.Config.vision_processorto the renderer, the generator and the trainer.RenderersConfigAdapter.buildsets it on an in-tree renderer's config (CustomRendererConfig), and raises for a library renderer or when the renderer config already sets one;MuseSparkRendererConfig.buildtakes 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_positionsfinds 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
mrope_positionsincluded, 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).Qwen35ImageRefRenderergives 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'sresized_size;grid_thwcomputes the same grid from the same resize rule.Test
tests/unit_tests/cpu/components/data/test_mm_dataset_preprocessing.py:grid_thwequals the gridresize_and_normalizegives (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 bareStopIterationthere 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, andpatchify(resize_and_normalize(...))equals its pixel values; hashes independent of the path; needs a vision processor; built throughfrom_renderers(...).build(vision_processor=...). Downloads theQwen/Qwen3.5-0.8Btokenizer, so it runs in CPU CI;QWEN3_5_TOKENIZERpoints it at a local copy.tests/unit_tests/cpu/components/test_renderer.py:buildrejects a vision processor for a library renderer, and one set twice.