Repository navigation
DeepSpeed ZeRO-2 / ZeRO-3: stage detection at load, MoE and fused LoRA leaves, precision resync, reentrant checkpointing - #14394
Conversation
A router picks a different expert subset per step and per rank, so ZeRO-3's per-submodule hooks see a step-dependent module order and, across ranks, mismatched all-gathers (DeepSeek-V3, OLMoE and friends on transformers 4.x call experts one by one). Mark every block with experts plus a gate or router a ZeRO-3 leaf before deepspeed.initialize, as DeepSpeed's own default list does for Mixtral and Qwen2/3-MoE. Adds deepspeed_zero_stage(), which reads the stage before TrainingArguments exist (accelerate launch env or its config file). No-op without ZeRO-3.
TrainingArguments resolve the DeepSpeed config's auto fp16 / bf16 from the flags the caller passed. Unsloth's trainers then switch models that cannot run in float16 (Gemma3, Qwen3-MoE) to float32 on a T4 / V100, and transformers refused to train: ds fp16.enabled=True vs hf fp16=False. When the switch changed the flags, point the filled config at them.
The switch to non-reentrant checkpointing on any distributed launch exists for DDP's reducer (#3713). DeepSpeed reduces from its own hooks, and under ZeRO-3 non-reentrant recompute re-runs the parameter gather hooks and fails torch's saved-tensor check (DeepSeek-V3 on transformers 4.57.6: 115 tensors saved in the forward, 67 in the recompute). Keep the reentrant path under DeepSpeed, as FSDP2 and one GPU do.
The fused LoRA kernels and the fast RMSNorm read q/k/v/o, MLP and LoRA weights inside the layer forward without calling those modules, so ZeRO-3 only finds them on attribute access and registers them as external parameters. Its prefetch trace then stops matching once forwards differ, and GRPO died on its next step with 'tracing error ... expected the next 8 parameters in the parameter fetch queue'. Mark each patched decoder layer a ZeRO-3 leaf so its whole subtree is gathered on entry. SFT LoRA / QLoRA parity with one GPU is unchanged.
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. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f9d29d65f3
ℹ️ 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".
| if bool(section.get("enabled", False)) != enabled: | ||
| section["enabled"] = enabled | ||
| changed.append(key) |
There was a problem hiding this comment.
Remove resolved DeepSpeed precision mismatches
When an explicit DeepSpeed config has fp16.enabled: true but args.fp16 was initially false, HfTrainerDeepSpeedConfig.trainer_config_process() records that mismatch before the generated trainer later enables fp16 automatically. This loop then sees that the config already has the desired value and leaves the wrapper's existing mismatches entry intact, so trainer_config_finalize() still raises and the run cannot start. The resync must also clear or recompute the precision-related mismatch bookkeeping.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 150f442: after the resync, the fp16.enabled / bf16.enabled entries that trainer_config_process already queued in hf_deepspeed_config.mismatches are dropped (the config now agrees with the flags), so trainer_config_finalize no longer raises for them; other mismatches stay. Test pins the prefix to the string transformers writes in fill_match.
| if bool(section.get("enabled", False)) != enabled: | ||
| section["enabled"] = enabled | ||
| changed.append(key) |
There was a problem hiding this comment.
Refresh the cached DeepSpeed dtype after changing precision
When this helper changes a filled fp16/bf16 section, the associated HfTrainerDeepSpeedConfig._dtype remains the value computed from the old flags. For a DeepSpeed config using tensor_parallel.autotp_size > 1, Transformers passes hf_deepspeed_config.dtype() to deepspeed.tp_model_init(), so a forced float32 or bf16 switch can still initialize tensor parallelism with the stale dtype. Update the holder's cached dtype along with its config.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 150f442: _dtype is recomputed from the resynced config with the same bf16 / fp16 / float32 order trainer_config_process uses, so tp_model_init and dtype() see the switched precision.
…refresh the cached dtype [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 150f44265f
ℹ️ 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".
| if hasattr(hf_config, "_dtype"): | ||
| enabled = lambda key: hf_config.config.get(key, {}).get("enabled", False) is True | ||
| hf_config._dtype = ( | ||
| torch.bfloat16 if enabled("bf16") else torch.float16 if enabled("fp16") else torch.float32 |
There was a problem hiding this comment.
Derive cached dtype from the new precision flags
When the caller's DeepSpeed config omits the fp16/bf16 sections and Unsloth switches the arguments from float32 to fp16 or bf16, this recomputation still records torch.float32 because the desired section has not been added yet. AcceleratorState subsequently adds that section through DeepSpeedPlugin.set_mixed_precision(), but it does not refresh HfTrainerDeepSpeedConfig._dtype, so configurations using tensor_parallel.autotp_size > 1 initialize tensor parallelism with float32 despite DeepSpeed training in the selected mixed precision. Compute _dtype from the updated argument flags or otherwise refresh it after the plugin fills absent sections.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ebd1e3e: _dtype is now derived from the resolved flags (bf16, else fp16, else float32), not from the config sections, so a config without fp16 / bf16 sections that accelerate fills in later still gets the switched dtype. New test with no precision sections and bf16 = True: was float32, now bfloat16.
…the config has no fp16 / bf16 section [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ebd1e3eb15
ℹ️ 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".
| if str(os.environ.get("ACCELERATE_USE_DEEPSPEED", "")).strip().lower() not in _TRUTHY: | ||
| return None |
There was a problem hiding this comment.
Re-run ZeRO setup after TrainingArguments exist
When users load and PEFT-patch the model before constructing SFTConfig/TrainingArguments(deepspeed=...) under torchrun, there is no Transformers weakref or ACCELERATE_USE_DEEPSPEED environment variable yet, so this returns None. All new consumers make permanent setup decisions during model patching and are never retried after the Trainer receives the DeepSpeed arguments: MoE and fused-LoRA leaves remain unmarked, while distributed VLMs retain the non-reentrant checkpoint path that this change says fails under ZeRO. Re-run the stage-dependent setup from the Trainer hook once its arguments/plugin are available.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 122d80d: the generated Unsloth trainer init (all TRL trainers patched in rl.py, after the precision resync and before accelerator.prepare) now calls apply_deepspeed_zero3_model_setup(model). Once TrainingArguments has made ZeRO-3 visible it re-marks MoE blocks and the fused LoRA layers (tagged at patch time) as ZeRO-3 leaves, idempotently. The VLM checkpointing choice is bound into the modules at load, so it cannot be switched cleanly afterwards; in that case it prints a one-line warning to load under the DeepSpeed launch. Tests: a meta Qwen3-MoE loaded with no DeepSpeed, then the HF DeepSpeed config exposed: MoE blocks and the fused layer become leaves, the unfused one does not, a second call changes nothing; plus a source check that the trainer calls it. 3 new tests failed before, 30 pass now.
| if n_qkv + n_o + n_mlp > 0: | ||
| set_deepspeed_fused_lora_leaf_modules(model.model.model.layers) |
There was a problem hiding this comment.
Check actual fused kernels before marking Qwen2 layers
For Qwen2, the existing fallback increments n_qkv even when it did not install apply_lora_qkv—for example, a q-projection-only adapter fails the fused QKV condition because Qwen2's Q/K/V projections have biases, and no MLP or O kernel need be fused. This count nevertheless marks every decoder block as a ZeRO-3 leaf, forcing whole-block all-gathers despite all weight accesses still going through their modules; on large models this unnecessarily raises peak memory and can cause OOMs. Base this decision on the actually installed fused methods rather than the aggregate logging counters.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3c3c43e: the leaf marking now goes through _fused_lora_layers, which keeps only layers whose self_attn.apply_qkv / apply_o is the fused LoRA function or whose MLP forward is bound to the fused MLP, so the qwen2 counter fallback (and any layer left unfused) no longer turns a whole block into a ZeRO-3 leaf. Test covers an unfused layer next to QKV-, O- and MLP-fused ones.
…l as leaves [skip ci]
|
@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". |
…n ZeRO-3 only shows up in TrainingArguments [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
[skip ci]
# Conflicts: # unsloth/models/llama.py [skip ci]
…stead of inference_mode (unslothai#14395) ## Summary - Score old / reference logprobs with the gathered ZeRO-3 head (unsloth_zoo helper from unslothai/unsloth-zoo1900, guarded import so older zoo keeps today's behaviour). - On a DeepSpeed launch, score under `no_grad` instead of `inference_mode`, as FSDP already does: ZeRO-3 keeps parameters gathered there, and the next training step failed with `Inference tensors cannot be saved for backward`. ## Tests - `tests/test_fsdp_generation_grad_mode.py`: 4 new cases fail on main, 15 pass here. - Kaggle 2x T4, ZeRO-3 GRPO with LoRA and QLoRA (with the zoo PR and the fused LoRA leaf change in unslothai#14394): trains 4 steps; main fails at step 1. ## Not covered - Parity with one GPU, vLLM generation, a trainable head. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…mpile packing test off leaked env (#14425) ## Problem Two tests on main fail in CI for reasons in the tests, not the product. They are red on unrelated PRs, for example #14409 and #14365. **1. `tests/python/test_v100_fullft_precision.py` (10 tests, `Repo tests (CPU, studio)`)** ``` tests/python/test_v100_fullft_precision.py:80: in _decide exec(CODE, {"torch": torch, "os": os}, {"args": args, "model": model}) E NameError: name 'args' is not defined ``` The test runs the `mixed_precision` template from `unsloth/models/rl.py` with separate globals and locals dicts. #14394 added `_unsloth_precision_requested = tuple(getattr(args, k, False) for k in (...))` to that template. In the generated trainer this runs inside a function, where the generator sees `args`, so the product is fine. A generator inside `exec` with a separate locals dict cannot see those locals, so the test raises `NameError`. **2. `tests/test_legacy_block_compile_install.py::test_packed_calls_keep_the_unsloth_layer_forward` (`Repo tests (CPU, rest)`)** ``` tests/test_legacy_block_compile_install.py:105: in test_packed_calls_keep_the_unsloth_layer_forward E assert [] ``` The test (from #14398) expects an unpacked call to go through the compiled block. `_block_compile._wrap` keeps every call on the stock forward when `UNSLOTH_COMPILE_DISABLE` is `1`, `UNSLOTH_BLOCK_COMPILE` is `0`, or `UNSLOTH_FORCE_FLOAT32` is `1`. Eight test modules run `os.environ.setdefault("UNSLOTH_COMPILE_DISABLE", "1")` at import time, so the result depends on which modules a worker collected. The test passes alone and fails with any of those variables set. ## Fix Test only: - `test_v100_fullft_precision.py`: `exec` the template in one namespace, as in the trainer's function scope. Results are still read from `args` and the environment. - `test_legacy_block_compile_install.py`: the packing test clears the three variables with `monkeypatch.delenv` before wrapping. ## Verification - `test_v100_fullft_precision.py`: on main 10 failed (the `NameError` above); with this change 10 passed. - `test_legacy_block_compile_install.py` on main: - with any one of `UNSLOTH_COMPILE_DISABLE=1`, `UNSLOTH_BLOCK_COMPILE=0` or `UNSLOTH_FORCE_FLOAT32=1` set: 1 failed (the packing test), 5 passed; - with this change: 6 passed in each of those three cases and with none set.
Summary
accelerate launchenvironment or its config file).ds fp16.enabled=True vs hf fp16=False.CheckpointErrorunder ZeRO-3 on transformers 4.57.6.tracing error ... parameter fetch queue.Tests
tests/test_deepspeed_zero3.py: 18 new tests fail on main, all 24 pass here, on torch 2.10, 2.13 and 2.14.Not covered
lr_scheduler.stepon main and here; separate issue.