Repository navigation
[data] Multimodal chat SFT: image in the user turn, loss on the answer only - #5885
Conversation
…r only
## Summary (human-written)
Enable multimodal chat SFT -- image only.
## Why
On main there is no way to train VQA-style chat SFT with images. ChatProcessor is text-only and raises on any media. The multimodal processors take interleaved text and images with loss on all text, not chat turns with loss on the answer only.
**Example.**
```
messages = [
{"role": "user", "content": [{"type": "image", "image": "imgs/1.jpg"}, {"type": "text", "text": "Which organ?"}]},
{"role": "assistant", "content": "Liver"},
]
rendered: ... <|patch|> Which organ? ... Liver <eos>
expanded: ... <|image_start|> <|patch|> x N <|image_end|> Which organ? ... Liver <eos> # N = encoder output rows
labels: IGNORE on the system and user turns and all image tokens; loss on "Liver <eos>" only
```
## What changed
- Add MultiModalChatProcessor, a Grain sample processor for chat rows with images. Its Config owns messages_fn and the renderer config; the renderer is built in __init__. It renders the messages, processes each image part with the trainer's VisionProcessor, expands each rendered image token to <|image_start|> + N x <|patch|> + <|image_end|>, keeps the renderer's loss mask (model output only), shifts labels and drops overlong samples. It raises when a content part is not text or image, when placeholders do not match images, when the renderer already expands media, when the tokenizer is not a MultiModalTokenizer, and when Trainer.Config.vision_processor is not set. The content check runs before rendering because renderers can render other media parts as placeholders with no pixels (Glimmer renders a video part as <|video|>) or skip them (Glimmer drops an image_url part).
- Add expand_image_placeholders (multimodal/utils/text.py). It works on token ids.
- Muse Spark renderer: an image part renders as one <|patch|> token, which the processor expands (as transformers' MuseSparkProcessor does). Other media parts raise.
- Text-only paths reject non-text content parts with a shared require_content_types(messages, TEXT_CONTENT_TYPES) in torchtitan/components/renderer.py: both ChatProcessor paths (renderer and apply_chat_template). MultiModalChatProcessor calls it with the text types plus "image". This is needed because of the Spark renderer change: Spark returns no multi_modal_data for an image, so the multi_modal_data check in ChatProcessor no longer fires. A part with no type key counts as text.
- TokenEnv raises when the messages have image parts but the renderer returns no multi_modal_data. TokenEnv already supports image prompts from an image-reference renderer, so it keeps that path and only closes this gap: without the check, the Spark renderer's <|patch|> token would reach the generator with no image behind it.
- Add VisionProcessor.process_images(images): it resizes and normalizes each image and counts its placeholder tokens, and raises on a bad image. _process_mm_sample and MultiModalChatProcessor call it and keep only the data rule: drop the sample and log a warning when an image fails. The image loop moves out of _process_mm_sample with the same behavior.
## Numerics
No computation change. Existing multimodal datasets go through the same image processing and placeholder insertion; no loss comparison was run. Text-only chat data is unchanged; it only raises earlier on media parts.
## Testing
- CPU tests, each with the regression it catches:
- Placeholder count mismatch in expand_image_placeholders raises (silent misalignment of images and tokens).
- Chat processing with the Spark and Glimmer renderers keeps loss on the answer only (loss on prompt or image tokens).
- The loss mask survives packing and collation (mask lost or shifted by packing).
- Image parts are rejected in both ChatProcessor paths, renderer and apply_chat_template (pixel-less placeholder tokens; apply_chat_template accepted them).
- A video or an image_url part is rejected by MultiModalChatProcessor with the Glimmer renderer (a pixel-less <|video|> placeholder, or a silently dropped part).
- TokenEnv rejects image parts that the renderer rendered without images (a pixel-less <|patch|> token in an RL prompt).
- CPU tests at this commit: components/data, components/test_renderer.py, models/muse_spark, models/muse_glimmer, config and recipes 665 passed, 1 skipped, 3 xfailed; RL CPU tests 586 passed, 10 skipped (test_dapo_math and test_geometry3k need math_verify and test_vllm_wrapper needs attn_gym.mla, which are not installed locally; they also fail to import on main).
## Known issues / follow-ups
- Optional: a microbatch-level check in Muse Spark preprocess_inputs that the placeholder count equals the encoder output rows. Spark gathers by bank indices and does not check. The row formula is model-owned, so the check belongs there, not in the shared collator. Per sample, expand_image_placeholders already checks the count.
stack-info: PR: #5885, branch: fegin/stack/14
|
@claude review this pr |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The design is sound and has a consumer (the SLAKE recipe in #5895). MultiModalChatProcessor has a small validation gap that can silently train on media without pixels. A maintainer still needs to review, because this touches components/data, components/renderer.py and RL TokenEnv.
What this PR does. It adds MultiModalChatProcessor, a Grain sample processor for chat SFT with images:
- It renders the messages with a chat renderer that emits one
<|patch|>per image. - It processes the images and expands each placeholder to
<|image_start|>+ N x<|patch|>+<|image_end|>. - It keeps the renderer's loss mask, so only the answer gets loss.
The Muse Spark renderer now emits <|patch|> for image parts instead of raising. Because of that, the text-only paths (the ChatProcessor renderer path and TokenEnv) gain an explicit require_text_content guard. The rest of the change is mechanical: an _ImageProcessor base class and a shared _process_images helper.
Example.
user: [image(56x84), "Which organ?"] assistant: "Liver"
rendered: ... <|patch|> Which organ? ... Liver<|eot|>
expanded: ... <|image_start|> <|patch|>x6 <|image_end|> Which organ? ... Liver<|eot|>
labels: IGNORE everywhere except the assistant output span
Before: ChatProcessor raised on the image (Spark), and no processor did chat masking with images.
Must fix
mm_datasets.py:537-544: only"image"parts are checked. With the Glimmer renderer, a"video"part trains as a<|video|>token with no pixels, and animage_url/input_imagepart is dropped silently. Reject any part that is not text or image (see the inline comment).mm_datasets.py:514: check forMultiModalTokenizer, notHuggingFaceTokenizer. Otherwise a plainHuggingFaceTokenizerpasses the check and the run fails with anAttributeErrorin a data worker.
Should consider
text_datasets.py:194: callrequire_text_contentbefore the renderer branch so theapply_chat_templatepath is covered too (one line).
Questions
- The Verifiers rollouter renders prompts in its client with the in-tree renderer. Those prompts don't go through
TokenEnv, so they skip the new guard. Now that the Spark renderer accepts image parts, a Verifiers env that sends image content would get a<|patch|>with no pixels instead of an error. Is that path text-only by contract, or should it check too?
Details
- Necessity: on the base branch,
ChatProcessorrejects media and the interleaved processors put loss on all text, so VQA-style chat SFT is not possible. The example in the description reproduces against the code. - Placeholder safety: Spark escapes a literal
<|patch|>in text (< |patch|>, and the renderer test pins this). Glimmer does not escape it. A literal<|patch|>in Glimmer text therefore makesexpand_image_placeholdersraise on a count mismatch. That is loud rather than silent, so I'm not listing it as a finding. - Label shift:
labels[~loss_mask[1:]]matchesChatProcessor._tokenize_with_renderer. The inserted start/patch/end tokens get no loss, which also holds for images in assistant turns. - The expanded layout (start + N x patch + end) matches
insert_vision_placeholdersin the existing VisionProcessor path. Muse Spark and Glimmerpreprocess_inputsgather byimage_idpositions only. - Mechanical parts checked:
_process_mm_samplenow forwards**image_kwargstoprocess_image. Its only callers (OBELICS, CC12) pass exactly theprocess_imagearguments.- It no longer changes the caller's
textslist in place. - VisionProcessor's fields and behavior are unchanged.
Not verified: GPU training. The unit tests were not run in this job.
| images = [ | ||
| cast(ImagePart, part)["image"] | ||
| for message in messages | ||
| for part in ( | ||
| message["content"] if isinstance(message.get("content"), list) else () | ||
| ) | ||
| if part.get("type") == "image" | ||
| ] |
There was a problem hiding this comment.
This picks out only "image" parts and counts on the renderer to reject any other media. Spark does reject them, but Glimmer, which is one of the two renderers this PR tests, does not: muse_glimmer/renderer.py:160-175 renders "video" as <|video|> and skips every other unknown type without an error.
What happens with Glimmer:
- A
{"type": "video", ...}part trains as a<|video|>token with no pixels behind it. Glimmer'spreprocess_inputsonly checks images, so nothing catches it. - An
{"type": "image_url", ...}or{"type": "input_image", ...}part is dropped quietly, and the sample trains as text only.
In both cases the placeholder count still matches the number of images, so expand_image_placeholders passes. This is the same kind of hole that require_text_content closes for the text path.
Fix: reject any part whose type is not text or "image" before rendering. For example, add an allowed-types argument to require_text_content and call it here with _TEXT_CONTENT_TYPES | {"image"}, or raise inside this loop. That is about 5 lines, and it lets the processor stop depending on how each renderer handles unknown parts.
|
|
||
| def __init__(self, config: Config, *, context: DatasetBuildContext) -> None: | ||
| super().__init__(config, context=context) | ||
| if not isinstance(context.tokenizer, HuggingFaceTokenizer): |
There was a problem hiding this comment.
__call__ reads tokenizer.image_id, vision_start_id and vision_end_id. Only MultiModalTokenizer sets these (tokenizer.py, setattr(self, f"{name}_id", ...)). A plain HuggingFaceTokenizer passes this check, and the run then fails with an AttributeError on the first sample, inside a data worker, instead of a ValueError when the processor is built. That is also why the three pyrefly: ignore lines are there.
| if not isinstance(context.tokenizer, HuggingFaceTokenizer): | |
| if not isinstance(context.tokenizer, MultiModalTokenizer): | |
| raise ValueError("MultiModalChatProcessor requires a MultiModalTokenizer.") |
(Also update the description, which says "raises when the tokenizer is not a HuggingFaceTokenizer".)
| ) -> TextSequence | None: | ||
| if not messages or messages[-1]["role"] != "assistant": | ||
| raise ValueError("Chat samples must end with an assistant message.") | ||
| require_text_content(messages) |
There was a problem hiding this comment.
Should consider: this guard only covers the renderer path. The apply_chat_template path (no renderer, __call__ lines 161-183) still accepts list content with image parts, and an HF template typically renders those as a placeholder token with no pixels. The gap already exists on the base branch, but moving this single call into __call__, right after messages = self._messages_fn(sample), covers both text paths and fits this PR's goal that text-only paths reject media.
…regions (#5886) Stacked PRs: * #5904 * #5895 * #5894 * #5893 * #5892 * #5891 * #5890 * #5889 * #5888 * #5887 * #5885 * __->__#5886 --- --- --- ### [distributed] Keep grads of async collective inputs to local_compile regions ## Summary (human-written) See the issue: pytorch/pytorch#201700 This is a bug when compiling: AOTAutograd doesn't trace through AsyncCollectiveTensors and loses the requires_grad. This PR works around the problem in general. But the real solution should be fixing pytorch/pytorch#201700. ## Why On main, Muse Spark with TP > 1 and local compile on never trains tok_embeddings: its grad is None, for text-only and multimodal runs, with SP on and off. Module-boundary redistributions return un-awaited AsyncCollectiveTensors (async_op=True). AOTAutograd unwraps such an input with trigger_wait(), which returns the inner tensor without requires_grad (torch/_functorch/_aot_autograd/frontend_utils.py, added by pytorch/pytorch#179849), so the compiled region's output has no grad path back to the input. In Spark, the embedding output redistribution feeds the compiled embedding norm. Tracking issue: pytorch/pytorch#201700 (pytorch/pytorch#191113 is a closed, unmerged PR for the same bug). **Example.** ``` emb = tok_embeddings(tokens) # redistributed at the Module boundary -> AsyncCollectiveTensor h = compiled_norm(emb) # local_compile region loss(h).backward() before: tok_embeddings.weight.grad is None after: tok_embeddings.weight.grad is set ``` ## What changed - Every local_compile region and always-compiled helper is wrapped so an AsyncCollectiveTensor argument is awaited by a small autograd Function before the compiled call. The Function keeps the autograd edge. - Only top-level arguments are awaited. No in-tree region or always-compiled helper takes tensors inside a container (checked every signature; the only container argument is gdn's split_sizes: list[int]). - TODO(pytorch/pytorch#201700) in code: remove once AOTAutograd keeps the requires_grad of an unwrapped AsyncCollectiveTensor input. - The same bug hits the async k_shared all-gather into the mla_kv region in open PRs #5564 and #5682, which work around it with async_op=False. k_shared is a top-level argument of that region, so this fix covers it and they can keep async_op=True. In-tree CP MLA is not affected: in UlyssesMLAAttention only the k_shared all-gather stays async, and it feeds the eager materialize_mla_kv. The Q/KV all-to-all is synchronous in spmd_types 0.3.1, so the compiled flex call gets plain tensors. ## Alternatives considered - Wait inside Module redistribution (async_op=False): gives up the comm overlap for every Module boundary, not only compiled regions. - Fix in each model: the bug is in the local_compile layer and affects any model with a compiled region after a redistribution. ## Numerics Only Muse Spark with TP > 1 and local compile on changes: tok_embeddings gets grads and trains. Configs below were checked; others are unchecked. Setup: 2x H100, BASE = parent commit, TEST = this commit. debug.seed = 42, debug.deterministic = True, 10 steps, c4_test. Loss and grad_norm are read from TensorBoard. **Muse Spark debugmodel, TP2 + EP2 + SP, flex, default local_compile regions.** Changes, as expected. Step 1 loss is equal (same forward); step 1 grad_norm differs by the added tok_embeddings grad. | step | BASE loss | BASE grad_norm | TEST loss | TEST grad_norm | |---|---|---|---|---| | 1 | 7.82727003 | 4.97379541 | 7.82727003 | 4.97423124 | | 2 | 7.03273010 | 3.67558002 | 7.03092051 | 3.66602159 | | 3 | 6.13859034 | 2.72887707 | 6.14003372 | 2.73221183 | | 4 | 5.76145124 | 2.13588810 | 5.76339674 | 2.15090728 | | 5 | 5.83007097 | 2.06997371 | 5.82927275 | 2.06360984 | | 6 | 5.56987143 | 1.85165656 | 5.56976700 | 1.84894443 | | 7 | 5.37956715 | 1.88629401 | 5.37123251 | 1.88281417 | | 8 | 6.01605892 | 1.97213578 | 6.01554680 | 1.95823133 | | 9 | 5.18035460 | 1.96500850 | 5.18841839 | 1.98249125 | | 10 | 5.20351505 | 1.78124106 | 5.20615530 | 1.78476560 | - Step 1 per-parameter grads (local grad norm, both ranks): tok_embeddings.embedding.weight is None in BASE and nonzero in TEST (rank 0: 0.06576, rank 1: 0.00345). The other 225 parameters have bitwise equal grad norms. - Determinism: two TEST runs give bitwise equal loss and grad_norm at all 10 steps and equal step 1 per-parameter grads. So the BASE/TEST difference comes from this change. **DeepSeek V3 debugmodel, CP2, flex, default local_compile regions.** Unchanged: loss, grad_norm, and step 1 per-parameter grads are bitwise equal for both CP MLA backends. - UlyssesMLAAttention (no load balancer): step 10 loss 4.13782024, grad_norm 2.26978993 in BASE and TEST. - AllGatherKVMLAFlexAttention (no load balancer; the CP attention of the deepseek_v3_cp_pp golden): step 10 loss 4.13834953, grad_norm 2.27362609 in BASE and TEST. Not checked: DeepSeek V3 varlen with CP, because FlashAttention 3 supports head dim at most 128 and the debug MLA head dim is 192. ## Testing - CPU test: a compiled region (aot_eager) on an AsyncCollectiveTensor input passes the grad back. It fails without the fix. - CPU tests at this commit: tests/unit_tests/cpu/config/test_compile_config.py, 9 passed.
eba2ede to
ed98b45
Compare
… processor (#5887) Stacked PRs: * #5904 * #5895 * #5885 * #5894 * #5893 * #5892 * #5891 * #5890 * #5889 * #5981 * #5888 * __->__#5887 --- --- --- ### [muse_spark] Resample multimodal images with LANCZOS, as the released processor ## Summary (human-written) Use the correct resample for Muse Spark ## Why The Muse Spark multimodal dataloader resizes images with VisionProcessor's default interpolation, BICUBIC. The released Muse Spark processor_config.json resamples with LANCZOS (resample=1). So on main, training sees slightly different pixels than the released model's preprocessing. **Example.** ``` MUSE_SPARK_VISION_PROCESSOR_KWARGS before: image_interpolation_mode = "bicubic" (VisionProcessor default) after: image_interpolation_mode = "lanczos" (processor_config.json resample=1) ``` ## What changed - MUSE_SPARK_VISION_PROCESSOR_KWARGS sets image_interpolation_mode="lanczos". It applies to every Muse Spark multimodal recipe, for images and video frames. ## Numerics Image preprocessing changes for every Muse Spark multimodal recipe, including muse_spark_debugmodel_mm, so their multimodal losses change. Muse Spark has no golden loss files. Text-only recipes are unchanged. ## Testing - No new test: this is a single config value. tests/unit_tests/cpu/recipes/test_muse_spark.py builds muse_spark_debugmodel_mm; 6 passed at this commit.
…e_glimmer_30b_mm test recipe (#5888) Stacked PRs: * #5904 * #5895 * #5885 * #5894 * #5893 * #5892 * #5891 * #5890 * #5889 * #5981 * __->__#5888 --- --- --- ### [recipes] Use the released Muse tokens and image processor in the muse_glimmer_30b_mm test recipe ## Summary (human-written) The Muse Glimmer multimodal recipe uses incorrect tokens and image processor. This PR fixes the mismatch. ## Why On main, muse_glimmer_30b_mm does not build. It uses the Qwen-style debug tokens (<|image_pad|>, <|vision_start|>, ...), which the released Muse Glimmer 30B tokenizer does not have, so the tokenizer build raises. It also uses the debug pixel budget (max_pixels=3136, 4 merged tokens per image), not the released image processor. **Example.** ``` before: muse_glimmer_30b_mm -> tokenizer build raises (no <|image_pad|> in the released tokenizer) after: image tokens <|patch|> (200092), <|video|> (200091), <|image_start|> (200080), <|image_end|> (200081), pad <|finetune_right_pad|> (200018) images: closest-aspect grid up to 4096 merged tokens, LANCZOS ``` ## What changed - muse_glimmer_30b_mm uses the released special tokens and image processor. Its output matches the HF MuseGlimmerImageProcessor to 1.2e-7 with identical grids. - The released image processor is MUSE_GLIMMER_30B_VISION_PROCESSOR_KWARGS: the Muse Spark recipe's MuseGlimmerPatchGridResize with max_image_tokens=4096, and LANCZOS. Images only. - Mechanical: the debug token map and image processor settings are renamed MUSE_GLIMMER_DEBUG_SPECIAL_TOKENS and MUSE_GLIMMER_DEBUG_VISION_PROCESSOR_KWARGS. The debug recipe keeps them, because the debug tokenizer asset defines only those tokens. ## Numerics muse_glimmer_30b_mm did not build on main, so there is no baseline. The Muse Glimmer debug recipe and the Muse Spark recipes are unchanged (same tokens, same image processor). ## Testing - CPU test: three resize grids match the HF processor, one on the 4096-token cap path. It catches drift from the released processor. - CPU tests at this commit: recipes/test_muse_spark.py, components/data, models/muse_spark and models/muse_glimmer all pass (3 xfailed). Skips depend on the environment: one test needs a local tokenizer directory, one needs an accelerator.
|
@claude pleaser re-review since this PR just rebased |
There was a problem hiding this comment.
Verdict: Approve -- the rebased commit fixes every earlier item and maintainer comment, and introduces no new problems. A maintainer still needs to review, because this touches components/data, components/renderer.py and RL TokenEnv.
What changed since the last review. _ImageProcessor is gone. MultiModalChatProcessor is now a plain SampleProcessor that uses the trainer's vision_processor. The image loop moved to VisionProcessor.process_images. require_text_content became require_content_types(messages, allowed_types). TokenEnv now builds on #5824: it no longer rejects all media, and only raises when image parts render with no multi_modal_data.
Example.
user: [image(56x84), "Is it a lung?"] assistant: "yes"
rendered: ... <|patch|> Is it a lung? ... yes<|eot|>
expanded: ... <|image_start|> <|patch|>x6 <|image_end|> ... yes<|eot|>
labels: IGNORE except " to=user<|message|>yes<|eot|>" (Spark) / "yes<|eot|>" (Glimmer)
user: [{"type": "video", ...}, "Lung?"] with Glimmer -> ValueError "Unsupported 'video' content part."
Earlier items
- Resolved: non-text, non-image parts are rejected before rendering (
mm_datasets.py:432, via_CHAT_CONTENT_TYPES). Video andimage_urlare covered with Glimmer. - Resolved: the processor now checks for
MultiModalTokenizer(mm_datasets.py:415). - Resolved:
ChatProcessorchecks content types in__call__, so both the renderer path and theapply_chat_templatepath are covered (text_datasets.py:157). Both are tested. - Resolved (@tianyu-l): rebased onto #5873, and
process_imagesis aVisionProcessormethod that leaves the drop-sample decision to the caller. - Resolved (@tianyu-l, @wwwjn):
TokenEnvis rebased onto #5824 and uses the narrower image-parts-vs-multi_modal_datacheck.
Questions
- Still open from the last review: Verifiers prompts are rendered in the client, so they don't go through
TokenEnv. Is that path text-only by contract? Now that the Spark renderer accepts image parts, an image part sent there would turn into a<|patch|>token with no pixels instead of an error.
Details
- Dropping the
multi_modal_data is not Nonecheck fromChatProcessor._tokenize_with_rendereris safe.require_content_typesnow rejects image parts before rendering, and only image parts producemulti_modal_datain the in-tree renderers. _process_mm_samplebehaves as before. A missingvision_processorstill raises outside thetry. A bad image still drops the sample with a warning.textsis no longer changed in place, and each image position becomesNoneas before.TokenEnv._to_prompt:image_partsis collected once and reused for the path/hash alignment, so the logic is unchanged. Glimmervideo/image_urlparts in RL prompts are still unchecked there. That gap exists on the base branch too, and this PR only claims to close the image case.- The
pyrefly: ignorelines ontokenizer.image_idetc. are still needed:MultiModalTokenizersets those attributes withsetattr.
Not verified: GPU training. I did not run the unit tests in this job.
Stacked PRs:
[data] Multimodal chat SFT: image in the user turn, loss on the answer only
Summary (human-written)
Enable multimodal chat SFT -- image only.
Why
On main there is no way to train VQA-style chat SFT with images. ChatProcessor is text-only and raises on any media. The multimodal processors take interleaved text and images with loss on all text, not chat turns with loss on the answer only.
Example.
What changed
Numerics
No computation change. Existing multimodal datasets go through the same image processing and placeholder insertion; no loss comparison was run. Text-only chat data is unchanged; it only raises earlier on media parts.
Testing
Known issues / follow-ups