Skip to content

[Triton] [Bugfix] unified_attention: store zero for a kv_len 0 row in the segment reduce - #8424

Draft
yuychang wants to merge 2 commits into
ROCm:mainfrom
yuychang:fix/ua-uniform-reduce-empty-row-nan
Draft

yuychang wants to merge 2 commits into
ROCm:mainfrom
yuychang:fix/ua-uniform-reduce-empty-row-nan

Conversation

@yuychang

@yuychang yuychang commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Motivation

  • A sequence with kv_len 0 has no KV segment, so the reduce loads segm_max as all -inf.
  • exp2(-inf - -inf) is NaN, so the exp sum and the whole output row are NaN.
  • The same on main: 512 of 512 values of the empty row are NaN (8 Q / 1 KV decode, 1M bound, sinks on and off).
  • The divisor tiles_per_segment is 0 for such a row, so the segment count divided by 0 (undefined in the IR).

Changes

  • aiter/ops/triton/_triton_kernels/attention/unified_attention.py, reduce_segments
    • A -inf overall maximum becomes 0 in the single-tile and the segment-block merge paths
      • Weights and the exp sum are then 0 and the existing safe divide stores 0
      • A row with a segment has a finite maximum and is unchanged
    • tiles_per_segment is clamped to at least 1 in the sliding-window and the plain branch
      • A row with kv_len 0 then gets 0 segments without dividing by 0
  • op_tests/triton_tests/attention/test_unified_attention.py: new test_triton_unified_attn_3d_empty_row_is_zero
  • Not changed: the gfx1250 Gluon reduce kernels, which have the same exp2(-inf - -inf)

Performance (if applicable)

  • The reduce gains one scalar compare and select (and a max) per program
  • Hardware and software
    • MI355X (gfx950), GPU 0, ROCm 10.0.0, torch 2.11.0+rocm10.0.0, triton 3.8.0
  • Revisions
    • Before: main fc623e7458; after: this branch fb511b99eb
  • Method
    • Script below, backend="triton", decode, bf16 Q, fp8 KV, head size 64, block size 128, 1M bound
    • triton.testing.do_bench (50 warmup, 300 rep); 3 alternating runs per revision, separate JIT caches
  • Result
    • The medians are 2-3% higher after, but the three-run ranges overlap and the GPU is shared; no change is claimed
    • Raw runs (µs), before: 72.1 / 73.2 / 75.9, 73.9 / 74.1 / 76.0, 73.3 / 72.7 / 75.6
    • Raw runs (µs), after: 75.3 / 75.8 / 73.6, 75.7 / 75.7 / 73.9, 75.8 / 75.5 / 73.0
Hardware Workload/configuration Before (µs) After (µs) Change
MI355X 8 Q / 1 KV, 8 seqs (120k + 7 x 2k) 73.2 [72.1-75.9] 75.3 [73.6-75.8] 1.03x slower (ranges overlap)
MI355X 64 Q / 8 KV, 32 seqs x 8k 74.1 [73.9-76.0] 75.7 [73.9-75.7] 1.02x slower (ranges overlap)
MI355X 16 Q / 4 KV, 16 seqs x 4k 73.3 [72.7-75.6] 75.5 [73.0-75.8] 1.03x slower (ranges overlap)
# PYTHONPATH=<aiter checkout> python3 bench.py, run from the checkout root
import sys, torch, triton
sys.path.insert(0, "op_tests/triton_tests/attention")
from test_unified_attention import generate_data, e4m3_dtype
from aiter.ops.triton.attention.unified_attention import unified_attention

CASES = [
    ("8Q/1KV 120k+7x2k", (8, 1), [(1, 120000)] + [(1, 2000)] * 7),
    ("64Q/8KV 32x8k", (64, 8), [(1, 8000)] * 32),
    ("16Q/4KV 16x4k", (16, 4), [(1, 4000)] * 16),
]
for name, heads, seq_lens in CASES:
    torch.manual_seed(0)
    (q, _, _, k, v, _, out, cu, kv_lens, _, _, scale, ws, bt, _, _, qd, kd, vd, _) = generate_data(
        seq_lens=seq_lens, num_blocks=8192, block_size=128, head_size=64, num_heads=heads,
        sliding_window=None, q_dtype=torch.bfloat16, kv_dtype=e4m3_dtype,
        out_dtype=torch.bfloat16, device="cuda")
    f = lambda: unified_attention(
        q=q, k=k, v=v, out=out, cu_seqlens_q=cu, seqused_k=kv_lens, max_seqlen_q=1,
        max_seqlen_k=1 << 20, softmax_scale=scale, causal=True, window_size=ws, block_table=bt,
        softcap=0, q_descale=qd, k_descale=kd, v_descale=vd, sinks=None, backend="triton")
    f(); torch.cuda.synchronize()
    print(name, "%.1f us" % (triton.testing.do_bench(f, warmup=50, rep=300) * 1000))

Testing

  • Unit tests added or updated
  • Performance benchmarks run
  • Tested on MI250X
  • Tested on MI300X

Documentation

  • Docstrings updated
  • User guide updated
  • Performance guide updated
  • No documentation change is needed, with the reason stated below
    • Bug fix with no API change

Dependencies

  • No new third-party dependencies added
  • New dependencies are listed and justified below

Breaking Changes

  • None. A kv_len 0 row stores 0 instead of NaN; no caller is known to rely on the NaN.

PR Self-Review

Reviewed revision

fb511b99eba5c53207b3201e45f27f19a3da9c5a

Behavior and intent

  • A kv_len 0 row of the Triton unified attention 3D path stores 0 instead of NaN. Other rows are unchanged.

Validation and unverified scope

  • MI355X (gfx950), ROCm 10.0.0, torch 2.11.0+rocm10.0.0, triton 3.8.0, GPU 0
    • New test, -k empty_row_is_zero: 24 passed with this change
      • All 24 fail on main's kernel (the empty row is not zero)
    • Whole op_tests/triton_tests/attention/test_unified_attention.py: 2818 passed, 2963 skipped, 0 failed
      • Run before one extra assertion in the new test
      • The new test was rerun after it and after the gfx942 change: 24 passed
  • Not verified
    • MI300X (gfx942) and gfx1250 runs: no such hardware here
      • The test now also runs on gfx942, where the Triton reduce is the same code, but it was not run there
    • The gfx1250 Gluon reduce kernels (reduce_segments_gluon, split rebalance): same NaN for a kv_len 0 row

PR-specific question

Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant prevents
unsupported inputs from reaching it?

  • The Triton reduce_segments runs after the 3D kernel on every arch whose decode picks the Triton reduce
    • gfx950 and gfx942 always; gfx1250 for the Gluon backend uses its own reduce (not changed)
  • Invariant: only a row with no segment has an all -inf maximum
    • A row with a segment has a finite maximum, so its result is unchanged

Changed op tests

  • op_tests/triton_tests/attention/test_unified_attention.py: new test_triton_unified_attn_3d_empty_row_is_zero
    • Decode with one kv_len 0 row; 8 Q / 1 KV, 64 Q / 8 KV and 4 Q / 1 KV
    • Head size 64 (all segments at once) and 256 (segment blocks), sinks on and off, with and without a sliding window
    • It forces the 3D path and checks that the Triton reduce ran
    • It expects the empty row to be 0 and the live rows to match a run without it
    • Not redundant: no test has a kv_len 0 row on the Triton reduce

Related: #7088

…educe

- A sequence with no KV segment (kv_len 0, e.g. a padded decode slot) loads an all -inf maximum in reduce_segments
- exp2(-inf - -inf) is NaN, so the exp sum and the whole output row came out NaN instead of 0
- Map a -inf maximum to 0 so the weights and the exp sum are 0 and the existing safe divide stores 0
- Applies to the single-tile and the segment-block merge paths; rows with a segment are unchanged
- Clamp tiles_per_segment to at least 1: for kv_len 0 it was 0, and the segment count divided by it
- Add a decode test with one kv_len 0 row (G=8 and G=4, head size 64 and 256, sinks on/off, sliding window)
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
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 Radeon R9700 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 8424 --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.

Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.

- The test only runs the Triton reduce, which gfx942 also uses, so MI300X CI should cover it
- Not run on gfx942 here (no MI300X); the body says so
@yuychang

Copy link
Copy Markdown
Contributor Author

Closing: the padded-row case it fixes is not hit on the Kimi-K3/K3.1 serving paths.

@yuychang yuychang closed this Nov 28, 2026
@yuychang

Copy link
Copy Markdown
Contributor Author

Reopening: the Kimi-K3 DSpark draft runs on unified_attention with #7088's length-aware split, and CUDA-graph padded decode slots have kv_len 0, so this keeps those rows at 0 instead of NaN.

@yuychang yuychang reopened this Nov 28, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
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 Radeon R9700 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 8424 --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.

Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant