Repository navigation
[HIP] [Bugfix] paged_attention_ragged: scale FP8 softmax probabilities into the e4m3 normal range - #5642
Conversation
… the e4m3 normal range
On the FP8 KV-cache path the softmax probabilities are normalized to sum = 1
within a partition and only then cast to e4m3 for the P*V mfma
(pa_kernels.cuh:586-588 computes inv_sum_scale, :633-647 applies it before
__builtin_amdgcn_cvt_pk_fp8_f32, :794 consumes the result). With the default
partition_size = 256 and a near-uniform attention distribution every probability
lands at ~2^-8, which is SUBNORMAL in e4m3 (smallest normal 2^-6, subnormal step
2^-9) and therefore carries a relative ulp of 1/2. That injects ~15% RMS error
into P, which propagates 1:1 to the attention output.
The kAuto/bf16 branch (:596-621) keeps P in bf16, which represents 2^-8 exactly,
so only the FP8 branch is affected.
Fix: split inv_sum_scale into a pre-cast and a post-mfma factor. Rebase P to the
partition max -- making the largest probability exactly 1.0 -- scale it into the
e4m3 normal range before the cast, and fold 1/exp_sum back into the fp32
accumulator after the mfma. The two factors multiply back to inv_sum_scale
exactly, so the result is unchanged in exact arithmetic; only the rounding
improves. Instruction count, mfma count and memory traffic are unchanged.
The scale is the largest power of two inside the normal range (256 on gfx950,
128 on gfx942 where e4m3 is fnuz) rather than the range maximum: a power of two
is exact in binary, so the rescale introduces no rounding of its own, and the
headroom below the maximum keeps fp32 rounding from pushing the cast into
saturation.
This mirrors what aiter's own Gluon paged-decode kernel already does --
ops/triton/gluon/pa_decode_gluon.py:943 scales P by FP8_MAX_VALUE before the
cast with a compensating factor at :944/:975 and applies 1/exp_sums only at :990
("Scale the maximum value of value_scale to FP8_MAX_VALUE to improve the
precision of P * V", :933).
Only _paged_attention_kernel is changed. _paged_attention_kernel_EXPERIMENTAL
shares the pattern but is bf16-only (pa_ragged.py:32 requires
kv_dtype == "__hip_bfloat16"), so it never reaches the FP8 branch.
Validated on MI355X (gfx950), ROCm 7.0, same container before and after:
* op_tests/test_pa_ragged.py::test_paged_attention_ragged_glm_gqa_fp8_kv_nhd
FAIL -> PASS. It was already failing on a stock image before this change
(greatest relative difference 0.355 against a 0.03 tolerance).
* Mean relative error against an fp32 reference at head_dim 256, 1 KV head,
context 8192: 0.142 -> 0.027 at batch 1/8/32/64, a 5.2x reduction.
* BF16 path bit-identical (output checksums unchanged), BF16 error unchanged.
* Kernel time neutral within noise on both paths: FP8 13.49/14.57/35.36/59.68
-> 13.51/14.58/35.65/59.50 us; BF16 unchanged.
* 192 passed / 0 failed on a BF16 slice of test_pa_ragged.py.
The residual 0.027 is not this defect: the KV cache is genuinely FP8, and Q is
also cast to FP8 for the QK mfma (:379-409), which an fp32 emulation attributed
~0.007 to. Both are deliberate design choices, unlike the subnormal P.
Note that this op currently has no FP8-KV coverage in the main parametrized
matrix -- test_paged_attention skips every quantized-cache case for the Shomy
variant (op_tests/test_pa_ragged.py:686-688) -- and the one dedicated test uses
head_size 128 and seq_len 128, a single partition. Extending it to
multi-partition contexts and head_dim 256 would catch this class of defect.
Signed-off-by: Rita Brugarolas Brufau <[email protected]>
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
PR title tags & labels: |
6af25ad to
f712dcb
Compare
|
No activity for 15 days, so this is now labelled |
|
@zufayu @amd-ruitang3 Rebased onto current Why this one matters
The defective branch is the FP8 one specifically. SGLang selects it via Re-measured on current
|
| bs | context | main (no fix) | with fix | kernel time |
|---|---|---|---|---|
| 1 | 8 192 | 14.29% | 2.78% | 24.28 → 24.33 µs |
| 8 | 8 192 | 14.15% | 2.73% | 24.60 → 25.18 µs |
| 32 | 8 192 | 14.00% | 2.73% | 34.27 → 34.95 µs |
| 8 | 65 536 | 14.15% | 2.80% | 63.77 → 63.92 µs |
5.1x error reduction, and still timing-neutral — the largest time delta is 2.4% at bs=8 and the rest are under 1%, all within run-to-run noise. This reproduces the original measurement on this branch (0.142 → 0.027, 5.2x) on a stack three weeks newer.
The residual ~2.8% is the floor for this design: the probabilities are still cast to e4m3, they are just no longer subnormal. The KV cache itself is fp8 in both arms and in the reference, so that part cancels.
|
@rbrugaro-amd I’ve reviewed your PR. It aims to improve the robustness of FP8 attention. To make this more solid, could you add a regression test under |
|
I believe this was wrongly closed with the merge of #5715 and is still relevant. reopening |
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
The fix had no test asserting the property it restores. This adds one next to the existing GLM FP8 KV test, at seq_len 256 and 512 -- at or above the 256-token partition, where the normalized probabilities land at ~2^-8 and are subnormal in e4m3. Uses an aggregate relative error rather than elementwise assert_close, because at these lengths the output is a probability-weighted sum over seq_len values and individual errors average out: no element exceeds a 3e-2 tolerance on either side of the fix, while the aggregate separates cleanly (9.55% without the rescale, 3.40% with it, gfx950 / ROCm 7.2.4 at seq_len 512). The threshold is 6e-2, roughly midway, so it fails loudly on a regression without sitting on top of the passing value. Signed-off-by: Rita Brugarolas Brufau <[email protected]>
|
@amd-ruitang3 thanks — added The regression test
Both arms are the same kernel over the same KV values — one reading the cache as FP8, the other as BF16 upcast from that same FP8 — so the only thing measured is the in-kernel probability cast. Verified in both directions on gfx950 / ROCm 7.2.4:
and the failure is diagnostic rather than a bare tolerance miss: Why an aggregate metric rather than
|
|
@rbrugaro-amd our CI only run main in test*.py. Maybe not run @pytest. Are you sure that your test is triggered in CI? |
aiter_test.sh invokes op-tests as 'python3 <file>' and only two files are on the pytest allowlist, so every pytest-style test in this file is unreachable from CI. That includes test_paged_attention_ragged_glm_gqa_fp8_kv_nhd, added in ROCm#3609, which fails on current main at gfx950 -- it has never been red in CI because it has never been run. Calls both FP8 KV tests from __main__ so the existing invocation reaches them. They run first, ahead of the long sweep, since they are fast (~18s) and guard in-kernel precision, so a failure should surface early. pytest marks do not wrap the function, so the same definitions serve both direct calls and a pytest run. Signed-off-by: Rita Brugarolas Brufau <[email protected]>
Review feedback, and the inversion turns out to fix a real gap rather than being a style preference. csrc/include/aiter_enum.h lists the OCP archs as gfx950, gfx1201 and gfx1250, with gfx942 the only fnuz one. Keying on gfx950 and defaulting everything else to the fnuz constant therefore handed gfx1201 and gfx1250 the wrong scale. Keying on gfx942 as the exception matches that table and gives a new OCP arch the right constant by default. Also answers the other half of the comment -- why a power of two rather than the 448/240 range maximum -- with a measurement instead of an argument. On gfx950, aggregate relative error against the BF16 path at seq_len 256/512/1024 is 3.45/3.40/3.56% scaling to 256 and 3.51/3.48/3.60% scaling to 448. The ceiling is never better, so the tie-break is saturation headroom. The comment's previous lead reason -- exactness of the multiply and divide -- is true but ~2^-24 relative, negligible against e4m3 error, so it is now stated as the minor point it is. gfx950 behaviour is unchanged: the same four cells measure identically before and after the inversion, and both FP8 KV tests pass. Signed-off-by: Rita Brugarolas Brufau <[email protected]>
|
Regarding the test triggering in CI your observation was right. addressed in 65b23ef You were right — it wasn't running. aiter_test.sh invokes op-tests as python3 and only test_fhmoe.py and tuning_tests/test_fhmoe_tuner.py are on the pytest allowlist, so every @pytest-style test in test_pa_ragged.py was unreachable from CI. Worth flagging that this was not just my test: test_paged_attention_ragged_glm_gqa_fp8_kv_nhd, added in #3609, has never been executed by CI either. It fails on current main when you run it, which is why nobody has noticed. Fixed by calling both FP8 KV checks from main, so the existing invocation reaches them — no workflow change, ~18s added, and they run ahead of the long sweep so a precision failure surfaces early. Confirmed in CI on the last run, shard 7 of 8, both architectures: Both logs show the test actually executing rather than just being collected: [test] FP8 KV cache checks All 16 Standard Tests shards passed. The MI300X run matters beyond the wiring question: it is the first execution of the fnuz branch of the arch-conditional constant, which I have no hardware for locally, so the threshold is confirmed on both encodings rather than tuned to gfx950. |
Summary
On the FP8 KV-cache path,
paged_attention_raggednormalizes the softmaxprobabilities to sum = 1 within a partition and then casts them to
fp8_e4m3for the PV MFMA. With the defaultpartition_size = 256and atypical near-uniform attention distribution, every probability lands at ≈2⁻⁸ —
subnormal in e4m3 (min normal 2⁻⁶, subnormal step 2⁻⁹), where the relative
ulp is ½. The result is ~15% RMS error on
P, which propagates 1:1 to theattention output.
The BF16 path does not have this problem, and aiter's own Gluon paged-decode
kernel already implements the fix.
Reproduction
aiter's only FP8-KV test for this op fails on a stock image:
Environment: MI355X (gfx950), ROCm 7.0, torch 2.9.0a0, image
lmsysorg/sglang-rocm:v0.5.19-rocm700-mi35x-20260910+ aiter4ad99832823dde2315b361cbd3b54b1c5c12acd5.That test uses head_size 128, 8 KV heads, seq_len 128 — a single partition —
and it barely fails (3 of 24576 elements). At realistic decode contexts the
mechanism is pervasive. Measured against an fp32 PyTorch reference at
head_dim 256, 1 KV head, 4 query heads, context 8192 (32 partitions):
kv_cache_dtype"auto""fp8_e4m3"Error is flat in context length (0.140 / 0.147 / 0.149 at ctx 256 / 1024 / 4096)
— consistent with per-token independent rounding rather than an accumulation
problem — and identical for
"NHD"and"HND", so it is not a layout issue.Root cause
csrc/cpp_itfs/pa/pa_kernels.cuh::586-588—inv_sum_scale = 1/(partition_exp_sum + 1e-6) * exp(warp_max - partition_max).Pis fully normalized to sum 1.:633-647—d_out *= inv_sum_scale, then__builtin_amdgcn_cvt_pk_fp8_f32(...). The already-normalizedPis castto e4m3.
:794—gcn_mfma16x16x32_instr<__hip_fp8_e4m3, ...>consumes it.:596-621— thekAuto/bf16 branch keepsPin bf16, which represents2⁻⁸ exactly. Hence the 0.3% agreement there.
Qis also cast to fp8 on this path (:379-409), contributing a further ~0.7%.At
partition_size = 256, 100% of P values measured fall in the e4m3subnormal range, with RMS relative rounding error 0.163 — matching the observed
0.153. Raising
partition_sizeto 512 (p ≈ 2⁻⁹) drives the error to 1.04,which is the predicted behaviour if this diagnosis is right.
Attribution, by emulation
A partition-aware fp32 model with each rounding step toggled independently
(ctx 2048, partition 256; shipped kernel vs exact = 0.1534):
Adding only the two fp8 casts reproduces the shipped kernel to 0.14%.
Fix (implemented and validated)
Normalize
Pby the partition max rather than the sum — putting the largestvalue inside the e4m3 normal range — and fold
1/exp_suminto the fp32 outputafter the MFMA. Same instruction count, same MFMA, no extra memory traffic.
upstream/aiter-pa-ragged-fp8-fix.patch(54 insertions inpa_kernels.cuh)splits
inv_sum_scaleinto a pre-cast and a post-MFMA factor inside the existingif constexpr(KV_DTYPE != kAuto)branches, so the BF16 path is untouched. Thescale is the largest power of two inside the normal range (256 on gfx950,
128 on gfx942 where e4m3 is fnuz) rather than the range maximum: a power of two
is exact in binary, so the rescale introduces no rounding of its own and cannot
push the cast into saturation. The two factors multiply back to
inv_sum_scaleexactly, so the result is unchanged in exact arithmetic — only the rounding
improves.
Only
_paged_attention_kernelneeds it._paged_attention_kernel_EXPERIMENTALshares the pattern but is bf16-only (
pa_ragged.py:32requireskv_dtype == "__hip_bfloat16"), so it never reaches the fp8 branch.Validation
MI355X (gfx950), ROCm 7.0, same container before and after:
test_paged_attention_ragged_glm_gqa_fp8_kv_nhd5.2× error reduction, timing neutral to within noise, BF16 bit-identical.
Broader regression: 192 passed / 0 failed on a BF16 slice of
test_pa_ragged.py. Harness:notes/pa_fix_validate.py.The residual 0.0277 is expected and is not this defect — the KV cache is
genuinely fp8, and Q is also cast to fp8 for the QK MFMA (
:379-409), which theemulation attributed ~0.007 to. Both are deliberate design choices, unlike the
subnormal P.
This is what aiter's own Gluon kernel does, so the approach is already
established in-tree —
aiter/ops/triton/gluon/pa_decode_gluon.py::918keepsattention_probs = exp2(qk - max)unnormalized:943multiplies byFP8_MAX_VALUE(448) before the cast, with acompensating
probability_scaleat:944/:975:990applies1/exp_sumsonly after the MFMA:933, in as many words: "Scale the maximum value of value_scale toFP8_MAX_VALUE to improve the precision of P * V."
Test coverage gap
op_tests/test_pa_ragged.py:686-688— the main parametrizedtest_paged_attentionskips every quantized-cache case for the
Shomyvariant, sopaged_attention_raggedhas no FP8-KV coverage in the main matrix. The singlededicated test at
:452-514usesrtol = atol = 3e-2, head_size 128, seq_len128, and never exercises a multi-partition context or head_dim 256.
Suggest extending it to cover multi-partition contexts (≥ 1024 tokens) and
head_dim 256, which is where the defect is largest.
Impact
paged_attention_raggedis the decode attention op SGLang's aiter backend callsfor non-MLA models on ROCm
(
python/sglang/srt/layers/attention/aiter_backend.py:3312), and--kv-cache-dtype fp8_e4m3is a common production setting. Any deploymentcombining the two is running decode attention with ~15% error on the attention
probabilities.
I have not measured downstream task-accuracy impact — softmax outputs are
averages over many values and the error is zero-mean, so end-to-end damage may
be much smaller than the per-tensor number suggests. The kernel-level error is
nonetheless far outside the op's own stated tolerance.