Repository navigation
[recipes] Muse Spark SLAKE LoRA SFT recipes: LoRA decoder, LoRA vision + decoder - #5895
Conversation
…n + decoder
## Summary (human-written)
LoRA recipes for Muse Spark Open to train SLAKE dataset.
## Why
There is no recipe to fine-tune Muse Spark 816B-A42B_mm on medical VQA. SLAKE is small (4,919 English train samples), so LoRA is enough; full fine-tuning would overfit and needs many more GPUs. The SLAKE ablation compares LoRA on the decoder with LoRA on vision + decoder.
**Example.**
```
config = muse_spark_816b_a42b_slake_lora_vision_decoder_sft()
# 8 GB300, dp_shard=8 x EP=8, 4K packed sequences, 60 steps
# trainable: LoRA adapters on the decoder and on the vision encoder, adapter and projection
```
## What changed
- Add two English SLAKE LoRA SFT recipes: vision is the only dataset modality, the image is in the user turn, loss is on the answer only (MultiModalChatProcessor.Config), rows are packed, and CUDA graphs are off. The prompt uses reasoning_effort="low" (Reasoning strength 8, the lowest level the published chat template supports) and no date line: SLAKE targets are direct answers with no reasoning, so a high reasoning strength in the prompt would teach the model to skip reasoning when asked to reason.
- The user turn ends with the LLaVA 1.5 short-answer prompt "Answer the question using a single word or phrase." SLAKE labels are single words or short phrases. A forward-only check of the released weights on 40 English validation rows (job 2383724) without and with the prompt: answer-token loss 5.47 -> 2.79, <|eot|> loss 12.90 -> 0.22; greedy answers with the to=user header prefilled went from full sentences (0/40 exact match) to yes/no 13/15 and open 9/25 exact. A comment explains why it is needed and when RL prompts need it.
- LoRA targets are listed explicitly; the router gate is not a target. The decoder targets are one module-private constant shared with the UltraData LoRA recipe. LoRA vision + decoder adapts the vision attention and MLP, the vision adapter and the projection; conv1_linear stays frozen.
- _muse_spark_mm_dataloader accepts MultiModalChatProcessor.Config as well as VisionProcessor.Config.
- Validation loss on the English validation split runs at step 1 and every 10 steps, through the training data path with validation.json as the source. Steps cover the split once: ceil(214 packed microbatches / DP degree), so 27 at DP 8. One validation pass took about 27 s in job 2384192 (LoRA vision + decoder, 8 GB300), with memory at or below the training peak. The SLAKE root must hold validation.json.
- Metrics go to TensorBoard (event files under <dump folder>/tb), so runs can be compared and shared; the base 816B config exports nothing.
- max_images_per_microbatch comes from the shortest English SLAKE sample (219 tokens, measured with the recipe's data path). The SLAKE root defaults to ./assets/datasets/slake; the MUSE_SPARK_SLAKE_PATH env var overrides it.
- Training runs 60 steps, about 2 passes over the English train split (one pass is 28.7 steps after packing). A 90-step LoRA vision + decoder run with validation every 10 steps on the English validation split (job 2384192, 8 GB300, no checkpoint saved) had validation loss 3.22 at step 1, 0.107 at step 30, 0.063 at step 60 (lowest) and 0.072 at step 90, while training loss kept falling. The LoRA decoder variant uses the same count without a separate measurement. Learning rates are untuned starting points.
- Both recipes target 8 GB300 GPUs: dp_shard=8, EP=8 (256 experts / 8), TP=CP=PP=1, no sequence parallel. They keep dtype=float32, so the frozen base is stored in bf16 (frozen params use param_dtype storage) while adapters, grads and AdamW state stay fp32. seq_len is 4096 and a step is 32 x 4096 tokens, so each DP rank runs 4 accumulation microbatches of 4096 tokens. max_images_per_microbatch is 4096 // 219 = 18.
- Both use the GB300 settings of the UltraData LoRA recipe: BF16 Dist-MoE (inplace_wgrad_accum=False; activation slot 0.25, scratch 16.0), remat that saves the Dist-MoE save regions, local compile of the loss only, no fused-swiglu override, and 1800 s comm timeouts. Attention is flex with FA4 (BACKEND=FLASH); the UltraData recipe uses varlen with FA4. Dist-MoE and FA4 need SM100. CUDA graphs stay off.
- A comment cites the sizing: a fake-PG run of this layout and these settings (job 2368236, a recipe not in this PR, random init, forced balanced routing) used 254 GiB allocated / 261 GiB reserved of 276.6 GiB per GPU (steady-state max over steps 2-5); dp_shard=16 and EP=16 give more headroom.
- Mechanical: the UltraData LoRA recipe's Dist-MoE runtime, remat and compile-region setup moves into _use_gb300_lora_dist_moe, and its decoder targets move into _MUSE_SPARK_LORA_DECODER_TARGETS; both are shared with the SLAKE recipes. The UltraData config is unchanged (to_dict compared before and after, ignoring function object addresses).
## User-facing changes
| Before | After |
| --- | --- |
| No SLAKE recipes | muse_spark_816b_a42b_slake_{lora_decoder,lora_vision_decoder}_sft |
| - | SLAKE recipes: dp_shard=8, EP=8 on 8 GB300, BF16 Dist-MoE, FA4, validation, TensorBoard |
## Numerics
No change to existing recipes: the UltraData LoRA config is identical before and after (to_dict compared, ignoring function object addresses). The SLAKE recipes are new and have no baseline; they were sized with fake PG. LoRA vision + decoder at this commit's settings ran 60 steps on 8 GB300 from the released HF checkpoint (job 2385319): validation loss 3.23 at step 1, 0.104 at step 30 and 0.066 at step 60; peak 261.6 GiB of 276.6 GiB; 12.2 s per step; no NaN or recompile.
## Testing
- CPU test: both recipes' LoRA transforms build the expected trainable split on debugmodel_mm. It catches a renamed module, since LoRA only warns on unmatched targets.
- CPU recipe tests at this commit: 51 passed. recipes/test_muse_spark.py and config/test_transforms.py: 44 passed.
- --print-config passes for both SLAKE recipes (config __post_init__ validation included). Their processor is MultiModalChatProcessor.Config with the Spark patch size and LANCZOS.
- CPU tests at this commit: recipes, components/data, models/muse_spark, models/common, config and distributed, 1021 passed, 1 skipped, 3 xfailed.
## Known issues / follow-ups
- The LoRA decoder variant has not been run on GB300.
- TODO in code: drop train rows whose image is a duplicate or an adjacent slice of a validation or test image (same scan series), so test cases do not leak into training.
stack-info: PR: #5895, branch: fegin/stack/24
|
@claude review this pr |
There was a problem hiding this comment.
Verdict: Approve -- The PR only adds two recipes and makes one mechanical refactor in the recipe file, and the refactor keeps the UltraData config the same. Nothing I found blocks merging. The comments below are optional simplifications.
What this PR does. It adds two English SLAKE LoRA SFT recipes for Muse Spark 816B-A42B_mm on 8 GB300: decoder-only LoRA, and LoRA on vision + decoder. Each runs validation through the training data path, with validation.json as the source. It moves the GB300 BF16 Dist-MoE, remat and compile setup, plus the decoder LoRA targets, out of the UltraData recipe so both recipes can share them. It also lets _muse_spark_mm_dataloader accept MultiModalChatProcessor.Config.
Example.
row = {"img_name": "xmlab1/source.jpg", "question": "Which organ is abnormal?", "answer": "Liver", "q_lang": "en"}
user: [image] "Which organ is abnormal?\nAnswer the question using a single word or phrase."
assistant: "Liver" <- loss on answer tokens only
system: reasoning_effort="low", no date line
packed into 4096-token microbatches, at most 4096 // 219 = 18 images each
lora_decoder: adapters on wqkv/wo/output_gate/w13/w2
lora_vision_decoder: + vision attn/mlp, vision_adapter, vision_projection (conv1_linear frozen)
Should consider
torchtitan_recipes/models/muse_spark.py:705--_use_gb300_lora_dist_moechangesconfigand returns a transform that has to be applied before LoRA. Taking the LoRA transform and callingapply_transformsinside removes that ordering rule and the comm-timeout /override.importslines both recipes repeat.tests/unit_tests/cpu/recipes/test_muse_spark.py:84-- the test makes up forLoRATransformonly warning on unmatched targets. RaisingValueErrorthere in a follow-up PR would cover every LoRA recipe.torchtitan_recipes/models/muse_spark.py:948--_SlakeVariantis a mode string. It only chooses the target list and the checkpoint folder name, so the two public recipes could passlora_targets(and the folder) directly and drop theLiteraland the branch. Minor.
Questions
torchtitan_recipes/models/muse_spark.py:940-- was the 214 count measured at DP=1? Packing on each rank separately can change the total and how bins are spread across ranks.
Details
- Checked: LoRA matches targets on config FQNs (
vision_encoder.block.mlp.fc1), while the test checks module FQNs (layers.0.mlp.linear_fc1). Both line up with_matches_fqn, which matches an exact name or a dot-delimited suffix. - The validator sets
repeat=Truewhensteps > 0and rebuilds the dataloader with seed 42 on every pass, so each validation pass sees the same order. replace(model_config, dataset_modalities=("vision",))keeps the audio encoder in the model, and LoRA freezes it. That matches theMuseSparkModel.Configdocstring, which says unlisted encoders are skipped but kept in checkpoints.- The loss vocab size comes from the text
816B-A42Bconfig that gets thrown away. The_mmflavor uses the same_muse_spark_816b_a42bfactory, so the vocab size is the same. lr_scheduler.total_stepsisn't set, so it falls back totraining.steps=60, which is what you want here.- Overlap and direction: the PR builds on Grain data, Dist-MoE, torch_remat and
ModelConfigTransform, and nothing indirection.mdgoes against it.
Not verified: GB300 memory and step time, and the LoRA decoder variant on hardware (the PR description already notes this).
| def _use_gb300_lora_dist_moe(config: Trainer.Config) -> ModelConfigTransform: | ||
| """Set the GB300 BF16 Dist-MoE runtime, remat and compile regions for LoRA SFT. | ||
|
|
||
| Returns the Dist-MoE transform; apply it before the LoRA transform. | ||
| """ | ||
| from torchtitan.config.transform.dist_moe import DistMoeTransform | ||
| from torchtitan.models.common.dist_moe.runtime import DistMoeRuntime | ||
|
|
||
| config.model.local_compile.regions = ["loss"] | ||
| config.activation_remat = ActivationRematConfig( | ||
| save_regions=list(_MUSE_SPARK_DIST_MOE_SAVE_REGIONS), | ||
| ) | ||
| config.dist_moe_runtime = DistMoeRuntime.Config( | ||
| activation_slot_capacity_factor=0.25, | ||
| scratch_capacity_factor=16.0, | ||
| vmm_capacity_factor=None, | ||
| ) | ||
| return DistMoeTransform(expert_precision="bf16", inplace_wgrad_accum=False) |
There was a problem hiding this comment.
This helper changes config and also returns a transform that the caller has to apply before the LoRA transform. That ordering rule only lives in the docstring. Both callers also repeat the other GB300 LoRA settings by hand: comm.init_timeout_seconds = 1800, comm.train_timeout_seconds = 1800 and override.imports = [].
Smaller option: have it take the LoRA transform and return the finished config:
def _apply_gb300_lora_dist_moe(config: Trainer.Config, lora: LoRATransform) -> Trainer.Config:
... # local_compile, remat, dist_moe_runtime, comm timeouts, override.imports = []
return apply_transforms(
config, [DistMoeTransform(expert_precision="bf16", inplace_wgrad_accum=False), lora]
)Callers can't get the order wrong this way, and the 3 duplicated lines in each recipe go away. UltraData's sdpa_backends loop already runs after apply_transforms, so it isn't affected. You'd also no longer need the new ModelConfigTransform import.
| def test_slake_lora_trainable_split(variant): | ||
| # LoRA only warns on unmatched targets; this catches a renamed module. |
There was a problem hiding this comment.
This test exists because LoRATransform.transform only warns about unmatched target_modules (torchtitan/config/transform/lora.py:302-307), so a renamed module silently freezes everything. The same gap affects every LoRA recipe, UltraData included, not just SLAKE. Under principle 8 the root fix is to raise ValueError there. That belongs in its own small PR. After it lands, the rename case in this test is covered for every recipe, and the test can shrink to the checks the error can't express: no vision adapters in lora_decoder, and conv1 stays frozen. Can you note that follow-up, or point to an open PR that already does it?
| config.validator = Validator.Config( | ||
| freq=10, | ||
| # One validation step is one microbatch per DP rank; cover the split once. | ||
| steps=math.ceil(_SLAKE_VALIDATION_MICROBATCHES / dp_degree), |
There was a problem hiding this comment.
Question (unverified): how was the 214 measured? If samples are split across DP ranks before MMSamplePackingConfig packs them, each rank packs its own share. Packing 8 smaller shares wastes more space per bin, so the total across ranks can be higher than a single-rank count of 214. Some ranks can also get 28 bins. With steps=27 and the validator forcing repeat=True, those ranks skip their last bin and others wrap into a second epoch, so one pass doesn't quite "cover the split once". The effect on the loss is small, but if 214 is a DP=1 count, say so in the comment. If the coverage claim matters, size steps from the largest per-rank bin count.
…n + decoder
## Summary (human-written)
LoRA recipes for Muse Spark Open to train SLAKE dataset.
## Why
There is no recipe to fine-tune Muse Spark 816B-A42B_mm on medical VQA. SLAKE is small (4,919 English train samples), so LoRA is enough; full fine-tuning would overfit and needs many more GPUs. The SLAKE ablation compares LoRA on the decoder with LoRA on vision + decoder.
**Example.**
```
config = muse_spark_816b_a42b_slake_lora_vision_decoder_sft()
# 8 GB300, dp_shard=8 x EP=8, 4K packed sequences, 60 steps
# trainable: LoRA adapters on the decoder and on the vision encoder, adapter and projection
```
## What changed
- Add two English SLAKE LoRA SFT recipes: vision is the only dataset modality, the image is in the user turn, loss is on the answer only (MultiModalChatProcessor.Config), rows are packed, and CUDA graphs are off. The prompt uses reasoning_effort="low" (Reasoning strength 8, the lowest level the published chat template supports) and no date line: SLAKE targets are direct answers with no reasoning, so a high reasoning strength in the prompt would teach the model to skip reasoning when asked to reason.
- The user turn ends with the LLaVA 1.5 short-answer prompt "Answer the question using a single word or phrase." SLAKE labels are single words or short phrases. A forward-only check of the released weights on 40 English validation rows (job 2383724) without and with the prompt: answer-token loss 5.47 -> 2.79, <|eot|> loss 12.90 -> 0.22; greedy answers with the to=user header prefilled went from full sentences (0/40 exact match) to yes/no 13/15 and open 9/25 exact. A comment explains why it is needed and when RL prompts need it.
- LoRA targets are listed explicitly; the router gate is not a target. The decoder targets are one module-private constant shared with the UltraData LoRA recipe. LoRA vision + decoder adapts the vision attention and MLP, the vision adapter and the projection; conv1_linear stays frozen.
- _muse_spark_mm_dataloader accepts MultiModalChatProcessor.Config as well as VisionProcessor.Config.
- Validation loss on the English validation split runs at step 1 and every 10 steps, through the training data path with validation.json as the source. Steps cover the split once: ceil(214 packed microbatches / DP degree), so 27 at DP 8. One validation pass took about 27 s in job 2384192 (LoRA vision + decoder, 8 GB300), with memory at or below the training peak. The SLAKE root must hold validation.json.
- Metrics go to TensorBoard (event files under <dump folder>/tb), so runs can be compared and shared; the base 816B config exports nothing.
- max_images_per_microbatch comes from the shortest English SLAKE sample (219 tokens, measured with the recipe's data path). The SLAKE root defaults to ./assets/datasets/slake; the MUSE_SPARK_SLAKE_PATH env var overrides it.
- Training runs 60 steps, about 2 passes over the English train split (one pass is 28.7 steps after packing). A 90-step LoRA vision + decoder run with validation every 10 steps on the English validation split (job 2384192, 8 GB300, no checkpoint saved) had validation loss 3.22 at step 1, 0.107 at step 30, 0.063 at step 60 (lowest) and 0.072 at step 90, while training loss kept falling. The LoRA decoder variant uses the same count without a separate measurement. Learning rates are untuned starting points.
- Both recipes target 8 GB300 GPUs: dp_shard=8, EP=8 (256 experts / 8), TP=CP=PP=1, no sequence parallel. They keep dtype=float32, so the frozen base is stored in bf16 (frozen params use param_dtype storage) while adapters, grads and AdamW state stay fp32. seq_len is 4096 and a step is 32 x 4096 tokens, so each DP rank runs 4 accumulation microbatches of 4096 tokens. max_images_per_microbatch is 4096 // 219 = 18.
- Both use the GB300 settings of the UltraData LoRA recipe: BF16 Dist-MoE (inplace_wgrad_accum=False; activation slot 0.25, scratch 16.0), remat that saves the Dist-MoE save regions, local compile of the loss only, no fused-swiglu override, and 1800 s comm timeouts. Attention is flex with FA4 (BACKEND=FLASH); the UltraData recipe uses varlen with FA4. Dist-MoE and FA4 need SM100. CUDA graphs stay off.
- A comment cites the sizing: a fake-PG run of this layout and these settings (job 2368236, a recipe not in this PR, random init, forced balanced routing) used 254 GiB allocated / 261 GiB reserved of 276.6 GiB per GPU (steady-state max over steps 2-5); dp_shard=16 and EP=16 give more headroom.
- Mechanical: the UltraData LoRA recipe's Dist-MoE runtime, remat and compile-region setup moves into _use_gb300_lora_dist_moe, and its decoder targets move into _MUSE_SPARK_LORA_DECODER_TARGETS; both are shared with the SLAKE recipes. The UltraData config is unchanged (to_dict compared before and after, ignoring function object addresses).
## User-facing changes
| Before | After |
| --- | --- |
| No SLAKE recipes | muse_spark_816b_a42b_slake_{lora_decoder,lora_vision_decoder}_sft |
| - | SLAKE recipes: dp_shard=8, EP=8 on 8 GB300, BF16 Dist-MoE, FA4, validation, TensorBoard |
## Numerics
No change to existing recipes: the UltraData LoRA config is identical before and after (to_dict compared, ignoring function object addresses). The SLAKE recipes are new and have no baseline; they were sized with fake PG. LoRA vision + decoder at this commit's settings ran 60 steps on 8 GB300 from the released HF checkpoint (job 2385319): validation loss 3.23 at step 1, 0.104 at step 30 and 0.066 at step 60; peak 261.6 GiB of 276.6 GiB; 12.2 s per step; no NaN or recompile.
## Testing
- CPU test: both recipes' LoRA transforms build the expected trainable split on debugmodel_mm. It catches a renamed module, since LoRA only warns on unmatched targets.
- CPU recipe tests at this commit: 51 passed. recipes/test_muse_spark.py and config/test_transforms.py: 44 passed.
- --print-config passes for both SLAKE recipes (config __post_init__ validation included). Their processor is MultiModalChatProcessor.Config with the Spark patch size and LANCZOS.
- CPU tests at this commit: recipes, components/data, models/muse_spark, models/common, config and distributed, 1021 passed, 1 skipped, 3 xfailed.
## Known issues / follow-ups
- The LoRA decoder variant has not been run on GB300.
- TODO in code: drop train rows whose image is a duplicate or an adjacent slice of a validation or test image (same scan series), so test cases do not leak into training.
stack-info: PR: #5895, branch: fegin/stack/24
…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.
a7fcc3d to
0dd1c1a
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 please re-review |
There was a problem hiding this comment.
Verdict: Approve -- At 63b8094, both earlier comments that called for code changes are addressed, and the new commit adds no problems that block merging.
What changed since the last review. The SLAKE recipes moved out of torchtitan_recipes/models/muse_spark.py into their own module, torchtitan_recipes/sft/slake.py, with a matching test, tests/unit_tests/cpu/recipes/test_slake.py. The three helpers and the base config they reuse are now public, so no module imports another module's private names. The shared GB300 setup is now apply_gb300_lora_dist_moe(config, lora). The recipes also set vision_processor from MUSE_SPARK_VISION_PROCESSOR_KWARGS.
Example. The UltraData call site, before and after:
# before: GB300 settings set by hand, then
config = apply_transforms(config, [DistMoeTransform(...), _ultradata_lora_sft_transform()])
# after: one call sets the GB300 settings and applies both transforms, Dist-MoE first
config = apply_gb300_lora_dist_moe(config, _ultradata_lora_sft_transform())Earlier items
- Resolved:
_use_gb300_lora_dist_moeordering and duplicated settings.apply_gb300_lora_dist_moe(torchtitan_recipes/models/muse_spark.py:172) now applies Dist-MoE and then LoRA itself, and it owns the comm timeouts andoverride.imports = []. - Resolved (tianyu-l): separate file. The recipes are in
torchtitan_recipes/sft/slake.py. - Answered: the validation count. Each rank packs its share separately (25 to 32 microbatches at DP 8), and
steps=32covers the largest share (slake.py:53-57). - Still open, optional:
LoRATransform.transformstill only warns on unmatched targets (torchtitan/config/transform/lora.py:304). RaisingValueErrorin a follow-up would cover every LoRA recipe and lettest_slake.pydrop its rename check. - Still open, optional:
_SlakeVariantis still a mode string (slake.py:70). The author kept it, and it is minor.
Should consider
torchtitan_recipes/sft/__init__.py:7-- the docstring says "Verified supervised fine-tuning recipes", but the PR saysmuse_spark_816b_a42b_slake_lora_decoder_sfthas not run on GB300. Either drop "Verified" or add a note in that recipe's docstring saying it is unverified on hardware.
Details
- Checked:
Validator.should_validatereturns true forstep == 1 or step % freq == 0(torchtitan/components/validator.py:74), so "validation at step 1 and every 10 steps" is accurate. - With
steps != -1the validator forcesrepeat=True(validator.py:155), which matches the new comment that smaller ranks wrap around. - Making
muse_spark_816b_a42bpublic means--configcan select it (torchtitan/config/loader.py:124). Its docstring now says it is a base config and not verified on its own, which is enough. - No other in-repo code references the renamed private helpers. The callers in
torchtitan_recipes/tests/models/muse_spark.pyandtest_muse_spark.pyare updated.
Not verified: GB300 memory and step time; the LoRA decoder variant on hardware.
…n + decoder
## Summary (human-written)
LoRA recipes for Muse Spark Open to train SLAKE dataset.
## Why
There is no recipe to fine-tune Muse Spark 816B-A42B_mm on medical VQA. SLAKE is small (4,919 English train samples), so LoRA is enough; full fine-tuning would overfit and needs many more GPUs. The SLAKE ablation compares LoRA on the decoder with LoRA on vision + decoder.
**Example.**
```
from torchtitan_recipes.sft.slake import muse_spark_816b_a42b_slake_lora_vision_decoder_sft
config = muse_spark_816b_a42b_slake_lora_vision_decoder_sft()
# 8 GB300, dp_shard=8 x EP=8, 4K packed sequences, 60 steps
# trainable: LoRA adapters on the decoder and on the vision encoder, adapter and projection
```
## What changed
- Add two English SLAKE LoRA SFT recipes in a new torchtitan_recipes/sft/slake.py. torchtitan_recipes/sft/ holds SFT recipes, one module per dataset, like torchtitan_recipes/rl/ for RL tasks. The SLAKE data helpers stay private to that module. Vision is the only dataset modality, the image is in the user turn, loss is on the answer only (MultiModalChatProcessor.Config), rows are packed, and CUDA graphs are off. The prompt uses reasoning_effort="low" (Reasoning strength 8, the lowest level the published chat template supports) and no date line: SLAKE targets are direct answers with no reasoning, so a high reasoning strength in the prompt would teach the model to skip reasoning when asked to reason.
- The user turn ends with the LLaVA 1.5 short-answer prompt "Answer the question using a single word or phrase." SLAKE labels are single words or short phrases. A forward-only check of the released weights on 40 English validation rows (job 2383724) without and with the prompt: answer-token loss 5.47 -> 2.79, <|eot|> loss 12.90 -> 0.22; greedy answers with the to=user header prefilled went from full sentences (0/40 exact match) to yes/no 13/15 and open 9/25 exact. A comment explains why it is needed and when RL prompts need it.
- LoRA targets are listed explicitly; the router gate is not a target. The decoder targets are the UltraData LoRA recipe's targets, shared as MUSE_SPARK_LORA_DECODER_TARGETS in torchtitan_recipes/models/muse_spark.py; the CPU test checks that each one matches a decoder module. LoRA vision + decoder adapts the vision attention and MLP, the vision adapter and the projection; conv1_linear stays frozen.
- The SLAKE recipes set vision_processor from MUSE_SPARK_VISION_PROCESSOR_KWARGS.
- Validation loss on the English validation split runs at step 1 and every 10 steps, through the training data path with validation.json as the source. Steps cover each rank's share once: at DP 8 each rank packs 25 to 32 validation microbatches (214 in total, counted on CPU with the recipe's data path on the released SLAKE split), so validation runs 32 steps, and ranks with fewer microbatches wrap around. A 27-step validation pass took about 27 s in job 2384192 (LoRA vision + decoder, 8 GB300), with memory at or below the training peak. The SLAKE root must hold validation.json.
- Metrics go to TensorBoard (event files under <dump folder>/tb), so runs can be compared and shared; the base 816B config exports nothing.
- max_images_per_microbatch comes from the shortest English SLAKE sample (219 tokens, measured with the recipe's data path). The SLAKE root defaults to ./assets/datasets/slake; the MUSE_SPARK_SLAKE_PATH env var overrides it.
- Training runs 60 steps, about 2 passes over the English train split (one pass is 28.7 steps after packing). A 90-step LoRA vision + decoder run with validation every 10 steps on the English validation split (job 2384192, 8 GB300, no checkpoint saved) had validation loss 3.22 at step 1, 0.107 at step 30, 0.063 at step 60 (lowest) and 0.072 at step 90, while training loss kept falling. The LoRA decoder variant uses the same count without a separate measurement. Learning rates are untuned starting points.
- Both recipes target 8 GB300 GPUs: dp_shard=8, EP=8 (256 experts / 8), TP=CP=PP=1, no sequence parallel. They keep dtype=float32, so the frozen base is stored in bf16 (frozen params use param_dtype storage) while adapters, grads and AdamW state stay fp32. seq_len is 4096 and a step is 32 x 4096 tokens, so each DP rank runs 4 accumulation microbatches of 4096 tokens. max_images_per_microbatch is 4096 // 219 = 18.
- Both use the GB300 settings of the UltraData LoRA recipe: BF16 Dist-MoE (inplace_wgrad_accum=False; activation slot 0.25, scratch 16.0), remat that saves the Dist-MoE save regions, local compile of the loss only, no fused-swiglu override, and 1800 s comm timeouts. Attention is flex with FA4 (BACKEND=FLASH); the UltraData recipe uses varlen with FA4. Dist-MoE and FA4 need SM100. CUDA graphs stay off.
- A comment cites the sizing: a fake-PG run of this layout and these settings (job 2368236, a recipe not in this PR, random init, forced balanced routing) used 254 GiB allocated / 261 GiB reserved of 276.6 GiB per GPU (steady-state max over steps 2-5); dp_shard=16 and EP=16 give more headroom.
- Mechanical: the UltraData LoRA recipe's GB300 setup (Dist-MoE runtime, remat, compile regions, comm timeouts, no override imports) and its Dist-MoE and LoRA transforms move into apply_gb300_lora_dist_moe(config, lora) in torchtitan_recipes/models/muse_spark.py, shared with the SLAKE recipes. The SLAKE module also reuses three helpers of that module, which become public: _muse_spark_816b_a42b -> muse_spark_816b_a42b (base 816B config; its docstring says it is not verified as a recipe on its own, since --config can select it), _muse_spark_mm_dataloader -> muse_spark_mm_dataloader, _use_flex_flash_attention -> use_flex_flash_attention. Their callers in muse_spark.py, torchtitan_recipes/tests/models/muse_spark.py and test_muse_spark.py are updated. The UltraData LoRA decoder target list becomes the public MUSE_SPARK_LORA_DECODER_TARGETS. The SLAKE optimizer is a local copy of the UltraData LoRA optimizer with 10 warmup steps. The UltraData config and the other Muse Spark recipes are unchanged (--print-config compared before and after, ignoring function object addresses).
- torchtitan_recipes/README.md lists sft/ and torchtitan_recipes.sft.slake.
## User-facing changes
| Before | After |
| --- | --- |
| No SLAKE recipes | torchtitan_recipes.sft.slake: muse_spark_816b_a42b_slake_{lora_decoder,lora_vision_decoder}_sft |
| - | SLAKE recipes: dp_shard=8, EP=8 on 8 GB300, BF16 Dist-MoE, FA4, validation, TensorBoard |
| torchtitan_recipes.models.muse_spark: _muse_spark_816b_a42b, _muse_spark_mm_dataloader, _use_flex_flash_attention | muse_spark_816b_a42b, muse_spark_mm_dataloader, use_flex_flash_attention, apply_gb300_lora_dist_moe, MUSE_SPARK_LORA_DECODER_TARGETS |
## Numerics
No change to existing recipes: the UltraData LoRA config and the other Muse Spark recipes are identical before and after (--print-config compared, ignoring function object addresses). The SLAKE recipes are new and have no baseline; they were sized with fake PG. LoRA vision + decoder at this commit's settings ran 60 steps on 8 GB300 from the released HF checkpoint (job 2385319, 27 validation steps): validation loss 3.23 at step 1, 0.104 at step 30 and 0.066 at step 60; peak 261.6 GiB of 276.6 GiB; 12.2 s per step; no NaN or recompile. LoRA decoder at this commit's settings ran 60 steps on 8 GB300 (job 2526740, 32 validation steps): validation loss 3.23 at step 1, 0.101 at step 30 and 0.071 at step 60; training loss 3.239 -> 0.081; peak 259.4 GiB; 9.35 s per step; no NaN or OOM.
## Testing
- CPU test (tests/unit_tests/cpu/recipes/test_slake.py): both recipes' LoRA transforms build the expected trainable split on debugmodel_mm, and the adapted decoder modules are exactly MUSE_SPARK_LORA_DECODER_TARGETS. It catches a renamed module, since LoRA only warns on unmatched targets.
- `python -m torchtitan.train --module torchtitan_recipes.sft.slake --config <recipe> --print-config` passes for both SLAKE recipes (config __post_init__ validation included); their validator runs 32 steps. Their processor is MultiModalChatProcessor.Config, and their vision_processor has the Spark patch size and LANCZOS.
- CPU tests at this commit: components/data, components/test_renderer.py, models/muse_spark, models/muse_glimmer, config and recipes, 667 passed, 1 skipped, 3 xfailed; RL CPU tests 534 passed, 9 skipped (test_dapo_math and test_vllm_wrapper skipped: attn_gym.mla is not installed locally).
## Known issues / follow-ups
- TODO in code: drop train rows whose image is a duplicate or an adjacent slice of a validation or test image (same scan series), so test cases do not leak into training.
stack-info: PR: #5895, branch: fegin/stack/24
Stacked PRs:
[recipes] Muse Spark SLAKE LoRA SFT recipes: LoRA decoder, LoRA vision + decoder
Summary (human-written)
LoRA recipes for Muse Spark Open to train SLAKE dataset.
Why
There is no recipe to fine-tune Muse Spark 816B-A42B_mm on medical VQA. SLAKE is small (4,919 English train samples), so LoRA is enough; full fine-tuning would overfit and needs many more GPUs. The SLAKE ablation compares LoRA on the decoder with LoRA on vision + decoder.
Example.
What changed
User-facing changes
Numerics
No change to existing recipes: the UltraData LoRA config and the other Muse Spark recipes are identical before and after (--print-config compared, ignoring function object addresses). The SLAKE recipes are new and have no baseline; they were sized with fake PG. LoRA vision + decoder at this commit's settings ran 60 steps on 8 GB300 from the released HF checkpoint (job 2385319, 27 validation steps): validation loss 3.23 at step 1, 0.104 at step 30 and 0.066 at step 60; peak 261.6 GiB of 276.6 GiB; 12.2 s per step; no NaN or recompile. LoRA decoder at this commit's settings ran 60 steps on 8 GB300 (job 2526740, 32 validation steps): validation loss 3.23 at step 1, 0.101 at step 30 and 0.071 at step 60; training loss 3.239 -> 0.081; peak 259.4 GiB; 9.35 s per step; no NaN or OOM.
Testing
python -m torchtitan.train --module torchtitan_recipes.sft.slake --config <recipe> --print-configpasses for both SLAKE recipes (config post_init validation included); their validator runs 32 steps. Their processor is MultiModalChatProcessor.Config, and their vision_processor has the Spark patch size and LANCZOS.Known issues / follow-ups