Repository navigation
[GLM 5.3 Flash] Fix NaN gradients in chunked KDA - #48455
Conversation
decay_mask exponentiates pairwise differences of the cumulative log-decay before the causal mask is applied. Non-causal pairs give large positive differences (measured up to +313.9 at chunk_size=64) that overflow to inf in float32; the following masked_fill discards them in the forward pass, but the backward pass then computes 0 * inf = nan, which propagates to every parameter. Apply the mask before exp() instead, which is what the sibling chunked delta-rule models already do: Qwen3-Next masks the non-causal cumulative-decay differences with -inf ahead of the exponential, with a comment naming this very overflow. Those models keep the decay per head, so their pairwise tensor is [..., C, C] and the [C, C] mask applies directly; GLM5-Next keeps it per channel, so the tensor is [..., C, C, D] and the mask has to be broadcast over the channel axis. The mask must be strictly upper: the diagonal holds g_i - g_i = 0 and is still consumed by the intra-chunk term below. Forward output is bit-identical (max abs difference 0.0 against the current code). Verified on GLM-5.3-Flash 9B (A100, bf16): grad_norm nan -> finite, parameters with nan grads 252 -> 0. End-to-end SFT loss now decreases (3.15 -> 0.82); before the fix the optimizer step was skipped every step because the gradients were not finite, so the weights never changed.
The previous commit stops the nan gradients, but the intra-chunk term still builds an
explicit [..., chunk, chunk, head_dim] tensor of pairwise decays and reduces it with an
elementwise product. For GLM-5.3-Flash (64 linear heads, head_dim 128, chunk 64) that
tensor alone is 0.25 GiB per layer at 128 tokens and 8 GiB per layer at 4096, before any
activation is stored, which is what makes the torch path unusable rather than merely slow.
Split the chunk recursively instead. For a pair of blocks where every row index is larger
than every column index, the anchor A = g[mid] factorises exp(g_i - g_j) into
exp(g_i - A) * exp(A - g_j), so the cross-block term becomes a single matmul over head_dim
and never materialises a pairwise tensor. Because g is a cumulative sum of negative
log-decays both factors stay in [0, 1], so no positive exponent is formed at all - the
masking from the previous commit is only needed inside the small diagonal blocks. The two
products KDA needs (key/key for the UT transform, query/key for intra-chunk attention)
share the decay factors and the right-hand side, so they are computed together.
Measured on one A100, GLM-5.3-Flash linear-attention shapes (64 heads, head_dim 128,
chunk 64), bfloat16, forward plus backward through the full function:
seq 512 seq 2048
autograd peak fwd+bwd autograd peak fwd+bwd
before 3.39 6.47 48.2 ms 13.54 30.05 182.9 ms
after (8) 0.88 1.88 52.0 ms 3.51 8.60 80.2 ms
Block size 8 was picked from a sweep over 4/8/16/32 at those shapes; it is the fastest at
seq 2048 and close to the best at seq 512 while keeping the smallest memory among the fast
variants.
Outputs and gradients match the previous commit to the precision of the arithmetic used:
2e-07 relative in float32 with TF32 off, 5e-05 in bfloat16, and up to 7e-03 once TF32 is
enabled, which is the precision of the matmul itself.
|
Hmm, we recently refactored GDN in #47625, would a similar refactor with KDA already solve the overflow? (note that KDA is essentially GDN with and additional dim for the heads) |
|
@vasqu you mean applying the masking part? Yes, it solves nan gradient issue (I actually tested exactly that as an intermediate fix (20801e0): mask the non-causal g_i - g_j values to -inf before exp(). |
|
I'd love to go this step by step first, the memory issue would also apply to GDN then so I want to first make the NaN issue then memory issue Overall, we want users to mostly use hf kernels instead tbh (because the eager path will always lack in comparison) |
46624b3 to
94de37e
Compare
94de37e to
5af467f
Compare
Compare the chunked KDA path against the recurrent reference for outputs, final state and gradients under a saturated forget gate, and check that a linear attention layer still gets finite parameter gradients in that regime.
…ecay-mask-overflow
Kimi Linear inherits the linear attention layer from GLM-5.3-Flash, so its generated modeling file carries the same chunked KDA path and must be regenerated with the mask applied before the exponential.
vasqu
left a comment
There was a problem hiding this comment.
Just about the test design tbh
…r built from the shared model tester
…ecay-mask-overflow
|
@vasqu good points, I rewrote tests(just left only 1 simple test according to your code review comments 👌) |
vasqu
left a comment
There was a problem hiding this comment.
See my last comment but then we can merge
|
[For maintainers] Suggested jobs to run (before merge) run-slow: glm5_next, kimi_linear |
CI recapDashboard: View test results in Grafana |
|
The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update. |
* Fix nan gradients in GLM5-Next KDA chunked attention
decay_mask exponentiates pairwise differences of the cumulative log-decay before the
causal mask is applied. Non-causal pairs give large positive differences (measured up to
+313.9 at chunk_size=64) that overflow to inf in float32; the following masked_fill
discards them in the forward pass, but the backward pass then computes 0 * inf = nan,
which propagates to every parameter.
Apply the mask before exp() instead, which is what the sibling chunked delta-rule models
already do: Qwen3-Next masks the non-causal cumulative-decay differences with -inf ahead
of the exponential, with a comment naming this very overflow. Those models keep the decay
per head, so their pairwise tensor is [..., C, C] and the [C, C] mask applies directly;
GLM5-Next keeps it per channel, so the tensor is [..., C, C, D] and the mask has to be
broadcast over the channel axis. The mask must be strictly upper: the diagonal holds
g_i - g_i = 0 and is still consumed by the intra-chunk term below.
Forward output is bit-identical (max abs difference 0.0 against the current code).
Verified on GLM-5.3-Flash 9B (A100, bf16): grad_norm nan -> finite, parameters with nan
grads 252 -> 0. End-to-end SFT loss now decreases (3.15 -> 0.82); before the fix the
optimizer step was skipped every step because the gradients were not finite, so the
weights never changed.
* Compute the GLM5-Next KDA decay products blockwise instead of pairwise
The previous commit stops the nan gradients, but the intra-chunk term still builds an
explicit [..., chunk, chunk, head_dim] tensor of pairwise decays and reduces it with an
elementwise product. For GLM-5.3-Flash (64 linear heads, head_dim 128, chunk 64) that
tensor alone is 0.25 GiB per layer at 128 tokens and 8 GiB per layer at 4096, before any
activation is stored, which is what makes the torch path unusable rather than merely slow.
Split the chunk recursively instead. For a pair of blocks where every row index is larger
than every column index, the anchor A = g[mid] factorises exp(g_i - g_j) into
exp(g_i - A) * exp(A - g_j), so the cross-block term becomes a single matmul over head_dim
and never materialises a pairwise tensor. Because g is a cumulative sum of negative
log-decays both factors stay in [0, 1], so no positive exponent is formed at all - the
masking from the previous commit is only needed inside the small diagonal blocks. The two
products KDA needs (key/key for the UT transform, query/key for intra-chunk attention)
share the decay factors and the right-hand side, so they are computed together.
Measured on one A100, GLM-5.3-Flash linear-attention shapes (64 heads, head_dim 128,
chunk 64), bfloat16, forward plus backward through the full function:
seq 512 seq 2048
autograd peak fwd+bwd autograd peak fwd+bwd
before 3.39 6.47 48.2 ms 13.54 30.05 182.9 ms
after (8) 0.88 1.88 52.0 ms 3.51 8.60 80.2 ms
Block size 8 was picked from a sweep over 4/8/16/32 at those shapes; it is the fastest at
seq 2048 and close to the best at seq 512 while keeping the smallest memory among the fast
variants.
Outputs and gradients match the previous commit to the precision of the arithmetic used:
2e-07 relative in float32 with TF32 off, 5e-05 in bfloat16, and up to 7e-03 once TF32 is
enabled, which is the precision of the matmul itself.
* Revert the blockwise decay rewrite and keep only the mask-before-exp NaN fix
* Add regression tests for the chunked KDA decay mask
Compare the chunked KDA path against the recurrent reference for outputs, final state and gradients under a saturated forget gate, and check that a linear attention layer still gets finite parameter gradients in that regime.
* Propagate the KDA decay mask fix to kimi_linear
Kimi Linear inherits the linear attention layer from GLM-5.3-Flash, so its generated modeling file carries the same chunked KDA path and must be regenerated with the mask applied before the exponential.
* Narrow the KDA regression test down to a single linear attention layer built from the shared model tester
* Drop the per-parameter subtest from the KDA regression test
What does this PR do?
Hi @vasqu thank you for your work, I found an issue (using my dummy 9B model https://huggingface.co/imvladikon/GLM-5.3-Flash-9B-Surgery-Dummy with the same architecture as glm 5.3 flash) and this PR fixes an overflow in that path and also reduces the pairwise decay memory cost.
Problem
GLM5.3 Flash uses per-channel KDA decay. After the intra-chunk cumulative sum,
ghas shape[B, H, N, C, D].The current fallback computes pairwise decay as:
which materializes a
[B, H, N, C, C, D]tensor.Each per-token log-decay is non-positive, so cumulative
gis non-increasing. For causal pairs (i >= j),g_i - g_j <= 0, but for non-causal pairs (j > i) the difference is positive.With the default lower bound
-5andchunk_size=64, the largest non-causal difference can approach:while float32
exp()overflows at approximately88.7.The causal mask was applied only after the exponential. The forward output therefore remained finite because the overflowing entries were discarded, but autograd still propagated through the overflowing
exp(). On those masked entries the backward effectively evaluates0 * inf, producingNaNgradients.The pairwise representation is also very expensive in memory. For GLM-5.3-Flash (
64linear heads,head_dim=128,chunk_size=64), the decay tensor alone is approximately:0.25 GiBat sequence length1288 GiBat sequence length4096before accounting for the rest of the activations.
Fix
Instead of materializing the full per-channel pairwise decay tensor, compute the two causal products required by KDA,
AqkandAkk, blockwise.For a causal cross-block where every row comes after every column, choose a cumulative-decay reference
A = g[mid]. Then:Since cumulative
gis non-increasing andj < mid <= i, both exponent arguments are non-positive:The weighted decay product can therefore be evaluated exactly as a matrix multiplication over
head_dim, without constructing[rows, columns, head_dim]and without ever forming a positive cross-block exponent.This is the same local-reference factorization used by the production FLA KDA kernels.
FLA KDA:
https://github.com/fla-org/flash-linear-attention/blob/35dceaee5408e69a555fec34cb215c93c375dabe/fla/ops/kda/chunk_intra.py
The relevant computation there is equivalent to:
Meta's KDA implementation documents the same decomposition explicitly:
https://github.com/meta-pytorch/attention-gym/blob/6ee58c2a437d99d93533a85b9ccb6a955358cf20/attn_gym/linear/kda/fwd/triton/chunk_kda_fwd_intra_sub_chunk_forloop.py
It describes splitting:
into:
so that the decay-weighted interaction becomes a matrix multiplication.
The Kimi Linear paper also uses secondary chunking for numerical stability in KDA:
https://arxiv.org/abs/2510.26692
The official Kimi Linear repository points to FLA as the open-source KDA kernel implementation:
https://github.com/MoonshotAI/Kimi-Linear
The PyTorch fallback in this PR applies the same factorization recursively over the causal triangle and keeps the direct pairwise formulation only inside small
8x8diagonal blocks. Inside those diagonal blocks, non-causal values are masked to-infbeforeexp().The two KDA products,
AqkandAkk, share the same decay factors and key-side term and are computed together.Alternatives considered
Before switching to the blockwise formulation, two smaller fixes were tested:
exp()04de6850g <= 0invariant[B, H, N, C, C, D]tensor.-infbeforeexp()20801e01e61f4bc2Aqk/Akkproducts using the local-reference factorization already used by FLA KDA, while only using direct pairwise evaluation inside small diagonal blocks.The mask-before-
exp()version is sufficient if the only objective is to prevent NaN gradients. The blockwise version is used because the same pairwise representation causing the numerical issue is also the dominant memory cost of the PyTorch fallback.Related Transformers implementation
Qwen3-Next avoids the numerical part of the same problem by masking non-causal cumulative-decay differences before exponentiation:
https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen3_next/modeling_qwen3_next.py
Its decay is scalar per head, so the pairwise tensor is only
[B, H, N, C, C]. GLM5-Next has a separate decay for each head channel, which introduces the additionalDdimension and makes the direct pairwise representation substantially more expensive.Validation
The implementation was compared against both:
exp();Across float32 and bfloat16 tests, including partial chunks, different sequence/chunk sizes,
D != V, L2-normalized Q/K, initial recurrent states, and extreme negative decay values:1e-7;1e-8;The original implementation reproduces the failure mode directly: the forward result remains finite while gradients become NaN because non-causal pairwise exponentials overflow before masking.
A100, bfloat16,
H=64,head_dim=128,chunk_size=64, full forward + backward:block_size=8)block_size=8)block_size=8was selected from a sweep over4,8,16, and32on the GLM-5.3-Flash attention shapes. It gave the best overall memory/runtime tradeoff in these tests.