Repository navigation
torchrun: plain Trainer DDP find_unused default, FSDP2-collective SentenceTransformer save - #15324
Merged
Merged
Conversation
…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.
Member
Author
|
@codex 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. |
…figs (cross-attention layers skipped without images) [skip ci]
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 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". |
shimmyshimmer
pushed a commit
to shimmyshimmer/unsloth-staging-4
that referenced
this pull request
Oct 26, 2026
… torchrun) (unslothai#15359) Targets main (follows unslothai#15324, merged as e0a8f07). ## Problem `torchrun --nproc-per-node 2` on the DeepSeek-OCR notebook fails on the first backward, on main and on unslothai#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 (unslothai#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 unslothai#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 | unslothai#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 unslothai#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. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Two fixes so unmodified notebook scripts run under
torchrun --nproc-per-node 2(Kaggle T4x2).1. Plain
transformers.Trainerunder DDP: "marked as ready twice"Orpheus TTS (and the other notebooks that train a LoRA model with the plain
Trainer) failed on the first backward under DDP:Cause:
ddp_find_unused_parametersis None, the model is aPeftModel(not aPreTrainedModel), so transformers passesfind_unused_parameters=Trueto DDP. With reentrant gradient checkpointing the checkpointed forward runs without grad, DDP marks every LoRA weight unused, then the recompute marks them again. Unsloth already picksFalsefor this case (unsloth_default_ddp_find_unused_parametersin_ddp_defaults.py), but only the generated TRL trainers call it (rl.py), not the patchedTrainer.__init__.Fix: the patched
Trainer.__init__(_utils.py) calls the same default before the original__init__, so plainTrainer,Seq2SeqTrainerand any other subclass get it. It runs before__init__because transformers 5 builds the DDP kwargs inside__init__(4.x builds them in_wrap_model). The helper is unchanged: it only fills a value the user left as None, only under a distributed launch with gradient checkpointing on, and only for a single plain LoRA adapter on a decoder-only causal LM (MoE, towers,modules_to_save, embedding / lm_head adapters, encoder-decoder models are left to transformers). An explicitddp_find_unused_parametersis kept. TRL trainers call it twice now; the second call re-decides to the same value.2.
FastSentenceTransformersave_pretrainedunder native FSDP2With
UNSLOTH_FSDP2=1 torchrun, the sentence-transformer notebooks trained fine but crashed inmodel.save_pretrained(...):Cause:
SentenceTransformer.savereads the DTensor shards directly (through the Transformer module andPeftModel.save_pretrained), on every rank, into the same folder. The causal LM saves are collective (_fsdp2_collective_save/fsdp2_gathered), the sentence-transformer save was not.Fix (
sentence_transformer.py):FastSentenceTransformer.from_pretrained/get_peft_modelwrapSentenceTransformer.save(behindsave_pretrainedandSentenceTransformerTrainer._save) once. For a model FSDP2 does not shard it is a pass-through. For a sharded one every rank calls it,fsdp2_gatheredgathers the weights to rank 0, rank 0 writes, the other ranks return None and wait for the write. Two details keep the folder identical to a one-process save:model.encode, and a forward of a sharded model is collective. It is now run on every rank before the gather (whole weights vianative_fsdp2_unsharded, since older sentence-transformers'encodecallsself.forwardand skips the root unit's hooks), and the writer's card reuses the result. Without this, sentence-transformers 6.x hangs in the save (rank 0 alone in an all-gather), and 5.x writes a card without the similarity output.FSDP<Name>classes are named as their plain classes while rank 0 writes.The native FSDP2
Trainer.save_modelhook (fsdp2_native.py) gathers for a SentenceTransformer too (its trainer's_saveignores astate_dictand callssave_pretrained), so checkpoints andtrainer.save_model()write the same files.save.pyis not touched.Tests
New CPU tests, 2 gloo ranks, tiny random models built in the test:
tests/python/test_plain_trainer_ddp_gc.py: LoRA Llama with reentrant checkpointing armed on the model, plainTrainerandSeq2SeqTrainer, 2 steps under DDP. Head: trains, DDP built withfind_unused_parameters=False, both ranks log the same losses. An explicitddp_find_unused_parameters=Trueis kept (and still fails, as before).tests/python/test_sentence_transformer_fsdp2_save.py: BERT LoRA SentenceTransformer sharded with native FSDP2, forward and backward, thensave_pretrainedon both ranks andTrainer.save_modelthrough the native hook. Both folders equal a one-process save byte for byte (adapter, configs, tokenizer, README with the usage snippet output); rank 1 returns None; the shards are restored afterwards.ddp_find_unused_parameters=TruekeptExisting related tests pass on head:
test_ddp_find_unused_default.py,test_ddp_comm_defaults.py,test_fsdp2_native_trainer_ckpt_gloo.py,test_fsdp2_native_trainer_init_any_loader_gloo.py,test_cold_import_order.py,test_st_save_merged_signature.py,test_st_modules_json_trust_gate.py,tests/python/test_sentence_transformer_ddp_gc.py.GPU: the notebooks'
python_scriptson Kaggle T4x2 (torch 2.9.0, transformers 4.57.6, TRL 0.22.2, sentence-transformers 6.2.0),max_steps = 3, same zoo for both arms:trainer.train()(marked as ready twice)model.save_pretrained(invalid python storage)Not covered
find_unused_parameters=Trueand were not run under DDP here.SentenceTransformer.push_to_hub,save_pretrained_merged, GGUF and torchao exports under FSDP2 are unchanged by this PR.