Repository navigation
Fix DDP "marked ready twice" for VLMs with CPU offload + TiledMLP - #4240
Conversation
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
# Conflicts: # unsloth/models/vision.py
TiledMLP now takes its trainable params as autograd inputs under DDP, so each param is accumulated once per backward: fixes silently wrong all-reduced grads (default DDP) and marked-ready-twice (find_unused_parameters), for both the FastLanguageModel and FastModel loaders. The non-reentrant checkpoint wrapper is now bound on the modules themselves (prepare_model_for_training binds torch's checkpoint as a default argument, bypassing it), and only offloads activations for use_gradient_checkpointing='unsloth'.
|
@codex review |
|
@codex security review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b4186adfca
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for i, g in enumerate(grads[1:]): | ||
| if g is not None: | ||
| param_grads[i] = g if param_grads[i] is None else param_grads[i].add_(g) |
There was a problem hiding this comment.
Materialize zero gradients for unused tiled parameters
When a patched sparse MoE block has a trainable expert that receives no tokens on a rank, autograd.grad(..., allow_unused=True) returns None for that expert and this branch leaves its returned gradient as None. Because every parameter was nevertheless exposed as an input edge of _TiledMLPWithParams, DDP's unused-parameter traversal considers it reachable, but its accumulation hook never fires; the reducer can then hang or report an unfinished reduction, and it also cannot all-reduce another rank's nonzero expert gradient into this rank. This affects the .block_sparse_moe and NemotronHMOE modules that patch_tiled_mlp explicitly targets, so unused entries need zero gradients rather than None.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reproduced: a 2-rank gloo DDP run where a trainable expert only gets tokens on rank 1 completes 3 steps with both default DDP and find_unused_parameters=True, no hang or unfinished-reduction error, and both ranks end with the same all-reduced expert grad (norm 61.22351). A None grad returned from the Function still reaches the leaf's accumulation node, so DDP's hook fires.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
| def ddp_grads(tmp_path_factory): | ||
| ctx = mp.get_context("spawn") | ||
| queue = ctx.Queue() | ||
| init_file = tempfile.mktemp(dir = tmp_path_factory.mktemp("ddp")) |
…DP for encoder models (unslothai#13639) Fixes unslothai#4680 for the encoder models. Multi-GPU (torchrun / DDP) LoRA training of an MPNet embedding model such as `unsloth/all-mpnet-base-v2` with gradient checkpointing crashes on the first backward: ``` RuntimeError: Expected to mark a variable ready only once. ... 2) Reused parameters in multiple reentrant backward passes. ``` `FastSentenceTransformer` loads BERT-family models (`ENCODER_MODEL_TYPES`) through its own fast encoder route, which never reaches the FastModel DDP handling from unslothai#3751 / unslothai#4240. Two spots there pick reentrant checkpointing: - the patched MPNet encoder hard-codes `use_reentrant=True` - `gradient_checkpointing_enable()` is called with no kwargs, which is reentrant on transformers 4.57.x (`{"use_reentrant": True}`) and non-reentrant on 5.x Reentrant checkpointing runs one backward per checkpointed layer call. Sentence-transformers losses such as MultipleNegativesRankingLoss call the model once per text column, so each LoRA weight's DDP hook fires more than once per step and DDP raises. Setting `ddp_find_unused_parameters=False` by hand does not help. ## Change Under DDP only (`is_distributed()`, the same check the FastModel route uses), the fast encoder route now uses non-reentrant checkpointing: the MPNet patch takes `use_reentrant=False`, and `gradient_checkpointing_enable` gets `{"use_reentrant": False}`. On one GPU nothing changes: MPNet keeps `use_reentrant=True` and `gradient_checkpointing_enable()` is still called without kwargs, so the transformers default stays. EmbeddingGemma, Qwen3-Embedding and other decoder-based embedders go through FastModel and were already fixed by unslothai#4240 (released in 2026.10.4). ## Evidence 2x B200, torchrun, NCCL, transformers 5.17.0, sentence-transformers 6.1.0, MultipleNegativesRankingLoss, `use_gradient_checkpointing=True`, `ddp_find_unused_parameters` unset: | model | main | this PR | |---|---|---| | all-mpnet-base-v2 | crash at step 0 | 6 steps OK (twice) | | all-MiniLM-L6-v2 | 6 steps OK | 6 steps OK | | embeddinggemma-300m, `"unsloth"` GC | 6 steps OK | 6 steps OK, losses bit-identical to main | Single GPU, same scripts: mpnet and MiniLM losses and grad norms stay within the main vs main run-to-run spread (step 1 loss identical; grad norm spread 2.398 to 2.433 on main, 2.536 on this PR for mpnet step 1, step 6 loss 0.5583 / 0.5592 main vs 0.5561 here); EmbeddingGemma is bit-identical. `tests/python/test_sentence_transformer_ddp_gc.py` runs two gloo ranks on CPU through `get_peft_model` with a tiny MPNet and a tiny BERT, calling the model twice per step like MultipleNegativesRankingLoss, plus a single-process check that MPNet keeps reentrant checkpointing without DDP and switches with `WORLD_SIZE=2`: | test | main | this PR | |---|---|---| | DDP mpnet, transformers 5.17 | fails (marked ready twice) | passes | | DDP bert, transformers 5.17 | passes | passes | | DDP mpnet, transformers 4.57.6 | fails (rank hangs after the other raised) | passes | | DDP bert, transformers 4.57.6 | fails (rank hangs after the other raised) | passes | | one process, mpnet reentrant | passes | passes | | `WORLD_SIZE=2`, mpnet non-reentrant | fails | passes | Kaggle 2x T4 (NCCL), all-mpnet-base-v2 with gradient checkpointing: crashes on main (marked ready twice), trains on this PR. Not covered: 4-bit encoders (`load_in_4bit=True`) with gradient checkpointing under DDP still crash, since `prepare_model_for_kbit_training` forces reentrant checkpointing in unsloth-zoo; 4-bit is off by default for encoders.
Replacement for #4077 due to Studio rebasing. Rebased onto current main (merge commit, no force push).
Multi-GPU (DDP) training of vision models had three problems under
is_distributed():.backward()per sequence chunk, so DDP's gradient hooks fired once per chunk. With the default DDP settings this silently all-reduced only part of the MLP LoRA gradient; withfind_unused_parameters=Trueit raised "marked ready twice". TiledMLP now passes its trainable parameters to autograd as inputs and returns their summed gradients, so each parameter is accumulated exactly once. The patch is applied from both loaders (FastLanguageModelandFastModel) whenever TiledMLP is enabled under DDP; single GPU runs keep the stock TiledMLP.prepare_model_for_trainingcalls_set_gradient_checkpointing(), which binds torch'scheckpointas a default argument, so decoder layers kept running re-entrant checkpointing (which also breaksfind_unused_parameters=True). The wrapper is now bound on the modules directly (Gemma3n / Gemma4 keep their forced re-entrant path).use_gradient_checkpointing="unsloth"the wrapper now offloads the checkpointed layer inputs to CPU throughsaved_tensors_hooks(activations only, not masks or rotary tables).Results
2 rank gloo DDP, CPU, stock vs this PR, max abs gradient error vs an untiled single process reference over 3 steps (
tests/test_tiled_mlp_ddp.py):Unsloth
FastVisionModel+ LoRA, 2 rank DDP, tiny Qwen2.5-VL, 3 steps:Qwen2.5-VL-3B, seq 8192, 2 rank DDP,
use_gradient_checkpointing="unsloth": peak memory 10.21 GB before, 9.17 GB after (offload active, 108 offloaded layer inputs over 3 steps), 8.53 GB with TiledMLP; step 1 loss 12.8355 and grad norm 2.734 on both sides without TiledMLP.