Skip to content

Block compile: keep each compiled block whole under DDP (DeepSeek-OCR torchrun) - #15359

Merged
danielhanchen merged 9 commits into
mainfrom
dh/s7-plain-trainer-ddp-more
Oct 26, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
dh/s7-plain-trainer-ddp-more

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Targets main (follows #15324, merged as e0a8f07).

Problem

torchrun --nproc-per-node 2 on the DeepSeek-OCR notebook fails on the first backward, on main and on #15324 alike:

torch.utils.checkpoint.CheckpointError: torch.utils.checkpoint: A different number of tensors was saved during the original forward and recomputation.
Number of tensors saved during forward: 50
Number of tensors saved during recomputation: 49.

One GPU and UNSLOTH_FSDP2=1 train fine.

Cause

Under DDP, Unsloth checkpoints VLMs non-reentrantly (vision.py, vlm_gradient_checkpointing_reentrant()), and every decoder block is compiled as one region (_block_compile.py). When a block is called inside DDP.forward, dynamo hands its graph to DDPOptimizer (torch._dynamo.config.optimize_ddp), which splits it at gradient bucket boundaries. The checkpoint recompute runs from backward, outside DDP.forward, where dynamo compiles without DDPOptimizer. A block compiled whole in the recompute does not save the same tensors as the split forward, so the checkpoint's count check fails.

Evidence on one Kaggle T4x2 kernel, same script, same install: default fails as above; torch._dynamo.config.optimize_ddp = False before trainer.train() trains (losses 3.3576, 3.7844, 3.9564); UNSLOTH_BLOCK_COMPILE=0 also trains. Forcing non-reentrant checkpointing in a single process trains, so the split is the DDP-only ingredient.

Fix

_block_compile.py: while a DDP module is active and optimize_ddp is on, the block call runs under torch._dynamo.config.patch(optimize_ddp = False). Each block is already its own compiled region, so its gradients still reach DDP's buckets block by block. Nothing changes for a single process, FSDP2, a user's own torch.compile of the DDP module, or the global setting.

Tests

tests/python/test_block_compile_ddp_no_split.py: two CPU gloo ranks, a Llama with layers above DDP's 1 MB first bucket, block compile installed, non-reentrant checkpointing, DDP with find_unused_parameters=True and bucket_cap_mb=1. It counts DDPOptimizer calls on decoder block graphs, checks every layer ran its compiled region and that both ranks hold the same gradients.

tree result
main before this change (#15324 head 31c6353) fails: one DDPOptimizer split per block graph ([70])
this branch passes (torch 2.13.0 and 2.10.0)

tests/test_block_compile.py: same results as on #15324 (43 passed, 6 skipped; test_sm_count_is_read_outside_the_trace fails on both trees).

Notebook runs (Kaggle T4x2, torch 2.9.0, transformers 4.57.6, 3 steps)

notebook mode #15324 head this branch
Deepseek_OCR_(3B) single GPU trains trains (first two losses equal to main, third within 1e-3; main against itself varies by 3e-4)
Deepseek_OCR_(3B) DDP 2 ranks CheckpointError 50 vs 49 trains, 3 steps
Deepseek_OCR_(3B) FSDP2 2 ranks trains trains
Llasa_TTS_(1B), Whisper, Sesame_CSM_(1B), Spark_TTS_(0_5B), bert_classification DDP 2 ranks trains trains (Llasa, CSM, Spark losses bitwise equal to #15324; Whisper within 4e-4; bert's notebook split is unseeded)

Not fixed here

  • DeepSeek-OCR-2 under DDP still fails after this change, now with Recomputed values for the following tensors have different metadata (a [2, 287, 10, 128] tensor saved, [2, 10, 287, 128] recomputed). It reproduces in one process when non-reentrant checkpointing is forced, and UNSLOTH_BLOCK_COMPILE=0 trains, so it is a block compile plus non-reentrant checkpoint issue of its own. Workaround until then: UNSLOTH_BLOCK_COMPILE=0 under torchrun.
  • Multi-node and non-T4 GPUs were not run.

danielhanchen and others added 6 commits October 25, 2026 22:10
…tenceTransformer save

Plain transformers Trainer (and Seq2SeqTrainer, other subclasses) now gets the same
DDP find_unused_parameters default the generated TRL trainers already apply, before
Trainer.__init__ builds the DDP kwargs. A LoRA model with reentrant gradient
checkpointing no longer fails the first backward with "marked as ready twice".
An explicit ddp_find_unused_parameters is kept.

SentenceTransformer.save is collective under native FSDP2: every rank calls it, the
shards are gathered to rank 0, which writes; the other ranks return None. The native
Trainer.save_model hook gathers for a SentenceTransformer too. The saved folder equals
a one-process save byte for byte.
…figs (cross-attention layers skipped without images)

[skip ci]
Inside DDP.forward dynamo hands each compiled decoder block to DDPOptimizer, which
splits it at gradient bucket boundaries. Under DDP Unsloth checkpoints VLMs
non-reentrantly, and the recompute runs from backward outside DDP.forward, so a
block compiled there is whole and saves a different number of tensors than its
split forward. DeepSeek-OCR and DeepSeek-OCR-2 under torchrun on 2 GPUs failed the
first backward with 'A different number of tensors was saved during the original
forward and recomputation' (50 vs 49). The block call now runs with optimize_ddp
off while a DDP module is active; single process, FSDP2 and the global setting are
unchanged.
…dp-more

# Conflicts:
#	unsloth/models/_utils.py
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-10-26T12:27:18.662339Z 27469ea 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: cba60a77aa

ℹ️ 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

Copy link
Copy Markdown
Member Author

Follow-up from a deeper check (CPU gloo, 2 ranks, torch 2.6 / 2.10 / 2.13 / 2.14): the crash needs the checkpoint recompute to recompile rather than reuse the forward's cached block graph; forcing that miss reproduces CheckpointError: ... Number of tensors saved during forward: 27 / recomputation: 25 on main and trains on this branch. 27469ea adds that forced-recompile case as a regression test (skipped below torch 2.7, where block compile is off) and narrows the check to the mode that actually splits graphs (get_optimize_ddp_mode() == "ddp_optimizer"), importing DDP once instead of per call. Single process, FSDP2 and no-DDP never enter the patch (0 of 12 calls); DDP losses and grads are bit-identical to main with 0 recompiles. A user torch.compile of the DDP model also benefits (blocks stay whole, the forced crash is fixed there too).

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 27469ea553

ℹ️ 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 839b06f into main Oct 26, 2026
3 of 30 checks passed
@danielhanchen
danielhanchen deleted the dh/s7-plain-trainer-ddp-more branch October 26, 2026 12:44
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.

1 participant