Skip to content

Fix NaN gradients from compiled flex attention on short static training batches - #12207

Merged
danielhanchen merged 2 commits into
mainfrom
fix-flex-training-decode-lse
Sep 29, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
fix-flex-training-decode-lse

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

LoRA training on Qwen3.5 (and any model Unsloth runs through flex attention) can produce inf / NaN gradients at step 0, while the loss looks normal. It happens when the first training-mode flex call of the process has a static query length below 128 and a batch size above 1. A short no-grad forward first hides it, which made it look like a warm-up problem.

Root cause

This is a PyTorch Inductor bug in compiled flex attention, not in the model code.

  • For a static query length below 128 (and a power-of-two GQA ratio), Inductor lowers the forward with its flex_decoding kernel.
  • That kernel builds the logsumexp with a flexible layout, and comprehensive_padding pads its batch stride. For (2, 24, 121) the saved buffer is empty_strided_cuda((2, 24, 121), (2912, 121, 1)) instead of stride 2904.
  • The flex backward template indexes the logsumexp as if it were contiguous (off_chz2 = (off_zq * HQ + off_hq2) * Q_LEN). The lowering makes delta contiguous but not logsumexp.
  • Every batch row after the first therefore reads a logsumexp shifted by 8 floats. The forward stays correct, but dq / dk / dv come out 10 to 100x too large. On a 64-layer model this compounds until the gradients overflow.

PyTorch main has the same lowering, so a torch upgrade does not fix it.

Pure PyTorch repro (no Unsloth, no transformers; B200, torch 2.13, B=2, H=24, S=121, head_dim 256, causal block mask, torch.compile(flex_attention) vs eager flex, relative error):

Setting dq dk dv
compiled, default 21.26 14.97 17.15
kernel_options={"FORCE_USE_FLEX_ATTENTION": True} 0.0068 0.0064 0.0026
comprehensive_padding=False 0.0068 0.0064 0.0026
batch size 1 0.0049 0.0050 0.0007
S = 128 0.0052 0.0066 0.0012

head_dim 64 is affected as well (dq relative error 104).

This also explains the earlier observations: a short first forward makes the later length-121 call recompile with dynamic shapes, and the decoding kernel needs static shapes. Transformers recompiles flex when training changes, so a no-grad warm-up after get_peft_model does not help.

Fix

Unsloth already wraps the registered transformers flex_attention function to pass kernel_options for large head dims. The wrapper now also sets FORCE_USE_FLEX_ATTENTION=True on calls that need a backward: grad enabled, a non-CPU device, and q / k / v requiring grad.

  • Inference and generation still use the decoding kernel, since those calls need no backward.
  • A caller's explicit BACKEND is left alone, because torch rejects it combined with the legacy flag. A caller's own FORCE_USE_FLEX_ATTENTION value wins.
  • The flag exists in torch 2.6 through main.

The proper fix belongs in Inductor (require_contiguous on logsumexp in the flex backward lowering); this avoids the broken kernel pairing until then.

Results

unsloth/Qwen3.8-27B-NVFP4, B200, batch (2, 121), LoRA r=16, first step:

Run Loss Non-finite LoRA grads
main, gradient checkpointing unsloth 0.5069 736
this PR, gradient checkpointing unsloth 0.5069 0
main, gradient checkpointing off 0.5148 550
this PR, gradient checkpointing off 0.5097 0
control: flex compiled with dynamic=True 0.5097 0
control: eager flex 0.5097 0

Tests

tests/test_flex_large_head_dim_kernel_options.py gains 4 tests:

  • a call that needs a backward gets the flag, merged with the existing block sizes above head_dim 256;
  • no-grad, CPU and decode-shaped calls are left unchanged;
  • an explicit BACKEND or the caller's own flag value is respected;
  • on CUDA, the compiled registered function matches eager flex gradients at batch 2, 16 heads, length 121.

25 passed. With unsloth/models/_utils.py from main and the tests kept, 2 fail, including dq relative error 47.6 vs eager flex attention.

Not covered

  • Tested on B200 with torch 2.13 only.
  • Step time of the main flex kernel versus the decoding kernel for short training batches was not measured; the decoding result is wrong for training in any case.

Inductor lowers a static query length below 128 to flex_decoding, whose
logsumexp gets a padded batch stride from comprehensive_padding. The
flex backward template indexes LSE as contiguous, so with batch > 1 every
row after the first reads a shifted LSE and the gradients blow up
(Qwen3.5 LoRA on B200: 550 non-finite LoRA grads at step 0).
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 28, 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-09-29T08:04:58.917764Z 645e75b New commits
🔒 Security Review ✅ Completed 2026-09-28T14:34:57.093729Z 1781e5c 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 Summary

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

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-09-28T14:14:47.544469Z 1781e5c PR opened
🔒 Security Review 🔄 Running since 2026-09-28T14:14:47.273119Z 1781e5c 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 security review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 1781e5c85d

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 1781e5c85d

ℹ️ 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 e22e297 into main Sep 29, 2026
33 of 35 checks passed
@danielhanchen
danielhanchen deleted the fix-flex-training-decode-lse branch September 29, 2026 10:32
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