Skip to content

[GLM 5.3 Flash] Fix NaN gradients in chunked KDA - #48455

Merged
vasqu merged 11 commits into
huggingface:mainfrom
imvladikon:fix/glm5-next-kda-decay-mask-overflow
Sep 7, 2026
Merged

vasqu merged 11 commits into
huggingface:mainfrom
imvladikon:fix/glm5-next-kda-decay-mask-overflow

Conversation

@imvladikon

@imvladikon imvladikon commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

CPU CI GPU run-slow

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, g has shape [B, H, N, C, D].

The current fallback computes pairwise decay as:

decay_mask = (g.unsqueeze(-2) - g.unsqueeze(-3)).exp()

which materializes a [B, H, N, C, C, D] tensor.

Each per-token log-decay is non-positive, so cumulative g is 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 -5 and chunk_size=64, the largest non-causal difference can approach:

5 * (64 - 1) = 315

while float32 exp() overflows at approximately 88.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 evaluates 0 * inf, producing NaN gradients.

The pairwise representation is also very expensive in memory. For GLM-5.3-Flash (64 linear heads, head_dim=128, chunk_size=64), the decay tensor alone is approximately:

  • 0.25 GiB at sequence length 128
  • 8 GiB at sequence length 4096

before 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, Aqk and Akk, blockwise.

For a causal cross-block where every row comes after every column, choose a cumulative-decay reference A = g[mid]. Then:

exp(g_i - g_j)
= exp(g_i - A) * exp(A - g_j)

Since cumulative g is non-increasing and j < mid <= i, both exponent arguments are non-positive:

g_i - A <= 0
A - g_j <= 0

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:

b_gqn = exp2(b_g1 - b_gn1)
b_kgt = transpose(k0 * exp2(b_gn1 - b_g0))

Aqk += dot(q1 * b_gqn, b_kgt)
Akk += dot(k1 * b_gqn, b_kgt)

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:

2^(g_i - g_j)

into:

2^(g_i - ref) * 2^(ref - g_j)

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 8x8 diagonal blocks. Inside those diagonal blocks, non-causal values are masked to -inf before exp().

The two KDA products, Aqk and Akk, 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:

Approach Prototype Result Why not used
Clamp pairwise log-decays before exp() 04de6850 Fixes NaN gradients and leaves causal values unchanged under the current g <= 0 invariant It relies on the decay-sign invariant rather than causal structure and still materializes the full [B, H, N, C, C, D] tensor.
Mask non-causal entries to -inf before exp() 20801e01 Fixes the overflow exactly at the entries that are discarded; forward output is unchanged and gradients are finite This is the clean minimal numerical fix, but it still keeps the full per-channel pairwise decay tensor and therefore does not solve the memory problem.
Blockwise local-reference factorization e61f4bc2 Fixes both numerical overflow and pairwise-decay memory usage Selected. It computes the same causal Aqk/Akk products 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 additional D dimension and makes the direct pairwise representation substantially more expensive.

Validation

The implementation was compared against both:

  1. the pairwise implementation with non-causal entries masked before exp();
  2. the recurrent KDA reference.

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:

  • outputs remained finite;
  • recurrent states remained finite;
  • all gradients remained finite;
  • float32 output/state differences were on the order of 1e-7;
  • gradient differences were on the order of 1e-8;
  • bfloat16 differences were within expected matmul precision.

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:

Sequence length Implementation Saved autograd memory Peak memory Forward + backward
512 pairwise 3.39 GiB 6.47 GiB 48.2 ms
512 blockwise (block_size=8) 0.88 GiB 1.88 GiB 52.0 ms
2048 pairwise 13.54 GiB 30.05 GiB 182.9 ms
2048 blockwise (block_size=8) 3.51 GiB 8.60 GiB 80.2 ms

block_size=8 was selected from a sweep over 4, 8, 16, and 32 on the GLM-5.3-Flash attention shapes. It gave the best overall memory/runtime tradeoff in these tests.

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.
@imvladikon imvladikon changed the title [GLM5-Next] Fix NaN gradients and excessive memory use in chunked KDA [GLM 5.3 Flash] Fix NaN gradients and excessive memory use in chunked KDA Sep 1, 2026
@vasqu

vasqu commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

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)

@imvladikon

Copy link
Copy Markdown
Contributor Author

@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().
But there is a memory tradeoff because the remaining issue is that KDA has per-channel decay, as you wrote, so the analogous pairwise_decay has shape [B, H, N, C, C, D], rather than [B, H, N, C, C] as in GDN. We also cannot compute QK^T first and multiply by the decay afterwards, since the decay varies along D.
For GLM 5.3 Flash (H=64, D=128, C=64), that tensor alone is ~8 GiB at seq_len=4096. The blockwise factorization in this PR is intended to solve that second problem as well.

@vasqu

vasqu commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

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)

@imvladikon
imvladikon force-pushed the fix/glm5-next-kda-decay-mask-overflow branch from 46624b3 to 94de37e Compare September 5, 2026 15:53
@imvladikon
imvladikon force-pushed the fix/glm5-next-kda-decay-mask-overflow branch from 94de37e to 5af467f Compare September 5, 2026 15:57
@imvladikon imvladikon changed the title [GLM 5.3 Flash] Fix NaN gradients and excessive memory use in chunked KDA [GLM 5.3 Flash] Fix NaN gradients in chunked KDA Sep 5, 2026
@imvladikon

Copy link
Copy Markdown
Contributor Author

@vasqu Makes sense 👌 I’ve simplified the PR to just the NaN fix, I completely agree about preferring the kernels path. I think I happened to hit the fallback case because of the FLA resolution issue fixed in #48221, so I ended up observing the eager-path memory behavior more directly.

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.
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 vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just about the test design tbh

@imvladikon

Copy link
Copy Markdown
Contributor Author

@vasqu good points, I rewrote tests(just left only 1 simple test according to your code review comments 👌)

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See my last comment but then we can merge

@github-actions

github-actions Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: glm5_next, kimi_linear

@github-actions

github-actions Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

CI recap

Dashboard: View test results in Grafana
Latest run: 34143269116:2
Result: success | Jobs: 8 | Tests: 697 | Failures: 0 | Duration: 8m 36s

@vasqu
vasqu enabled auto-merge September 7, 2026 17:53
@vasqu
vasqu added this pull request to the merge queue Sep 7, 2026
@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

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.

Merged via the queue into huggingface:main with commit 0b179b2 Sep 7, 2026
38 checks passed
sbucaille pushed a commit to sbucaille/transformers that referenced this pull request Sep 16, 2026
* 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
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.

3 participants