Repository navigation
[AMD] perf: compact Triton extend-attention for ragged prefill (AMD/HIP-only) - #29677
Conversation
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
|
@valechen please run to fix linter errors for your PR. Thanks. |
4bb4b53 to
3c6ecac
Compare
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
9fc2766 to
a378248
Compare
Remove the SGLANG_PREFILL_TILE_BLOCK_M env var and derive BLOCK_M from _get_block_sizes_for_extend_attention() in TritonAttnBackend, threading it through the scheduler to PrefillAdder's tile-budget admission. This drops a user-facing knob and fixes a latent mismatch: the fixed default of 64 was wrong for head_dim=192 (DeepSeek MLA), where the kernel actually uses 128.
022d3f0 to
8b3d6c4
Compare
|
/rerun-failed-ci |
|
/rerun-failed-ci |
|
The only AMD pr ci issue (https://github.com/sgl-project/sglang/actions/runs/30872051504/job/91882062824?pr=29677#logs) is pre-existing on main: run 30816055633 (head 3953788, Aug 3) fails on the same file with the same error. The main run before it passed, so it's a flaky PD-disagg transfer on the MI35x fabric. Don't keep re-running — that job queued 12.5h before starting. Just post the main link so the merge oncall can waive it. The rest of the board is actually good. The full AMD matrix ran this time (unlike July, when the gate timed out and skipped everything), and all four of your tests passed on real HIP hardware: test_triton_attention_kernels.py passed mi300 1-gpu-small-amd part 3 |
|
@HaiShaw All PR Test Base / base-a/b/c clear. |
|
cuda CI all green |
|
To test amd stage-c (skipped for the failed stage-b) |
|
This PR includes #30407. For the experiment on how it resolves the segmentation fault, please see here. |
…during server warmup ROCM-31261: since sgl-project#29677 the first multi-request prefill after a fresh start JIT-compiles new variants of the Triton extend-attention kernel (_fwd_kernel) on every rank: `compact_batch_size` is an int argument Triton specializes when it equals 1, and the compact tile grid (ragged batches, HIP) is a constexpr. The bs=1 warmup covers neither, so ~0.9 s of compiles land in the first client's prefills. On MI355X, gpt-oss-120b TP8, QA's cold benchmark (32 x 8000 tokens): median TTFT 245 ms on 0.5.15 vs 1063 ms on 0.5.18 and 1268 ms on 0.5.21. - extend_attention: do_not_specialize compact_batch_size, so the batch size no longer selects a binary (also covers bs divisible by 16). - http_server: the warmup also prefills a uniform and a ragged pair (1 new token each) before the server reports ready; SGLANG_WARMUP_BATCHED_EXTEND=0 turns it off. Measured on 0.5.21 (088f7d8), caches wiped: cold median TTFT 1268 -> 314 ms (warm-cache 312 ms), no _fwd_kernel compiles during serving.
Motivation
This PR improves Triton extend-attention performance for ragged mixed-prefill batches by adding an optional compact query-tile launch grid.
The legacy grid is rectangular and sized by
max_len_extend:In a mixed batch, every short decode/partial-prefill row pays tile work proportional to the longest extend row. The compact path launches only the actual per-request query tiles:
and falls back to the legacy grid when compacting would not reduce launch work.
Framing — this closes a triton-vs-flash-attn gap, it is not a new technique.
The flash-attention varlen kernels already launch ragged-aware: the aiter backend calls
flash_attn_varlen_func/mha_batch_prefill_funcwith cu_seqlens (qo_indptr/kv_indptr), and their internal tile scheduler does work proportional to the sum of per-request query tiles —max_q_lenis only a scalar bound, never a grid multiplier. So the aiter/flash-attn path does not pay the rectangular penalty. Only the triton extend kernel used a literal(batch_size, head_num, cdiv(max_len_extend, BLOCK_M))grid. This PR brings the triton extend kernel up to parity with that ragged-aware launching; it has no effect on (and is not needed for) the aiter backend.Why this matters: Ragged mixed-prefill is production-real. Live serving batches commonly combine requests with different prompt lengths, and mixed chunking combines decode rows with long prefill chunks in the same attention call.
Platform scope: The optimization is AMD/HIP-only to avoid impacting other vendors. Both the compact grid logic and the optional scheduler tile-budget admission are gated on
_is_hip/_IS_HIP.Default behavior: The feature is enabled by default on AMD/HIP platforms (
SGLANG_TRITON_COMPACT_EXTEND_ATTENTION=True). To disable it for testing or comparison:Modifications
Core files (4):
python/sglang/kernels/ops/attention/extend_attention.py_compact_extend_q_tiles_per_head()to compute per-request tile countsSGLANG_TRITON_COMPACT_EXTEND_ATTENTIONat launch time (gated on_is_hip)compact_tiles < legacy_tiles, otherwise fall backuse_compact_tile_gridparameter stays vendor-neutral for testingpython/sglang/srt/layers/attention/triton_backend.pyforward_batch.extend_seq_lens_cpuintoextend_attention_fwd()so compact path has exact per-request extend lengthspython/sglang/srt/managers/schedule_policy.pyestimate_prefill_extend_tile_metrics()and optional scheduler tile-budget admissionSGLANG_PREFILL_TILE_BUDGET(default0= disabled),SGLANG_PREFILL_TILE_BUDGET_MODE=compact|legacy_IS_HIP— non-AMD scheduler admission unchanged even if env vars are setpython/sglang/srt/environ.pySGLANG_TRITON_COMPACT_EXTEND_ATTENTION = EnvBool(True)environment variable definitionTests (2):
test/registered/attention/test_triton_attention_kernels.pytest_compact_extend_attention_tile_count: verify compact tile logictest_extend_attention_compact_grid: compact vs legacy equivalencetest/registered/unit/managers/test_prefill_adder.pytest_prefill_tile_budget_disabled_on_non_hip: verify non-HIP no-opAll tests registered in CI (AMD + CUDA suites).
Accuracy Tests
Unit test correctness
All tests run in the registered SGLang test tree:
Model accuracy (4-GPU, real weights, Triton backend)
Setup:
amd/DeepSeek-R1-MXFP4, TP=4, Triton backend (--attention-backend triton), MI355X (gfx950), compact grid enabled (SGLANG_TRITON_COMPACT_EXTEND_ATTENTION=1),--kv-cache-dtype fp8_e4m3. Requires theforward_mla.pyw_kc None guards for Quark MXFP4.GSM8K result (1319 questions, 5-shot):
This validates the full multi-GPU model path with the compact grid actually exercised — the Triton extend kernel is the code path this PR modifies. Accuracy matches the AITER reference (0.946) within run-to-run noise, confirming the compact grid produces numerically correct results end-to-end.
Server command (Triton backend)
GSM8K client command
Speed Tests and Profiling
Hardware: 4x AMD Instinct MI355X (gfx950)
Setup: Production-like Triton serving benchmark (SGLang HTTP server +
sglang.bench_serving)Qwen/Qwen2.5-7B-Instruct,--load-format dummy, TP=4--attention-backend triton,--enable-mixed-chunk --chunked-prefill-size 2048SGLANG_USE_AITER=0, noSGLANG_PREFILL_TILE_BUDGETSGLANG_TRITON_COMPACT_EXTEND_ATTENTIONtoggled (1= compact,0= default)Fixed-workload throughput, CUDA graphs ENABLED (mean of 3 seeds)
These are end-to-end measurements (prefill + decode) via
sglang.bench_servingat--request-rate inf(all requests fired at once, closed-loop, to fixed-workload throughput).Tok/sis total end-to-end throughput;TTFTis the prefill latency;TPOTis the per-output-token (decode) latency.Workload notation
<INPUT>/<OUTPUT>, <N> req:INPUT/OUTPUTare the input and output length parameters,Nis the number of requests (--num-prompts). Actual lengths are sampled uniformly from[len * range_ratio, len]:--random-range-ratio 0.5→ lengths vary (e.g.4096/128→ inputs in [2048, 4096], outputs in [64, 128], i.e. 64–128 decode iterations per request).--random-range-ratio 1.0→ every request is exactlyINPUT/OUTPUT(e.g.4096/128→ all inputs 4096, all outputs 128).Variance: Total tok/s CV ≤ 2.5% across 3 seeds — the gap is not seed noise.
Why graphs matter: The default path barely improves with graphs because its bottleneck is the rectangular prefill grid (not graph-captured). The compact path removes that waste, letting decode graphs take effect.
Open-loop traffic, production-shaped arrivals
This is the realistic SLA story. With a fixed offered rate of 8 req/s (CUDA graphs ENABLED, the default deployment), the legacy Triton path cannot keep up — it drains only 3.48 req/s, so the queue builds and latency collapses. With the compact grid, the same server on the same hardware sustains the offered load at sub-second latency.
Config:
--request-rate 8 --max-concurrency 64 --random-input-len 4096 --random-output-len 128 --random-range-ratio 0.5 --num-prompts 128At an offered rate of 8 req/s the default path falls behind (3.48 < 8 req/s) and mean end-to-end latency blows up to ~16.7 s (P99 ~31 s); compact keeps up at ~0.88 s mean — the difference between an SLA-violating server and a healthy one, with no config change other than the compact flag.
Server command (Triton benchmark)
Launched once per setting; only
SGLANG_TRITON_COMPACT_EXTEND_ATTENTIONdiffers (1= compact,0= default). The command below is the graph-ENABLED (default) deployment used for all numbers above.Saturated client command (per workload/seed)
Open-loop client command
Multi-model breadth
The compact grid's benefit is a function of the per-GPU attention geometry (query heads, head_dim) and batch raggedness — not of weight values — so it generalizes across model families. Kernel microbenchmark of
extend_attention_fwd(compact vs legacy) at each model's published shape, mapped to a realistic tensor-parallel shard, single MI355X. Every result is numerically bit-exact (max abs diff = 0.0). Speedup is the extend-attention kernel time.Covers GQA, MQA, and MHA; dense and MoE; head_dim 64/128/256 (the 256 cases land ~9× vs ~12–15× for 128, still large). Closed-weight rows use published shapes —
just as valid since the effect is geometry-only.
TinyLlama-1.1B End2End
Independent end-to-end (prefill + decode) serving run on a different architecture than Qwen — TinyLlama-1.1B (
LlamaForCausalLM), TP=1, dummy weights,--attention-backend triton, saturated (--request-rate inf, closed-loop) ragged 2048/128, mean of 2 seeds.Workload:
--random-input-len 2048 --random-output-len 128 --random-range-ratio 0.5→ inputs in [1024, 2048], outputs in [64, 128], i.e. 64–128 decode iterations per request.The gain exceeds Qwen-7B's +242% because for a tiny model the rectangular attention-grid waste is a larger fraction of per-step compute.
DeepSeek R1 MXFP4 prefill-only validation
Test Environment:
amd/DeepSeek-R1-MXFP4(Quark MXFP4 quantization, DeepSeek V3 architecture, 671B parameters)--attention-backend tritonforward_mla.pyw_kc None guards for Quark MXFP4Open-loop traffic benchmark (4 req/s arrival rate, 64 requests):
Key Findings:
Why Latency Improvement is Larger Than Throughput:
The -33.8% latency improvement vs +2.4% throughput makes sense:
Profiling Breakdown (prefill-only, PyTorch profiler):
Component breakdown for DeepSeek R1 MXFP4 prefill (TP=4, 4096 input tokens):
Even in prefill (this PR's target), attention is only ~12% of execution time. A 50-67% reduction in attention tiles (compact grid) would theoretically save 3.3-4.4ms out of 54.5ms (~6-8% end-to-end speedup). The observed +2.4% reflects that:
Mixed Workload Results:
A testing with 1 prefill + 10 decode iterations showed minimal benefit (+0.1% throughput) because prefill attention is only a small fraction of the overall E2E time when combined with decode. The prefill-only test above correctly isolates the PR's optimization target and shows the measurable +2.4% throughput gain on prefill workloads.
Server command (Baseline mode)
Server command (Compact mode)
# Same as baseline, but with SGLANG_TRITON_COMPACT_EXTEND_ATTENTION=1 HIP_VISIBLE_DEVICES=4,5,6,7 \ SGLANG_TRITON_COMPACT_EXTEND_ATTENTION=1 \ python3 -m sglang.launch_server \ --model-path amd/DeepSeek-R1-MXFP4 \ --tp-size 4 --trust-remote-code \ --chunked-prefill-size 131072 --host 0.0.0.0 --port 9000 \ --log-requests --disable-radix-cache --mem-fraction-static 0.8 \ --max-running-requests 64 --kv-cache-dtype fp8_e4m3 \ --attention-backend tritonClient command (Prefill-only benchmark)
python3 open_loop_benchmark_r1_mxfp4.py \ --mode {baseline|compact} \ --request-rate 4 \ --max-concurrency 64 \ --random-input-len 4096 \ --random-output-len 1 \ --random-range-ratio 0.5 \ --num-prompts 64 \ --seed 42Conclusion:
The optimization works as designed and provides measurable benefit (+2.4% throughput, -33.8% latency) on DeepSeek R1 MXFP4 prefill workloads, but the gain is modest compared to smaller models because DeepSeek R1's unique architecture (massive MoE + TP communication) means attention is only 12% of prefill time. The compact grid successfully reduces wasted tile launches, but this translates to limited end-to-end impact when the model is dominated by communication and MoE compute rather than attention.
Caveats
Checklist
Review and Merge Process
/tag-and-rerun-ci,/tag-run-ci-label,/rerun-failed-ciCI States
Latest PR Test (Base): ✅ Run #31030229198
Latest PR Test (Extra): ❌ Run #31119790024