Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Fix NaN gradients from compiled flex attention on short static training batches (#12207)
Daniel Hane22e297407eb
diff --git a/tests/test_flex_large_head_dim_kernel_options.py b/tests/test_flex_large_head_dim_kernel_options.pyindex 72f8d435e57..8d5906bd140 100644--- a/tests/test_flex_large_head_dim_kernel_options.py+++ b/tests/test_flex_large_head_dim_kernel_options.py@@ -122,3 +122,91 @@ def test_the_wrapper_keeps_the_original_signature():parameters = inspect.signature(ALL_ATTENTION_FUNCTIONS["flex_attention"]).parametersfor name in ("module", "query", "key", "value", "attention_mask"):assert name in parameters+++class _GradTensor(_Tensor):+ def __init__(+ self,+ shape,+ requires_grad,+ device_type = "cuda",+ ):+ super().__init__(shape)+ self.requires_grad = requires_grad+ self.device = type("device", (), {"type": device_type})()+++def _call_with(query, **kwargs):+ original, seen = _record()+ u._wrap_flex_attention_forward(original)(None, query, query, query, None, **kwargs)+ return seen.get("kernel_options")+++def test_a_call_that_needs_a_backward_forces_the_main_flex_kernel():+ assert _call_with(_GradTensor((2, 16, 121, 128), True)) == {"FORCE_USE_FLEX_ATTENTION": True}+ # Above 256 both sets of options apply.+ got = _call_with(_GradTensor((2, 16, 121, 512), True))+ assert got["FORCE_USE_FLEX_ATTENTION"] is True and got["BLOCK_M"] == 32+++def test_inference_keeps_flex_decoding():+ import torch++ assert _call_with(_GradTensor((2, 16, 1, 128), False)) is None+ with torch.no_grad():+ assert _call_with(_GradTensor((2, 16, 121, 128), True)) is None+ assert _call_with(_GradTensor((2, 16, 121, 128), True, device_type = "cpu")) is None+++def test_an_explicit_backend_is_not_combined_with_the_legacy_knob():+ # torch refuses BACKEND together with FORCE_USE_FLEX_ATTENTION.+ got = _call_with(+ _GradTensor((2, 16, 121, 128), True), kernel_options = {"BACKEND": "TRITON_DECODE"}+ )+ assert got == {"BACKEND": "TRITON_DECODE"}+ got = _call_with(+ _GradTensor((2, 16, 121, 128), True), kernel_options = {"FORCE_USE_FLEX_ATTENTION": False}+ )+ assert got == {"FORCE_USE_FLEX_ATTENTION": False}+++def test_compiled_flex_backward_matches_eager_for_a_short_static_batch():+ # B > 1, static query length below 128, 16 * 121 floats per batch (not a multiple of 32): the+ # shape where flex_decoding's padded logsumexp gave gradients off by 10x or more.+ import torch++ if not torch.cuda.is_available():+ pytest.skip("needs a CUDA device for the Triton flex kernels")+ try:+ from torch.nn.attention.flex_attention import create_block_mask+ except ImportError:+ pytest.skip("torch has no flex_attention")+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS++ torch._dynamo.reset()+ B, H, S, D = 2, 16, 121, 64+ gen = torch.Generator(device = "cuda").manual_seed(0)+ q, k, v, grad = (+ torch.randn(B, H, S, D, device = "cuda", dtype = torch.bfloat16, generator = gen)+ for _ in range(4)+ )+ mask = create_block_mask(+ lambda b, h, qi, ki: qi >= ki, B = B, H = None, Q_LEN = S, KV_LEN = S, device = "cuda"+ )+ module = torch.nn.Module().train()++ def grads(eager):+ qq, kk, vv = (t.clone().requires_grad_(True) for t in (q, k, v))+ if eager:+ from torch.nn.attention.flex_attention import flex_attention+ out = flex_attention(qq, kk, vv, block_mask = mask, scale = D**-0.5).transpose(1, 2)+ else:+ out, _ = ALL_ATTENTION_FUNCTIONS["flex_attention"](+ module, qq, kk, vv, mask, scaling = D**-0.5+ )+ out.backward(grad.transpose(1, 2))+ return [t.grad.float() for t in (qq, kk, vv)]++ for name, got, want in zip("qkv", grads(eager = False), grads(eager = True)):+ err = ((got - want).abs().max() / want.abs().max()).item()+ assert err < 0.05, f"d{name} relative error {err:.3g} vs eager flex attention"diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.pyindex 142b2f37914..b79e67ccccf 100644--- a/unsloth/models/_utils.py+++ b/unsloth/models/_utils.py@@ -590,8 +590,19 @@ def _flex_kernel_options_for_head_dim(head_dim):return dict(_FLEX_LARGE_HEAD_DIM_KERNEL_OPTIONS)+def _flex_call_needs_backward(query, key, value):+ """True when this flex call is recorded for autograd on an accelerator."""+ try:+ if not torch.is_grad_enabled() or query.device.type == "cpu":+ return False+ return any(getattr(t, "requires_grad", False) for t in (query, key, value))+ except Exception:+ return False++def _wrap_flex_attention_forward(flex_attention_forward):- """Add kernel_options to a registered `flex_attention` function, for large head dims only."""+ """Add kernel_options to a registered `flex_attention` function: block sizes above head_dim+ 256, and the main flex kernel for calls that need a backward."""if getattr(flex_attention_forward, "_unsloth_flex_kernel_options", False):return flex_attention_forward@@ -606,6 +617,14 @@ def _wrap_flex_attention_forward(flex_attention_forward):)except Exception:kernel_options = None+ # Inductor picks flex_decoding for a static query length below 128. Its logsumexp gets a+ # padded batch stride (comprehensive_padding) that the backward template ignores, so every+ # batch row after the first reads a shifted LSE and the gradients blow up.+ if _flex_call_needs_backward(query, key, value) and "BACKEND" not in (+ kwargs.get("kernel_options") or {}+ ):+ kernel_options = kernel_options or {}+ kernel_options["FORCE_USE_FLEX_ATTENTION"] = Trueif kernel_options is not None:# A caller that already asked for something keeps it: only fill the gaps.requested = kwargs.get("kernel_options") or {}@@ -619,7 +638,7 @@ def _wrap_flex_attention_forward(flex_attention_forward):def patch_flex_attention_kernel_options():- """Wrap the registered flex_attention to pass kernel_options above head_dim 256.+ """Wrap the registered flex_attention to pass the kernel_options of _wrap_flex_attention_forward.Unconditional, since explicit requests and _FLEX_PREFERRED_MODELS reach flex too. Returns Truewhen the registered function is wrapped.