Repository navigation
DDP: find_unused_parameters off when only embed_tokens / lm_head train beside LoRA (CPT notebooks crashed under DDP) - #18036
Merged
Conversation
…ead train Continued pretraining and text completion notebooks train embed_tokens and lm_head through modules_to_save. The DDP default helper left ddp_find_unused_parameters at None for any modules_to_save, so transformers passed find_unused_parameters=True to DDP. Under Unsloth's reentrant gradient checkpointing that marks every LoRA weight unused after the no-grad forward, then the recompute marks it ready again: the first backward raised "Expected to mark a variable ready only once". The trainable copies of the input and output embeddings run outside the checkpointed layers on every forward, so they always receive a gradient and False is safe. Other modules_to_save, LoRA on the head or embedding, MoE and VLM towers keep the previous default.
Member
Author
|
@codex review |
Codex Review Summary: ✅ CompletedThis 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. |
|
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". |
…ezvous) [skip ci]
danielhanchen
added a commit
that referenced
this pull request
Nov 17, 2026
…red since #18036) (#18072) ## Summary `Repo tests (CPU, rest-2)` fails on main since #18036 (seen on #18045, on `0d4793e1`): ``` tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding AssertionError: 1 file reads in the test trees touch a checked-in file with the platform default encoding, ... 'tests/_ddp_trainable_embeddings_worker.py:81: open()' ``` #18036 added `tests/_ddp_trainable_embeddings_worker.py`, which writes each rank's result JSON with `open(path, "w")`, so it uses the platform default encoding (cp1252 on Windows). The repo-wide guard requires every `open()` in the test trees to name an encoding. The DDP change itself is fine; only the new helper missed the convention. The guard is doing its job. ## Change - `tests/_ddp_trainable_embeddings_worker.py`: the result file is written with `encoding = "utf-8"`. - `tests/test_ddp_find_unused_default.py`: the two `read_text()` calls that read those files back pass `encoding = "utf-8"` too, so the writer and the reader agree on every platform. ## Verification - `tests/test_source_read_encoding.py -k checked_in_file_reads`: fails on main with the line above, passes with this change.
shimmyshimmer
pushed a commit
to shimmyshimmer/unsloth-staging-4
that referenced
this pull request
Nov 17, 2026
…on every GPU, else native FSDP2 (unslothai#18061) ### Problem Multi-GPU launches pick DDP or FSDP2 by hand (`UNSLOTH_FSDP2=1`, `UNSLOTH_PARALLEL="fsdp=1"`). The generated launcher defaults to FSDP2 everywhere, but the M2 notebook sweep on Kaggle 2x T4 (same scripts run under DDP and FSDP2) shows FSDP2 is often the slower and heavier choice when the model already fits on one GPU: - 33 real-size cells passed in both modes and logged throughput. DDP over FSDP2 steady tokens/s: median 1.03x, DDP at least 0.98x in 28 of 33. The biggest wins are all vision or long-sequence: Qwen3_5_(4B)_Vision 1.97x, Qwen2.5_(7B)-Alpaca 1.83x, LFM2.5_(1.2B)-Translation 1.64x, Qwen2_VL_(7B) 1.56x, Qwen2.5_VL_(7B) 1.48x, Qwen3_VL_(8B) 1.39x. - Peak memory: 45 real-size cells passed in both modes, and DDP used less in 28 of them. In the vision runs FSDP2 peaked 3 to 6 GB higher: Qwen3_VL_(8B)-Vision-GRPO 8.7 vs 14.9 GB, Pixtral_(12B) 10.3 vs 14.4 GB, Qwen3_5_(4B)_Vision 10.2 vs 14.2 GB. - Mistral_Nemo_(12B)-Alpaca passes under DDP (9.7 GB peak). FSDP2 runs out of memory when it unshards the whole model for generate after training. - DDP never ran out of memory in a cell where FSDP2 passed. The one OOM under DDP (Qwen3_Embedding_(0_6B), batch 256 per device) also OOMs under FSDP2. FSDP2 still matters when the weights plus training state do not fit on one card, for example 16-bit LoRA on an 8B model on a T4. ### Change `UNSLOTH_PARALLEL=auto` (opt-in) picks the data parallel mode by memory: - **When it decides:** once per process, at the first Unsloth `from_pretrained`. That is before any load-time code reads `UNSLOTH_FSDP2` (4-bit storage dtype, sharded loading, gradient checkpointing mode). If no Unsloth load ran, it decides at the first `Trainer` instead, using the model passed in. - **Fits** means weights + training state + activation margin <= what this rank's GPU can hold: - weights: the checkpoint's safetensors headers, no weights downloaded. Quantize-on-load counts the quantized linear weights at 4-bit / 8-bit size. - training state: per trainable parameter, the gradient, its DDP bucket copy and two AdamW moments. Before `get_peft_model`, LoRA is assumed at r=16 on every linear weight. - activation margin: 20% of the GPU. This is the activation share the device map planner (`loader_utils._plan_fits_first_device`) already keeps free. In M2, DDP's training peak above its post-setup reserved memory was 0.97 GB median and 3.04 GB p90, which is 21% of a T4. - **Ranks agree:** one `all_gather_object` across ranks. DDP is picked only if every rank fits; otherwise every rank takes FSDP2. Anything that cannot be sized also picks FSDP2, which is today's launcher default. - **Output:** the decision is written as `UNSLOTH_FSDP2=0` or `1`, so everything after it sees an ordinary explicit launch, and child processes inherit it. Rank 0 prints one line with the numbers and how to force the other mode. - **Precision:** sizing follows the loader's -bf16 rule (now one helper, `mapper.bf16_repo_loads_16bit`, used by the loader too). A `quantization_config` or `load_in_fp8` load is not sized and picks FSDP2. Each rank sizes its own GPU (`LOCAL_RANK`). - **Conservative by construction:** only loads the estimator models exactly are sized (16-bit LoRA, pre-quantized bitsandbytes, quantize-on-load with the loaders' skip lists, full finetuning with float32 master weights). Everything else (quantization_config, fp8, fast_inference, forced float32 or custom dtypes, unreadable configs) picks FSDP2 and the rank 0 line says why. - **Explicit layouts are unchanged.** `auto` combined with `UNSLOTH_FSDP2`, tp / pp / cp, or an `accelerate launch` FSDP config is refused with a message. `UNSLOTH_PARALLEL_AUTO_GB` overrides the per-rank budget. Header-only estimates against the M2 measured post-setup reserved memory (T4, 14.56 GB): | notebook model | estimated weights | M2 reserved at start | auto | |---|---|---|---| | Llama-3.1-8B, 4-bit | 5.80 GB | 5.74 GB | ddp | | gemma-2-9b, 4-bit | 6.25 GB | 5.93 GB | ddp | | Qwen2.5-VL-7B bnb-4bit | 6.90 GB | 6.70 GB | ddp | | Pixtral-12B, 4-bit | 8.70 GB | 8.75 GB | ddp | | Mistral-Nemo-12B, 4-bit | 8.46 GB | n/a (DDP peak 9.7 GB) | ddp | | Llama-3.1-8B, 16-bit LoRA | 16.06 GB | n/a | fsdp2 | | gemma-3-27b, 4-bit | 16.63 GB | n/a | fsdp2 | The launcher default stays FSDP2 for now. The M2 DDP crash with trainable embed_tokens / lm_head (Mistral CPT, Text_Completion) is fixed by unslothai#18036, and the Kaggle run below shows auto picking DDP there and training. The 27B / 30B 4-bit notebooks run out of memory at load under both modes, because each rank loads the whole 4-bit model. Auto picks FSDP2 there and changes nothing. ### Tests `tests/test_parallel_auto.py` (26 tests) runs on CPU. The gloo tests use a world of 2 and `trl-internal-testing/tiny-Qwen3ForCausalLM`. Each test takes under 10 s. - Parsing: `auto` parses; explicit layouts parse and translate as before; conflicting variables are refused; a child process inherits the decision. - Arithmetic: the decision and training-state formulas. Sizing: the tiny checkpoint's safetensors headers, 16-bit vs 4-bit on load. - Gloo, world 2: fits picks ddp (run through the real `from_pretrained` decorator); does not fit picks fsdp2; ranks disagree picks fsdp2 on every rank. The decision is made once. - End to end, through the real `_unsloth_trainer_init` source: a LoRA Trainer under auto trains exactly like the explicit layout it picked, for both DDP and FSDP2. Losses match, LoRA weights are bit-identical, and the run is wrapped in DDP or FSDP2 as expected. Flip check: - On origin/main all new tests fail. - With only `parallel_auto.py` copied in and none of the wiring, the 10 parsing / wiring / end-to-end tests still fail. - On this branch all 26 pass. The three review fixes (per-rank GPU sizing, Trainer wrapper installed while auto is unresolved, -bf16 / quantization_config sizing) each have a test that fails on the previous head and passes now. Existing suites (`test_parallel_env.py`, `test_parallel_capabilities_*.py`, `test_fsdp2_native_trainer_init_any_loader_gloo.py`, `test_fsdp2_native_trainer_args_gloo.py`) fail the same two tests before and after: `test_parallel_capabilities_latent_sinks.py`, a DeepseekV41 `_keep_in_fp32_modules` error with this transformers version. Nothing else fails. Kaggle 2x T4: `torchrun --nproc-per-node 2`, LoRA r=16, seq 512, batch 2 per GPU unless noted. Stack: this branch on unsloth main 9e27e6a, unsloth_zoo main, torch 2.14.1, transformers 5.17.0, trl 1.15.0. Peak is max reserved per GPU (rank 0 / rank 1). Each arm ran once, so the tok/s gap between auto and explicit is run-to-run noise, not a speedup. Losses match the explicit arm to 1e-4 in a and c (GPU reduction order) and exactly in b. | arm | layout | rank 0 decision | tok/s | peak GiB | losses (first, last) | |---|---|---|---|---|---| | a: Llama-3.1-8B-Instruct bnb-4bit, 10 steps | auto | DDP: weights 5.31 + state 0.54 + margin 2.91 GiB fits 14.43 GiB | 723 | 6.79 / 7.04 | 1.7930, 0.2772 | | | `fsdp=0` | | 677 | 6.79 / 7.04 | 1.7930, 0.2771 | | c: Mistral v0.3 7B bnb-4bit CPT, trainable embed_tokens + lm_head, 6 steps | auto | DDP: weights 3.85 + state 0.54 + margin 2.91 GiB fits 14.43 GiB | 601 | 11.00 / 11.29 | 0.8652, 0.6884 | | | `fsdp=0` | | 570 | 11.00 / 11.29 | 0.8652, 0.6884 | | b: Llama-3.1-8B-Instruct 16-bit, seq 256, batch 1, 10 steps | auto | FSDP2: needs 18.49 GiB (weights 14.96 + state 0.62 + margin 2.91) but has 14.43 GiB | 106 | 12.69 / 12.71 | 3.7241, 4.7500 | | | `dp=2,fsdp=1` | | 104 | 12.69 / 12.71 | 3.7241, 4.7500 | Every auto arm ended up wrapped the same way as its explicit arm: DDP in a and c, FSDP2 (32 LlamaDecoderLayer blocks + root) in b.
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.
Summary
Continued pretraining and text completion notebooks (for example
Mistral_v0.3_(7B)-CPTandMistral_(7B)-Text_Completion) crash under plain DDP (torchrun, 2 ranks,UNSLOTH_FSDP2=0) in the first backward:1 GPU and FSDP2 train fine.
Root cause
These notebooks pass
embed_tokensandlm_headintarget_modules, which Unsloth turns intomodules_to_save(full trainable copies).unsloth_default_ddp_find_unused_parametersinunsloth/models/_ddp_defaults.pysetsddp_find_unused_parameters = Falseonly for a plain LoRA adapter and left it atNonewhenevermodules_to_savewas set. transformers then passesfind_unused_parameters=Trueto DDP for every PEFT model.Under Unsloth's reentrant gradient checkpointing the checkpointed forward runs without grad, so DDP's unused-parameter search marks every LoRA weight inside the decoder layers as unused (ready) at the end of forward. The recompute in the checkpoint backward then fires their gradient hooks again, and DDP raises "mark a variable ready only once". This is the same failure the helper already prevents for plain LoRA.
Fix
The trainable copies of the input embedding and output head run outside the checkpointed layers on every forward, so they always receive a gradient.
Falseis therefore safe for them, exactly as for the LoRA weights. The helper now acceptsmodules_to_saveentries that name the input / output embeddings (resolved throughget_input_embeddings/get_output_embeddings, so aliases such aswtework), and admits theirmodules_to_savecopies parameter by parameter. Everything else keeps the previous default: othermodules_to_save(for examplenorm), LoRA onlm_headorembed_tokens, MoE, VLM towers, several adapters, non-LoRA PEFT. A classifier head inmodules_to_saveis now matched by name rather than by any.modules_to_save.parameter.1 GPU is unchanged (the helper only acts when distributed), and FSDP2 does not use this setting.
Tests
tests/test_ddp_find_unused_default.py: new cases formodules_to_saveof["embed_tokens", "lm_head"],["lm_head"],["embed_tokens"], and a classifier plusembed_tokens(all nowFalse), plus["lm_head", "norm"]and a classifier plusnorm(stillNone).test_trainable_embeddings_train_under_ddp_reentrant_checkpointing: two gloo ranks on CPU, tiny Llama with LoRA plus trainableembed_tokens/lm_head, reentrant checkpointing, DDP built the way the Trainer builds it. Losses and per-parameter gradient norms must match a single process on the full batch.tests/test_ddp_find_unused_default.py(63 tests)test_ddp_tower_sync,test_ddp_frozen_sync,test_block_swap_auto_ddp)Kaggle 2x T4 (torchrun,
UNSLOTH_FSDP2=0, notebooks shrunk to 4 optimizer steps)unsloth
b2ad0b4and unsloth-zoo73ee2bd(main), torch 2.14.1, transformers 5.17.0, TRL 1.15.0, PEFT 0.21.3. The head arm is the same install with this change's_ddp_defaults.pycopied over.Mistral_(7B)-Text_CompletionMistral_v0.3_(7B)-CPT, continued pretraining (embed_tokens + lm_head)Mistral_v0.3_(7B)-CPT, instruction stageOn the fp16 skips: under DDP each rank backpropagates the full per-token loss scaled by the world size, so its scaled gradients are about twice as large as one gradient accumulation micro step on 1 GPU and overflow at a different step. Before the first skip the runs match.