Skip to content

Block compile: keep the GatedDeltaNet self-check out of a non-reentrant checkpoint - #14195

Merged
danielhanchen merged 3 commits into
unslothai:mainfrom
oobabooga:gdn-selfcheck-checkpoint
Oct 19, 2026
Merged

danielhanchen merged 3 commits into
unslothai:mainfrom
oobabooga:gdn-selfcheck-checkpoint

Conversation

@oobabooga

Copy link
Copy Markdown
Member

Addresses the GatedDeltaNet failure in #14063.

Problem

On 2026.10.6, LoRA training of Qwen3.5 (a GatedDeltaNet hybrid) with use_gradient_checkpointing="unsloth" under DDP or FSDP2 dies in the backward of step 1. Reproduced here on Qwen3.5-0.8B with 2 GPUs; the issue reports the same on the 27B model with 8 GPUs:

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: 55
Number of tensors saved during recomputation: 45.

Single-GPU runs are not affected. UNSLOTH_BLOCK_COMPILE=0 avoids it.

Root cause

Distributed runs use torch's non-reentrant checkpoint (use_reentrant = not is_distributed() in vision.py), whose saved-tensor hooks are active for the whole layer forward.

On the first GatedDeltaNet layer, the block-compile wrapper calls _prepare_gdn, which runs _gdn_op._fla_ops. Its _self_check does a forward and torch.autograd.grad against fla's own Function. Because this happens inside the checkpointed layer forward:

  1. The self-check's saved tensors are packed into the layer's checkpoint frame.
  2. Its autograd.grad unpacks them, which starts a recompute of the whole layer during forward0.
  3. That nested recompute enters the block-compile wrapper before the layer is marked checked, so the trial loop catches torch's _StopRecomputationError and demotes the layer kind _FULL -> _SPLIT -> _OFF. The self-check then fails as well, so the fla opaque op is disabled.
  4. The original forward finishes compiled and saves the self-check's tensors plus the compiled set (55). The real recompute in backward runs the stock forward for that layer (45), and check_recomputed_tensors_match raises.

The fla self-check runs for every user because unsloth_zoo vendors fla.

Fix

Run the self-check in _fla_ops under its own saved_tensors_hooks, so an enclosing checkpoint never sees its tensors. The pack hook detaches, as torch's own recompute hook does, so a check that fails before autograd.grad does not leave a reference cycle holding its tensors.

#14065 alone does not fix the reproduction. Re-raising _StopRecomputationError removes the demotion, but the self-check's tensors are still in the frame, so the run still fails with 55 vs 46. With this change the nested recompute never happens.

Verification

Qwen3.5-0.8B, LoRA r=16, use_gradient_checkpointing="unsloth", 3 steps, 2 GPUs, torch 2.12.1+cu130:

Launch main This PR
torchrun, DDP wrapper CheckpointError 55 vs 45, 18 layers OFF trains, 24 layers FULL
accelerate FSDP2, SFTTrainer CheckpointError 55 vs 45, 18 layers OFF trains, 24 layers FULL

Single GPU (reentrant) is unchanged: same step-0 loss, all layers FULL.

Tests:

  • New test_gdn_self_check_stays_out_of_a_non_reentrant_checkpoint runs _fla_ops inside checkpoint(..., use_reentrant=False) with a stand-in self-check that calls autograd.grad. It fails on main with CheckpointError (10 vs 5) and passes here. It runs on CPU without fla.
  • tests/test_block_compile.py: 22 passed, 1 failed. test_qwen3_5_gdn_block_has_no_break fails the same way on main.

Not covered

The plain-attention case in the issue (MuseGlimmerTextDecoderLayer, 65 vs 64) and the reported slowdown.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 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 ✅ Completed 2026-10-19T07:02:08.887919Z 43c4cbd Manual request
ℹ️ 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 danielhanchen self-assigned this Oct 19, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 3b1f3b88af

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

@oobabooga

Copy link
Copy Markdown
Member Author

Reached Codex review convergence at oobabooga#385.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 43c4cbdf33

ℹ️ 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
danielhanchen merged commit cefb057 into unslothai:main Oct 19, 2026
iam-knoit pushed a commit to SynhalaAI/unsloth that referenced this pull request Oct 19, 2026
unslothai#14231)

## Summary

Follow-up to the unslothai#13880 review.

1. **Process-global QLoRA flag.** `prepare_fsdp2_qlora` set
`unsloth.kernels.utils._FSDP2_QLORA_PREPARED = True`, and the LoRA
getters and `fast_lora_forward` read it before falling back to the
`Linear4bit`'s own `quant_state`. Dynamo guards on a global it reads.
Once one FSDP2 QLoRA model had been prepared, every compiled dense LoRA
forward in the process compiled a second graph. The fallback is now
gated on the weight itself: only an FSDP2 all-gathered 4-bit weight
loses `quant_state`, and its packed bytes are `(N, 1)`. The flag and its
setter are removed.
2. **Block compile and non-reentrant checkpointing.** A non-reentrant
checkpoint ends a recompute by raising `_StopRecomputationError` through
the forward. The block compile wrapper treated that as a compile failure
and put the stock forward back in every block. It now re-raises it.

Without FSDP2 the getters take the same path as before: `getattr(W,
"quant_state")` first, and the shape check only runs when that is
`None`.

## Tests

`tests/python/test_get_lora_parameters_fsdp2_quant_state.py`:

| Case | main | this PR |
|---|---|---|
| a compiled dense LoRA forward, before and after an FSDP2 QLoRA model
is prepared | 2 graphs | 1 graph |
| the getters read no process-global flag | fails | passes |

With the existing fp8 getter tests, `tests/test_block_compile.py`,
`tests/test_fsdp2_qlora.py` and
`tests/test_fsdp2_qlora_prepare_order.py`: 59 passed.

Under a 2-rank launch with Unsloth's block compile, Llama, Qwen3,
Qwen3-MoE, Gemma3, Gemma4 and Qwen2.5-VL show 0 graph breaks and nothing
compiling from step 2 on, LoRA and QLoRA.

## Not covered here

- torch 2.13 only so far; torch 2.10 and 2.14 runs on T4 x2 are in
progress.
- The GatedDeltaNet self-check under a distributed checkpoint is fixed
separately in unslothai#14195.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-zoo-staging-2 that referenced this pull request Oct 21, 2026
…i#1895)

Fixes the remaining Muse Glimmer part of
unslothai/unsloth#14063 (the GatedDeltaNet
part was fixed in unslothai/unsloth#14195).

## Problem

Muse Glimmer LoRA training with block compile (on by default) and
`use_gradient_checkpointing="unsloth"`:

1. Under DDP it dies in the backward of step 1, with no block compile
demotion logged:
   ```
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: 67
   Number of tensors saved during recomputation: 64.
   ```
2. On any launch, single GPU included, every step recompiles one graph
per sliding-attention layer. This is the slowdown reported in the issue
(140-180 s/step with block compile against ~18 s/step without).

## Root cause

Unsloth compiles each decoder layer as one region, so the Muse Glimmer
sdpa router is traced. On its deferral path (every sliding layer below
3x the window, and every sliding layer while compiling, since the band
probe declines under compile) it bumps a debug counter, `_DEFERRED[0] +=
1`. Dynamo guards on the counter's value, so the next call never matches
a cached graph and recompiles.

Under DDP, the forward's compiles happen inside DDP's forward, where
dynamo's DDPOptimizer splits each layer graph at gradient-bucket
boundaries. The non-reentrant checkpoint's recompute runs in backward,
outside DDP's forward, and the counter has moved on, so it recompiles
there without the split. The two graphs save a different number of
tensors, and `check_recomputed_tensors_match` raises. Distributed runs
use the non-reentrant checkpoint (`use_reentrant = not
is_distributed()`), which is why only they crash; single GPU only pays
the recompiles.

## Fix

Skip the counter while compiling. It is a debug statistic
(`muse_glimmer_banded_stats`); eager calls still count. The engaged
paths are unchanged.

## Verification

8-layer random Muse Glimmer (real layer pattern: 3 sliding + RoPE, then
1 full + NoPE; hidden 1024, 8 / 2 heads, head_dim 128), LoRA r=16,
`use_gradient_checkpointing="unsloth"`, 4 steps, unsloth main:

| Run | zoo main | This PR |
| --- | --- | --- |
| DDP, non-reentrant checkpoint | `CheckpointError` 67 vs 64 in step 0
backward | trains, all 8 layers compiled |
| Single GPU, graphs compiled after steps 0 / 1 / 2 / 3 | 13 / 19 / 25 /
31 (6 per step, one per sliding layer; 4 in backward) | 7 / 7 / 7 / 7 (0
in backward) |

Real 2-GPU DDP (`torchrun --nproc_per_node=2`, Kaggle 2x T4, fp16, the
same model and script): zoo main fails on both ranks with
`CheckpointError` 67 vs 64 in the step 0 backward, 2 recompiles inside
the backward; with this change both ranks train 4 steps, 7 graphs total,
none compiled in the backward.

Controls on the failing DDP run: `UNSLOTH_BLOCK_COMPILE=0` trains, and
`torch._dynamo.config.optimize_ddp = False` also trains (no split, so
the recompute's recompile matches).

Tests: new `test_compiled_deferral_does_not_recompile` compiles a call
through the router 4 times and asserts one frame compile. It fails on
main and passes here; `tests/test_muse_glimmer_banded_attention.py` 20
passed, on CPU.

The added `torch.compiler.is_compiling()` check costs about 0.1 us per
eager sliding-layer call.
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.

2 participants