Skip to content

DeepSpeed ZeRO-2 / ZeRO-3: stage detection at load, MoE and fused LoRA leaves, precision resync, reentrant checkpointing - #14394

Merged
danielhanchen merged 14 commits into
mainfrom
dh/s2-w2
Oct 20, 2026
Merged

danielhanchen merged 14 commits into
mainfrom
dh/s2-w2

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

  • Detect the DeepSpeed ZeRO stage at load time, before TrainingArguments exist (the accelerate launch environment or its config file).
  • Mark MoE blocks (experts plus a gate or router) as ZeRO-3 leaf modules, as DeepSpeed already does for Mixtral and Qwen MoE.
  • Resync a filled DeepSpeed config when the trainer switches precision. Gemma3 and Qwen3-MoE forced to float32 on a T4 failed with ds fp16.enabled=True vs hf fp16=False.
  • FastModel keeps reentrant gradient checkpointing under DeepSpeed; non-reentrant recompute raised CheckpointError under ZeRO-3 on transformers 4.57.6.
  • Fused LoRA decoder layers become ZeRO-3 leaves, so the weights the fused kernels read are gathered with the layer. This fixes the GRPO 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.
  • Kaggle 2x T4, main vs this branch in one kernel, ZeRO-2 and ZeRO-3: LoRA / QLoRA / full finetune on Llama, LoRA on Qwen3-MoE, LoRA / QLoRA on Gemma3 VL. fp32 parity with one GPU unchanged (Llama about 1e-6 over 12 steps); the fp16 MoE and VL runs go from ValueError to training.

Not covered

  • No MoE hang reproduced on hardware (unit tests only).
  • transformers 4.57.6 + DeepSpeed fails in lr_scheduler.step on main and here; separate issue.

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 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 ⚠️ Failed 2026-10-20T22:31:28.484926Z
We couldn’t complete this review. Comment @codex review to try again.
bb0561d New commits
🔒 Security Review ⚠️ Failed 2026-10-20T18:50:06.389443Z
We couldn’t complete this review. Comment @codex security review to try again.
f9d29d6 PR opened
ℹ️ 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen danielhanchen self-assigned this Oct 20, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +310 to +312
if bool(section.get("enabled", False)) != enabled:
section["enabled"] = enabled
changed.append(key)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +310 to +312
if bool(section.get("enabled", False)) != enabled:
section["enabled"] = enabled
changed.append(key)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread unsloth/models/loader_utils.py Outdated
Comment on lines +327 to +330
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +269 to +270
if str(os.environ.get("ACCELERATE_USE_DEEPSPEED", "")).strip().lower() not in _TRUTHY:
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment thread unsloth/models/llama.py Outdated
Comment on lines +5131 to +5132
if n_qkv + n_o + n_mlp > 0:
set_deepspeed_fused_lora_leaf_modules(model.model.model.layers)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 3c3c43e4dc

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

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 122d80dc17

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

[skip ci]
# Conflicts:
#	unsloth/models/llama.py

[skip ci]
@danielhanchen
danielhanchen merged commit b098d77 into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the dh/s2-w2 branch October 20, 2026 22:32
Chroma01 pushed a commit to Chroma01/unsloth that referenced this pull request Oct 21, 2026
…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>
danielhanchen added a commit that referenced this pull request Oct 21, 2026
…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.
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