Repository navigation
MoE router aux loss keeps its gradient under unsloth gradient checkpointing - #17873
Merged
Merged
Conversation
…inting Reentrant checkpointing (Unsloth's smart offloaded checkpointing, transformers' default) runs the first layer forward under no_grad, so the router logits it returns carry no graph: with the load-balancing loss on, the loss gained its value but the gradients did not. Tiny gpt-oss with router_aux_loss_coef 0.9: LoRA grad norm 0.0170 with use_gradient_checkpointing = 'unsloth' vs 0.0283 without (transformers 4.57.6), 0.0176 vs 0.0701 (5.23); on Kaggle 2xT4 the same drop showed under one GPU and FSDP2 while DDP, which already checkpoints non-reentrantly, matched. pp_native refused this pairing for pipeline parallel only. A model whose config carries output_router_logits with the loss on (output_router_logits, or router_aux_loss_coef > 0, which TRL's SFTTrainer turns on) now takes the non-reentrant path DeepSeek-V4.1 and DDP VLMs already use, activations still offloaded through saved-tensor hooks. Gemma 3n / 4 keep reentrant checkpointing for their AOT backward. GPU test: grad norm with checkpointing equals without on gpt-oss and Qwen3-MoE tiny, both transformers versions; it fails on main.
The trial forward that #17857 runs inside a non-reentrant checkpoint was recorded by transformers' output capture as an extra MoE router_logits entry, which changed the load-balancing loss and its gradient (tiny Qwen3-MoE, coefficient 0.9: LoRA grad norm 1.044 with checkpointing vs 1.214 without). Suppress capture for the trial: the collector context variable on transformers 5, the make_capture_wrapper forwards on 4.x.
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. |
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! 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: # tests/test_block_compile.py # unsloth/models/_block_compile.py [skip ci]
This was referenced Nov 16, 2026
danielhanchen
added a commit
that referenced
this pull request
Nov 16, 2026
) ## Summary `Repo tests (CPU, rest-2)` has failed on `main` since #17873 (MoE router aux loss under unsloth gradient checkpointing): ``` tests/test_moe_aux_loss_checkpointing.py::test_router_aux_loss_gradient_survives_unsloth_checkpointing[trl-internal-testing/tiny-GptOssForCausalLM] tests/test_moe_aux_loss_checkpointing.py::test_router_aux_loss_gradient_survives_unsloth_checkpointing[trl-internal-testing/tiny-Qwen3MoeForCausalLM] unsloth/models/_utils.py:521: in apply_unsloth_gradient_checkpointing E RuntimeError: pin_memory=True requires a CUDA or other accelerator backend; no pinned memory allocator is available on this system. ``` The module is marked `gpu` only. The `Repo tests (CPU)` shards select with `-m 'not server and not e2e'`, so gpu-marked tests are collected there too. The suite's convention is to pair the marker with a recorded real-accelerator skip, as in `tests/test_cross_entropy_*.py`. The fix #17873 tests is right; the test just ran on a runner it cannot use. ## Change (test only) `pytestmark` adds `skipif(not has_real_accelerator(), ...)` from `tests/_shared/real_accelerator.py`, next to `pytest.mark.gpu`. That probe records the answer before `tests/_zoo_aggressive_cuda_spoof.py` patches `torch.cuda.is_available`, so a CPU runner skips and a GPU box still runs both cases. ## Verification `tests/test_moe_aux_loss_checkpointing.py` on a CPU host: 2 skipped (`loads a model with offloaded gradient checkpointing`). On `main`: 2 failed as above. `tests/python/test_accelerator_skip_guards.py` accepts the new guard. Its one remaining failure, `test_block_cudagraphs_side_grad.py`, is fixed separately in #17890.
Penguinjanator
pushed a commit
to Penguinjanator/unsloth
that referenced
this pull request
Nov 16, 2026
…on without Triton, kernel and test gates (unslothai#17882) Backend CI on main has been red since today's merges. Every failure traces to one commit; this fixes the unsloth side (the gloo-cp shard also needs unslothai/unsloth-zoo#2542, since CI installs zoo from main). | CI shard / test | Cause | Fix | |---|---|---| | gloo: `test_qwen4exp_parallel_matches_one_process[pp*]`, `test_pp_splits_streams_and_runs_the_mixer_last`, all of `test_frozen_table_pp_gloo.py` | unslothai#17785: transformers 5.17 (the CI pin) names the Qwen4Exp layer type `qwen_sparse_attention`, 5.22 renamed it `indexed_attention`; pipeline parallel only accepted the new name, so every rank raised "hybrid layer stacks" | accept both names in `_PP_HYBRID_FAMILIES` | | diffusion (Python 3.13): 13 tests in `test_diffusion_int8_attention_triton_device.py` | unslothai#17855: `_launch` read `triton.runtime` while `triton` is `None` on that shard | check `triton is not None` first | | rest: `test_every_constexpr_line_has_a_comment` | unslothai#17860: 23 uncommented `tl.constexpr` parameters in `large_head_attention.py` | comments added; `_tma_tile`'s signature split one parameter per line | | rest: `test_every_launch_requests_fp_fusion` | unslothai#17860: the `_launch` helper forwards `enable_fp_fusion` from every caller, but the gate did not know it is a helper | registered like `layernorm.py`'s | | rest: `test_no_file_is_dropped_or_run_twice` | unslothai#17868: `tests/test_ddp_push_rank0_gloo.py` matched both the gloo shard and rest-2's `test_[dimsu]*.py` | renamed `tests/test_hub_push_rank0_ddp_gloo.py` | | rest-2: `test_checked_in_file_reads_name_an_encoding` | unslothai#17867: `read_text()` without an encoding in `tests/test_bind_local_cuda_device.py` | `encoding = "utf-8"` | | rest-2: `test_sentence_transformer_trainer_checks_the_placement_before_the_deferred_compile[*]` | unslothai#17859: `patch_train_dataloader` assumed every trainer class has `get_train_dataloader` | skip the patch when the method is missing | | rest-2: `test_router_aux_loss_gradient_survives_unsloth_checkpointing[*]` | unslothai#17873: the gpu-marked test still runs under CI's `-m 'not server and not e2e'` | `has_real_accelerator()` skip next to the gpu mark | | studio: `test_no_skip_guard_reads_a_spoofable_accelerator_probe` | unslothai#17850: `test_block_cudagraphs_side_grad.py` skipped on `torch.cuda.is_available()`, which the CUDA spoof fakes | skip on `has_real_cuda()` | ## Tests In a venv matching CI (Python 3.12, torch 2.10.0+cpu, transformers 5.17.0, TRL 1.15, PEFT 0.21.3, `UNSLOTH_COMPILE_DISABLE=1`, `-m 'not server and not e2e'`): - gloo: `test_qwen4exp_parallel_gloo.py` failed on main, 9 / 9 pass here; `test_frozen_table_pp_gloo.py` 13 / 13. - rest / rest-2 / studio: the nine affected files had exactly CI's 9 failures on main; 153 passed / 6 skipped here. - diffusion: with Triton blocked (as on the Python 3.13 shard), the 13 failures pass here; with Triton present everything passes. The only non-test code changes are the PP layer-type name, the Triton `None` check and the Sentence Transformers method check; `large_head_attention.py` changes are comments only.
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.
With the MoE router load-balancing loss on, Unsloth's default
"unsloth"gradient checkpointing kept the aux loss in the logged value but dropped its gradient. On gpt-oss the step-1 grad norm was 0.0261 with checkpointing vs 0.0486 without.Root cause
Reentrant checkpointing runs the layer forward under
no_gradfirst. The router logits that transformers captures there carry no graph. The loss therefore gains the aux value, but the router and expert LoRA weights get no aux gradient.pp_nativerefused this pairing for pipeline parallel only.Fix
A model whose config has
output_router_logits, with the loss on, now takes the non-reentrant checkpoint path that DeepSeek-V4.1 and DDP already use. "Loss on" meansoutput_router_logitsis set, orrouter_aux_loss_coef > 0, which TRL's SFTTrainer turns on. Activations are still offloaded through saved-tensor hooks. Gemma 3n / 4 keep reentrant checkpointing.This PR includes #17872's commit, which keeps block compile's non-reentrant trial forward out of output capture. Without it, Qwen3-MoE records an extra
router_logitsentry. Merge #17872 first.Results
GPU test
tests/test_moe_aux_loss_checkpointing.py(B200, correctness only): LoRA grad norm with"unsloth"checkpointing equals the norm without checkpointing, at aux coefficient 0.9.Colab T4 (fp16, gpt-oss, one GPU): grad norms with checkpointing now equal those without,
[0.0486, 0.048, 0.0625, 0.0266]. 8 activation tensors were offloaded. Qwen3-MoE also matches.Cost (Colab L4, medium random Qwen3-MoE, hidden 1024, 8 layers, 32 experts top-4, LoRA r16, bf16, batch 2 x 1024, median of steps 8-30; base run 3 times, head 3 times):
Step time is about 5% slower, and peak memory about 23% lower.
Not covered: FSDP2 after the change, larger models and longer sequences.