Skip to content

Eager flex_attention: build the score_mod backward graph outside checkpoint saved-tensor hooks - #18219

Merged
danielhanchen merged 3 commits into
mainfrom
flex-eager-checkpoint-hooks
Nov 17, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
flex-eager-checkpoint-hooks

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Summary

Eager flex_attention inside a non-reentrant gradient checkpoint (the default under DDP) restarts the checkpointed layer's recompute in the middle of its own forward. Depending on what the layer saved, training either stops with

torch.utils.checkpoint.CheckpointError: torch.utils.checkpoint: Recomputed values for the following tensors have different metadata than during the forward pass.

or keeps going with wrong input gradients and no error.

This PR builds flex's score_mod backward graph under identity saved-tensor hooks whenever some saved-tensor hooks are active. Nothing changes when no hooks are active.

Root cause

When flex_attention runs eagerly (Inductor could not compile the call, suppress_errors falls back, or Dynamo has marked flex as skipped), the HOP's autograd implementation calls create_fw_bw_graph (torch/_higher_order_ops/flex_attention.py). That function traces the score_mod joint graph with make_fx, and the trace calls torch.autograd.grad. Inside a non-reentrant checkpoint the checkpoint's pack / unpack hooks are the active default hooks. The trace packs through them and then unpacks, and the unpack is what tells the checkpoint frame to recompute. So the layer reruns while its first forward is still in flight, and the checkpoint compares the tensors saved so far against a full rerun.

The traced joint graph holds no activations, so running the trace under identity hooks (the innermost hooks win) is the correct behaviour.

The same happens without block compile. On origin/main, the tiny Gemma-2 test model with UNSLOTH_BLOCK_COMPILE=0 and non-reentrant checkpointing does not raise, but its LoRA gradient norm is 146.57 on the first step and 373.30 on the second (the correct value is 0.026149). Nothing in the run flags it.

Pure torch reproduces it with no Unsloth code. A Linear followed by eager flex_attention with a softcap score_mod, on 1 x 2 x 32 x 8 inputs:

run layer calls during forward input grad norm
no checkpoint 1 28.6913
non-reentrant checkpoint, torch as is 2 76.7271 (wrong)
non-reentrant checkpoint, with this fix 1 28.6913

In Unsloth, the tiny Gemma-2 test model (head_dim 8) hits it through per-layer block compile. The forced main flex kernel cannot lower at head_dim below 16, so the full-attention layer keeps flex outside the block, and that flex call runs eagerly. With reentrant checkpointing (single GPU) the forward runs under no_grad and never builds the joint graph, which is why only DDP failed. Real Gemma-2 (head_dim 256) compiles flex in this configuration, so this exact trigger is specific to the tiny model. A tiny Gemma-2 copy with head_dim 64 compiles flex and never reaches the eager path. Any training run where flex falls back to eager while non-reentrant checkpointing is on is exposed, though.

Changes

  • unsloth/import_fixes.py: fix_flex_attention_eager_saved_tensor_hooks wraps create_fw_bw_graph. Under active saved-tensor hooks it pushes identity hooks for the trace. Otherwise, or if hooks are disabled, it calls torch's function unchanged. torch 2.6 has no way to query the active hooks (_top_saved_tensors_default_hooks), so there the trace always runs under identity hooks. The fix is idempotent and does nothing on a torch without the function.
  • unsloth/_gpu_init.py: applies the fix at import, next to the other torch fixes.
  • tests/test_flex_eager_checkpoint_hooks.py: a CPU test for the wrapper contract (wraps once, nothing pushed without hooks, identity hooks pushed under active hooks) and a GPU test checking that eager flex in a non-reentrant checkpoint matches the plain run, with exactly one layer call during the forward.

Testing

  • New tests: origin/main 2 failed (the checkpoint recomputed the layer inside its own forward, wrapper missing), this branch 2 passed, about 1 s of test time each.
  • Tiny Gemma-2, real 2-rank DDP (torchrun, gloo, both ranks on one B200), 2 LoRA steps: origin/main raises the CheckpointError above on both ranks. This branch completes, and both ranks report identical loss and grad norm.
  • Same model on one GPU with non-reentrant checkpointing forced: origin/main fails, this branch passes.
  • Parity numbers and the no-change check on a model that already worked are in the table below.

Tiny Gemma-2, non-reentrant checkpointing forced on one GPU, fp32, 2 LoRA steps (one-step loss and LoRA grad norm):

arm loss grad norm
origin/main, block compile off 12.45302868 146.571 then 373.299
origin/main, block compile on CheckpointError
this PR, block compile off 12.45302868 0.026148804
this PR, block compile on 12.45302868 0.026148802
this PR, reentrant, block compile off (reference) 12.45302868 0.026148804

Block on vs off on this branch: loss delta 0, grad norm relative delta 7.1e-08, inside the #10744 tolerances (loss 1.4e-4, grad norm 1.5e-3).

No change where nothing was broken: a tiny Gemma-2 with head_dim 64 (flex compiles, both layers fully block compiled) gives bit-identical loss and grad norm on origin/main and this branch, in bf16 and fp32. A counting wrapper shows that create_fw_bw_graph runs 2 times there and never under active hooks, so the fix stays inert. On the head_dim 8 model it engages 8 times. Reentrant checkpointing results are identical on both trees.

torch versions (CPU wheels): wrapper applied, CPU test, and the pure-torch repro (Linear + eager flex with a softcap score_mod in a non-reentrant checkpoint, input grad error vs no checkpoint)

torch wrapper CPU test repro, torch as is repro, with this PR
2.6.0 applied (always under identity hooks) passed 2 layer calls in the forward, error inf 1 call, error 0
2.10.0 applied passed 2 calls, NaN gradient 1 call, error 0
2.14.1 applied (also reached from the new sdpa_dense_backward call site) passed CPU flex has no backward
2.15.0 applied passed CPU flex has no backward

AMD gfx1151 (ROCm, torch 2.11), base vs this PR

Linux Windows
new tests 2 failed / 2 passed 2 failed / 2 passed
tiny Gemma-2, flex, non-reentrant checkpoint, block compile off base fails (the recompute starts inside flex's FX trace); this PR matches no checkpoint exactly same
standard LoRA training cells and generate identical identical

Not covered

  • NCCL across two physical GPUs (DDP ran with gloo on one card).
  • A real-size model that falls back to eager flex during training.
  • The numerical effect on torch 2.14 / 2.15 (CPU flex has no backward there; no CUDA run on those versions).

…kpoint saved-tensor hooks

Eager flex_attention traces its score_mod backward with torch.autograd.grad in
create_fw_bw_graph during the forward. Inside a non-reentrant checkpoint (the DDP
default) the unpack restarts the layer's recompute mid forward: CheckpointError
(tiny Gemma-2 with block compile under DDP) or silently wrong input gradients.
Trace under identity hooks while saved-tensor hooks are active.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T22:15:34.885686Z 285a5de 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 765e82805b

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

Reviewed commit: 285a5ded56

ℹ️ 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 e5dc6b4 into main Nov 17, 2026
@danielhanchen
danielhanchen deleted the flex-eager-checkpoint-hooks branch November 17, 2026 22:40
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