Skip to content

Fix DDP "marked ready twice" for VLMs with CPU offload + TiledMLP - #4240

Merged
danielhanchen merged 8 commits into
mainfrom
dh/recover-4077-ddp-vlm-tiled-mlp
Sep 29, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
dh/recover-4077-ddp-vlm-tiled-mlp

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Mar 12, 2026 •

Copy link
Copy Markdown
Member

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():

  1. TiledMLP gradients were wrong or crashed. TiledMLP ran a nested .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; with find_unused_parameters=True it 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 (FastLanguageModel and FastModel) whenever TiledMLP is enabled under DDP; single GPU runs keep the stock TiledMLP.
  2. The non-reentrant checkpoint wrapper from Fix VLM + DDP checkpointing #3751 was never used. prepare_model_for_training calls _set_gradient_checkpointing(), which binds torch's checkpoint as a default argument, so decoder layers kept running re-entrant checkpointing (which also breaks find_unused_parameters=True). The wrapper is now bound on the modules directly (Gemma3n / Gemma4 keep their forced re-entrant path).
  3. CPU activation offload was dropped under DDP. With use_gradient_checkpointing="unsloth" the wrapper now offloads the checkpointed layer inputs to CPU through saved_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):

DDP mode before after
default 5.2e+01 (wrong grads) 1.5e-05
find_unused_parameters marked ready twice 1.5e-05
static_graph 1.5e-05 1.5e-05
gradient_as_bucket_view 5.2e+01 (wrong grads) 1.5e-05

Unsloth FastVisionModel + LoRA, 2 rank DDP, tiny Qwen2.5-VL, 3 steps:

TiledMLP find_unused before after
off False OK OK, grad norm identical
off True marked ready twice OK
on False marked ready twice OK, grad norm matches single process reference
on True marked ready twice OK

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.

gemini-code-assist[bot]

This comment was marked as outdated.

# 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'.
@unslothai unslothai deleted a comment from nidhishgajjar Sep 29, 2026
@unslothai unslothai deleted a comment from nidhishgajjar Sep 29, 2026
@unslothai unslothai deleted a comment from gemini-code-assist Bot Sep 29, 2026
@unslothai unslothai deleted a comment from gemini-code-assist Bot Sep 29, 2026
@unslothai unslothai deleted a comment from gemini-code-assist Bot Sep 29, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-29T13:58:20.813572Z b4186ad Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +57 to +59
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

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".

@danielhanchen
danielhanchen merged commit 46764a6 into main Sep 29, 2026
20 of 25 checks passed
@danielhanchen
danielhanchen deleted the dh/recover-4077-ddp-vlm-tiled-mlp branch September 29, 2026 15:47
def ddp_grads(tmp_path_factory):
ctx = mp.get_context("spawn")
queue = ctx.Queue()
init_file = tempfile.mktemp(dir = tmp_path_factory.mktemp("ddp"))
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Oct 22, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

edge case# non-studio# still-needed# Stale but the problem is still present on main; review it

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants