Skip to content

Fix VLM + DDP checkpointing - #3751

Merged
danielhanchen merged 1 commit into
unslothai:mainfrom
djsaunde:ddp2
Dec 20, 2025
Merged

danielhanchen merged 1 commit into
unslothai:mainfrom
djsaunde:ddp2

Conversation

@djsaunde

@djsaunde djsaunde commented Dec 18, 2025 •

Copy link
Copy Markdown
Contributor

Closes #3713.

Unfortunately, this makes DDP training somewhat slower then expected for VLM models. I see this as a kind of short-term fix; we should try to really root cause this so we can still use our gradient checkpointing impl.

Searching online, I see a few different training libs had also run into this problem, and the fix was to fallback to use_reentrant=False checkpointing.

See the linked issue for more details.

@djsaunde djsaunde self-assigned this Dec 18, 2025
@djsaunde djsaunde changed the title Fix VLM DDP checkpointing Fix VLM + DDP checkpointing Dec 18, 2025
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @djsaunde, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a critical stability issue in Vision-Language Models (VLMs) when trained with Distributed Data Parallel (DDP) by modifying how gradient checkpointing is handled. It specifically disables re-entrant checkpointing in DDP environments to prevent errors, ensuring that training can proceed without interruption. This change involves adapting both Unsloth's internal checkpointing mechanisms and external PyTorch/Hugging Face utilities to operate in a non-reentrant mode when DDP is active, providing a functional solution for VLM DDP training.

Highlights

  • DDP Checkpointing Fix: Implemented a fix for Vision-Language Models (VLMs) encountering 'marked ready twice' errors during Distributed Data Parallel (DDP) training, which was caused by re-entrant gradient checkpointing.
  • Conditional Re-entrant Checkpointing: The system now dynamically detects if DDP is active and, if so, disables re-entrant gradient checkpointing by unpatching Unsloth's custom implementations and forcing PyTorch's and Hugging Face's checkpointing functions to use use_reentrant=False.
  • Performance Trade-off: While resolving the DDP stability issue, this change is noted as a short-term fix that may lead to slower DDP training for VLM models, with a future goal to root cause the underlying performance degradation.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request addresses a checkpointing issue with Vision Language Models (VLMs) under Distributed Data Parallel (DDP) by disabling re-entrant gradient checkpointing. The approach involves monkey-patching torch.utils.checkpoint.checkpoint and transformers.modeling_utils.checkpoint to force use_reentrant=False when in a distributed environment.

My review focuses on the implementation of this monkey-patching. I've identified a potential bug where the checkpointing function could be wrapped multiple times if the patching code is executed more than once, and I've provided a suggestion to prevent this. I also raised a concern about the global nature of the patch and suggested considering a more scoped approach or providing a way to revert the patch in a future, more permanent solution.

Comment thread unsloth/models/vision.py Resolved
Comment thread unsloth/models/vision.py Resolved
@danielhanchen
danielhanchen merged commit 10137f1 into unslothai:main Dec 20, 2025
nepfaff added a commit to nepfaff/unsloth that referenced this pull request Feb 17, 2026
Improves the existing DDP compatibility block (from PR unslothai#3751) with two
targeted fixes that preserve Unsloth's memory optimizations:

1. Non-reentrant checkpointing with CPU activation offloading via
   saved_tensors_hooks. PR unslothai#3751 switched to non-reentrant but dropped
   CPU offloading entirely, increasing memory by ~10 GiB.

2. DDP-safe TiledMLP backward: uses functional torch.autograd.grad()
   for all-but-last sequence chunk (no DDP hooks fired), then
   .backward() for the final chunk (fires hooks exactly once).

Both fixes are gated behind is_distributed() — single-GPU training
is completely unaffected.

Tested on Qwen3-VL-4B + LoRA with 8x L40S GPUs:
- 128K tokens: 31.0 GiB peak, 300s/step (was OOM without these fixes)
- 64K tokens: 33.8 GiB peak, 171s/step
- 32K tokens: 24.8 GiB peak, 69s/step

Fixes unslothai#3713

Co-Authored-By: Claude Opus 4.6 <[email protected]>
abiswas-realadvice pushed a commit to abiswas-realadvice/unsloth that referenced this pull request May 14, 2026
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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] DDP with Qwen2.5VL 7B

2 participants