Skip to content

[Triton/Gluon] [Bugfix] unified_attention: mask the V page tail past seqused_k (NaN/Inf leak) - #6475

Open
aaab8b wants to merge 1 commit into
ROCm:mainfrom
aaab8b:fix/unified-attention-v-tail-mask
Open

aaab8b wants to merge 1 commit into
ROCm:mainfrom
aaab8b:fix/unified-attention-v-tail-mask

Conversation

@aaab8b

@aaab8b aaab8b commented Oct 13, 2026

Copy link
Copy Markdown

Summary

On the TILE_SIZE == BLOCK_SIZE path (non-shuffled KV cache), kernel_unified_attention_2d and kernel_unified_attention_3d load the whole KV page, including the slots past seqused_k in a sequence's last page. Those slots get softmax weight 0, but they still go through P @ V, and 0 * NaN = NaN, 0 * Inf = NaN. A single non-finite value left in a page tail therefore turns the attention output of every query that reads that page into NaN.

This PR masks the V load to the sequence length on that path (K keeps the full-page load) and adds a regression test.

This is the default path, not a corner case: on gfx942 and gfx950, a 64-token page with head_dim <= 128 gives TILE_SIZE == BLOCK_SIZE == 64 for every 2D and 3D Triton call, and vLLM's ROCM_AITER_UNIFIED_ATTN backend picks a 64-token page by default.

Motivation

We hit this in RL training (Qwen3-4B, vLLM with speculative decoding, MI308X): the target model's attention output occasionally contained NaN. In every captured input, Q and all K/V inside seqused_k were finite. The only non-finite values sat in KV-cache slots past seqused_k in the last page, and the same inputs through vLLM's own Triton attention backend gave finite output.

A page tail can hold anything: stale KV from a recycled page, KV of rejected draft tokens, or uninitialized memory. Whatever is there, slots past seqused_k must not affect the output. Why the tails held NaN/Inf in our runs is a separate issue that we are still tracking down.

Root cause

In the masked tile loop of both kernels (aiter/ops/triton/_triton_kernels/attention/unified_attention.py), the tile mask is dropped when a tile is exactly one page:

for j in range(masked_tile_start, tile_end):
    seq_offset = j * TILE_SIZE + offs_t
    # to reduce the masking effect when not needed
    if TILE_SIZE == BLOCK_SIZE:
        tile_mask = tl.full((1,), 1, dtype=tl.int1)
    else:
        tile_mask = seq_offset < max_seq_prefix_len
    ...
        v_mask = v_dim_mask[None, :] & tile_mask[:, None]
    ...
        k_mask = dim_mask[:, None] & tile_mask[None, :]

With TILE_SIZE == BLOCK_SIZE, tile j is page j, so every address stays inside an allocated page. But the slots of the last page past seqused_k are allocated without belonging to the sequence.

  • A non-finite K tail is harmless. It only poisons its column of S, and S = tl.where(... & seq_mask, S, float("-inf")) replaces that whole column. That is a select, not a multiply, so the NaN never reaches the result.
  • A non-finite V tail is not. P is exactly 0 for those slots, but acc = tl.dot(P.to(V.dtype), V, acc=acc) computes 0 * NaN = NaN. The NaN survives acc / L and, on the 3D path, the weighted sum in reduce_segments.

When the path is taken. TILE_SIZE is derived as max(TILE_SIZE_MIN, min(TILE_SIZE_MAX, next_pow2(block_size))) (compute_tile_params).

  • 64-token page, head_dim <= 128: the gfx942 and gfx950 tables give TILE_SIZE = 64 for every 2D and kv_split entry, so every call takes this path.
  • 16- or 32-token page: decode (Q_LEQ_1) and 3D calls follow the page size and also take it. 2D calls with q > 1 use TILE_SIZE = 64 and the masked branch.

Why it went unnoticed. generate_data in test_unified_attention.py fills the whole cache with randn, so page tails are always finite, and finite × 0 = 0. vLLM's upstream kernel, which this one is adapted from, masks both K and V with seq_offset < max_seq_prefix_len and has no such shortcut.

The shortcut has been there since unified attention was added in #1148. The kernel file is byte-identical from v0.1.22 through v0.1.24.post1, and current main is affected.

Minimal reproducer

Default configs, nothing monkeypatched. One NaN or Inf is written to the first V slot past seqused_k; everything the sequence actually owns is finite. The reference reads only the kv_len tokens of the sequence.

"""KV slots past seqused_k leak into Triton unified_attention output.

Default configs only (nothing is monkeypatched). On gfx942/gfx950 a 64-token
page with head_dim 128 gives TILE_SIZE == BLOCK_SIZE == 64 for both cases.
"""

import torch

from aiter.ops.triton.attention.unified_attention import unified_attention

PAGE, HQ, HK, D = 64, 8, 1, 128


def run(q_len, kv_len, poison):
    torch.manual_seed(0)
    pages = (kv_len + PAGE - 1) // PAGE
    q = torch.randn(q_len, HQ, D, dtype=torch.bfloat16, device="cuda")
    k = torch.randn(pages, PAGE, HK, D, dtype=q.dtype, device="cuda")
    v = torch.randn_like(k)
    # The last page holds kv_len % PAGE tokens of this sequence; the slots after
    # them belong to nobody. Put one non-finite value in the first such V slot.
    v[pages - 1, kv_len % PAGE, 0, 0] = poison

    out = torch.empty_like(q)
    unified_attention(
        q=q,
        k=k,
        v=v,
        out=out,
        cu_seqlens_q=torch.tensor([0, q_len], dtype=torch.int32, device="cuda"),
        max_seqlen_q=q_len,
        seqused_k=torch.tensor([kv_len], dtype=torch.int32, device="cuda"),
        max_seqlen_k=kv_len,
        softmax_scale=D**-0.5,
        causal=True,
        window_size=(-1, -1),
        block_table=torch.arange(pages, dtype=torch.int32, device="cuda")[None],
        softcap=0.0,
        q_descale=None,
        k_descale=None,
        v_descale=None,
        backend="triton",
    )

    # Reference: causal attention over the kv_len logical tokens only.
    key = k.flatten(0, 1)[:kv_len].float().repeat_interleave(HQ // HK, 1)
    val = v.flatten(0, 1)[:kv_len].float().repeat_interleave(HQ // HK, 1)
    score = torch.einsum("qhd,khd->hqk", q.float() * D**-0.5, key)
    future = torch.ones(q_len, kv_len, dtype=torch.bool, device="cuda")
    score = score.masked_fill(future.triu(kv_len - q_len + 1), float("-inf"))
    ref = torch.einsum("hqk,khd->qhd", score.softmax(-1), val)

    nonfinite = int((~torch.isfinite(out)).sum())
    close = torch.allclose(out.float(), ref, atol=1.5e-2, rtol=1e-2)
    return nonfinite, close


if __name__ == "__main__":
    ok = True
    for name, q_len, kv_len in [("2D, q=8 kv=71", 8, 71), ("3D, q=1 kv=1000", 1, 1000)]:
        for poison in (float("nan"), float("inf")):
            nonfinite, close = run(q_len, kv_len, poison)
            ok &= nonfinite == 0 and close
            print(
                f"{name:16s} V page tail = {poison!s:4s} -> "
                f"non-finite outputs: {nonfinite:3d}, matches reference: {close}"
            )
    print(
        "PASS" if ok else "FAIL: the KV page tail past seqused_k leaked into the output"
    )
    raise SystemExit(0 if ok else 1)

Output on MI308X with AITER_TRITON_ONLY=1 python repro_ua_v_page_tail.py:

# main (cc7099335)
2D, q=8 kv=71    V page tail = nan  -> non-finite outputs:  64, matches reference: False
2D, q=8 kv=71    V page tail = inf  -> non-finite outputs:  64, matches reference: False
3D, q=1 kv=1000  V page tail = nan  -> non-finite outputs:   8, matches reference: False
3D, q=1 kv=1000  V page tail = inf  -> non-finite outputs:   8, matches reference: False
FAIL: the KV page tail past seqused_k leaked into the output        # exit code 1

# this PR
2D, q=8 kv=71    V page tail = nan  -> non-finite outputs:   0, matches reference: True
2D, q=8 kv=71    V page tail = inf  -> non-finite outputs:   0, matches reference: True
3D, q=1 kv=1000  V page tail = nan  -> non-finite outputs:   0, matches reference: True
3D, q=1 kv=1000  V page tail = inf  -> non-finite outputs:   0, matches reference: True
PASS                                                                # exit code 0

The 64 non-finite outputs are 8 query tokens × 8 query heads × the one poisoned head-dim lane; the 3D case has a single query token, hence 8. Every value in the sequence is finite, but the output still contains NaN.

Fix

     for j in range(masked_tile_start, tile_end):
         seq_offset = j * TILE_SIZE + offs_t
-        # to reduce the masking effect when not needed
         if TILE_SIZE == BLOCK_SIZE:
+            # The score mask discards K-tail columns after QK, but an unmasked
+            # non-shuffled V tail can still poison PV through 0 * NaN/Inf.
             tile_mask = tl.full((1,), 1, dtype=tl.int1)
+            v_tile_mask = seq_offset < seq_len
         else:
             tile_mask = seq_offset < max_seq_prefix_len
+            v_tile_mask = tile_mask
 ...
-            v_mask = v_dim_mask[None, :] & tile_mask[:, None]
+            v_mask = v_dim_mask[None, :] & v_tile_mask[:, None]

The 3D kernel gets the same change.

  • Masked slots are never read. tl.load returns other=0.0 for them, so the tail contributes 0 * 0 no matter what the page holds. This is not a nan_to_num: a NaN computed from tokens inside the sequence still propagates.
  • K is unchanged. It keeps the full-page load, because the score mask already discards its tail.
  • seq_len is the boundary. Slots inside the sequence but beyond a q-block's causal prefix hold valid, finite KV and get P = 0, so max_seq_prefix_len is not needed here.
  • No numeric change on clean inputs. With finite page tails, the output is bitwise identical to main on every benchmark shape below.

Test Plan

Hardware: AMD Instinct MI308X (gfx942), ROCm 7.14, PyTorch 2.12, Triton 3.7, Python 3.12, run with AITER_TRITON_ONLY=1. I have no gfx950 or gfx1250 hardware, so those archs rely on CI.

  1. The reproducer above, on main and on this PR.
  2. Default path with realistic shapes: 32 q / 8 kv heads, head_dim 128, bf16, a random block table, and one NaN in the first tail slot of each sequence's last page. Nothing is forced; aiter picks the route, TILE_SIZE and NUM_SEGMENTS. Pages of 64 and 16 tokens.
  3. New regression test test_triton_unified_attn_masks_nonfinite_kv_page_tail:
    • Cases: 2D, 3D with 1 segment, and 3D with 4 segments, each with NaN and Inf.
    • What it pins: TILE_SIZE == BLOCK_SIZE and the route, so every arch exercises this path.
    • What it poisons: both the K and the V tail.
  4. Existing tests: pytest op_tests/triton_tests/attention/test_unified_attention.py -k "not gluon".
  5. Performance, main vs. this PR.
  6. black 26.3.0 and ruff 0.15.7 on the changed files.

Test Result

  1. Reproducer: fails on main (4/4 cases produce NaN, exit code 1) and passes with this PR (4/4).

  2. Default path: NaN count in the output, main → this PR.

    Scenario Route aiter picks 64-token page 16-token page
    spec-verify, q=4 × 4 seqs, kv <= 512 2D 512 → 0 0 → 0 (TILE_SIZE 64 != page, masked branch)
    spec-verify, q=4 × 2 seqs, kv > 512 3D (16 / 64 segments) 256 → 0 256 → 0
    decode, q=1 × 4 seqs, kv <= 512 2D 128 → 0 128 → 0
    decode, q=1 × 2 seqs, kv > 512 3D (16 / 64 segments) 64 → 0 64 → 0
    chunked prefill, q=100, kv=300 2D 1408 → 0 0 → 0

    In the chunked-prefill row, only 44 of the 100 query tokens are hit: exactly those whose causal range reaches the last page. Poisoning the K tail instead of the V tail gives 0 NaN on main and on this PR in every row.

  3. Regression test: 6/6 fail against main's kernel with KV page tail leaked into the output, and 6/6 pass with this PR.

  4. Existing tests: 1128 passed, 0 failed, 1120 skipped.

    • 1024 shuffled-cache cases need the gfx950/gfx1250 Gluon 2D kernel.
    • 96 test_triton_unified_attn_3d cases are gfx950/gfx1250 only.
  5. Performance: MI308X, kernel time with triton.testing.do_bench_cudagraph. Both kernels ran in the same process, swapped in the order main / PR / PR / main. A second full run agreed with this one within 0.15 percentage points on every shape.

    Shape (32 q / 8 kv heads, D=128, bf16) Path main (µs) this PR (µs) Δ
    decode, bs=8, kv=4k 3D, TILE 64, 32 segments 138.3 137.2 -0.8%
    decode, bs=64, kv=2k 2D, TILE 64 607.0 594.3 -2.1%
    decode, bs=256, kv=1k 2D, TILE 64 1185.7 1163.9 -1.8%
    spec-verify, q=4, bs=32, kv=2k 2D, TILE 64 294.2 300.5 +2.1%
    chunked prefill, q=512, kv=4k 2D, TILE 64 485.2 474.8 -2.1%
    prefill, q=kv=4k 2D, TILE 64 1650.9 1642.5 -0.5%
    decode, bs=8, kv=4k, 16-token page 3D, TILE 16, 32 segments 122.3 122.8 +0.4%
  6. Lint: black and ruff are clean.

Known limitations and follow-ups

  • Shuffled KV cache. The shuffled branch of the same loops loads the page with no mask at all (k_mask = v_mask = None), so the same 0 * NaN reasoning applies. It is not changed here: gfx942 does not exercise that layout, and I could not test it. A post-load tl.where(seq_offset[:, None] < seq_len, V, 0.0) would be the equivalent fix.
  • Gluon kernels (gfx950, gfx1250). They have a similar one-page-per-tile fast path. I have not checked them.
  • [Triton/Gluon] Restructure Unified Attention Kernel (merging 2d/3d and modularization) #6337. It restructures this kernel and keeps the same shortcut in the new tile_mask() helper, where K and V share one mask. Whichever PR lands first, the other needs to keep a separate V mask; we are happy to rebase.

Authors

xiongxuyang, bingzhaodong

Submission Checklist

…seqused_k

On the TILE_SIZE == BLOCK_SIZE path, kernel_unified_attention_2d and
kernel_unified_attention_3d load the whole KV page, including the slots
past seqused_k in a sequence's last page. Those slots get softmax weight
0, but 0 * NaN = NaN in P @ V, so one NaN/Inf left in a page tail turns
the output of every query that reads that page into NaN.

Mask the V load to seq_len on that path. K keeps the full-page load: its
tail columns are already replaced with -inf by the score mask.

Add test_triton_unified_attn_masks_nonfinite_kv_page_tail, which writes
NaN/Inf past seqused_k and runs the 2D, 3D and split-KV 3D paths.

Signed-off-by: bingzhaodong <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the gfx1201 ROCm runner
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 6475 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

@aaab8b
aaab8b marked this pull request as ready for review October 13, 2026 08:22
@aaab8b
aaab8b requested a review from a team October 13, 2026 08:22
@Boss2002n
Boss2002n requested a balanced review from Copilot October 13, 2026 09:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The regression test bypasses production config resolution by hardcoding tuning parameters.

1 open finding
What changed in this PR

Fixes non-finite KV page-tail values contaminating Triton unified-attention output.

Changes:

  • Masks V loads beyond seqused_k in 2D and 3D kernels.
  • Adds NaN/Inf regression coverage for unsplit and split paths.
File Description
aiter/​ops/​triton/​_triton_kernels/​attention/​unified_attention.py Masks non-shuffled V page tails.
op_tests/​triton_tests/​attention/​test_unified_attention.py Adds page-tail regression tests.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +990 to +993
config["TILE_SIZE"] = block_size
seen_tile_sizes.append(block_size)
if op == "kv_split":
config["NUM_SEGMENTS"] = num_segments
@cagrikymk

Copy link
Copy Markdown
Contributor

@aaab8b This is a nice catch!
I assume there is a vllm kernel that writes NaNs to kv cache? Not sure if this indicates some other issue where a kernel writes to an address it is not supposed to (OOB issue).

Regardless, this is something we probably need to address.

Do you have access to any mi355 machine to check perf there as well? If not, I can also run some benchmarks.

Given you skip masking for K load, hopefully this reduces the masking ops needed in the loop. When paired with splitting the masked loop, I think it should be okay in terms of perf.

@aaab8b

aaab8b commented Oct 21, 2026

Copy link
Copy Markdown
Author

@aaab8b This is a nice catch! I assume there is a vllm kernel that writes NaNs to kv cache? Not sure if this indicates some other issue where a kernel writes to an address it is not supposed to (OOB issue).

Regardless, this is something we probably need to address.

Do you have access to any mi355 machine to check perf there as well? If not, I can also run some benchmarks.

Given you skip masking for K load, hopefully this reduces the masking ops needed in the loop. When paired with splitting the masked loop, I think it should be okay in terms of perf.

@cagrikymk Sorry for the late reply! Our team had a site building activity and I have forgot to check reply from github. I don't have a certain 355 cluster to use right now. Can you run the benchmarks for me? Thanks a lot!

@cagrikymk

cagrikymk commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

I see some regressions on MI355.

By head size mean Δ
D = 64 −0.06%
D = 128 −1.32%
D = 256 +27.14%

The overall median Δ is −0.04%; the mean is pulled up entirely by the D=256 cases.

Regressions over 5%

phase kv bs D SWA kernel base (µs) fix (µs) Δ
decode 32013 32 256 off 3d+reduce 1244.0 2502.8 +101.2%
decode 32013 32 256 128 2d 12.7 31.1 +144.3%
decode 32013 32 256 1024 2d 47.1 152.1 +222.7%
decode 32013 128 256 off 3d+reduce 4762.2 9757.0 +104.9%
decode 32013 128 256 128 2d 42.2 106.5 +152.3%
decode 32013 128 256 1024 2d 183.6 594.9 +223.9%
spec4 32013 32 256 off 3d+reduce 2208.5 5146.4 +133.0%
spec4 32013 128 128 off 2d 3702.9 4029.7 +8.8%

Measurement noise (A/B spread) for these rows is 0.07–1.7%.

Root cause of the D=256 regression: register spills

ISA dumped from the compiled kernels (isa/, produced by dump_isa.py):

Kernel / case base VGPRs fix VGPRs fix VGPR spills fix scratch (B) fix scratch instrs
2d, decode D=256 SWA 128 193 256 35 144 58
3d, decode D=256 197 256 36 148 81
3d, spec4 D=256 197 256 36 148 81
2d, decode D=128 SWA 128 154 152 0 0 0
3d, decode D=128 144 136 0 0 0
2d, spec4 D=128 186 166 0 0 0
2d, prefill D=128 216 232 0 0 0
3d, decode D=64 108 126 0 0 0
2d, spec4 D=64 100 104 0 0 0

@github-actions

Copy link
Copy Markdown
Contributor

No activity for 15 days, so this is now labelled stale. A push or a comment clears it; keep-open exempts it. Nothing is closed automatically.

@github-actions github-actions Bot added the stale The PR hasn't been updated in 2 weeks label Nov 13, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stale The PR hasn't been updated in 2 weeks Triton/Gluon

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants