diff --git a/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/qwen3.8next-rocm10-patches.sh b/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/qwen3.8next-rocm10-patches.sh new file mode 100755 index 0000000000..24b9bb8255 --- /dev/null +++ b/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/qwen3.8next-rocm10-patches.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# Qwen3.8-Flash-Next kernels on lmsysorg/sglang-rocm:v0.5.23-rocm10-mi35x-20261117 (SGLang +# c67db7c762 and AITER 581579ab 0.1.29.dev156 with FlyDSL 0.4.2, both editable checkouts under +# /sgl-workspace). +# AITER +# - Not touched. The image's AITER has what the AITER release wheel gave this recipe before: +# ROCm/aiter#5992 (FlyDSL causal conv1d prefill, GDN decode/verify kernels), #6670 (FlyDSL +# fused QSA sparse decode, needed by sglang#45196), #6496 (FlyDSL single-kernel GDN fused +# chunked prefill) and #5993 (hc_mix kernels). The script only checks that the FlyDSL modules +# are importable. +# SGLang (each patch is the source-only diff of an open upstream PR, rebased onto the image's +# SGLang; tests, benchmarks and AITER's AOT registry dropped; the header of each file names the +# PR and its head commit) +# - 01 sglang#48648 fused decode-sized hyper-connection norm + inject, SGLANG_OPT_QWEN4_FUSED_HC +# - 02 sglang#45196 QSA sparse decode on the AITER FlyDSL kernel (on with SGLANG_USE_AITER) +# - 03 sglang#48649 faster QSA decode MQA logits (padded Q, group-strided launch) +# - 04 sglang#45529 fused QK norm + RoPE + gate for Qwen3.5 self-attention on gfx950 +# - 05 sglang#41879 GDN prefill conv on AITER FlyDSL, SGLANG_AITER_GDN_CONV +# - 06 sglang#44103 GDN chunked prefill on AITER, SGLANG_AITER_GDN_PREFILL[_H] +# - 07 sglang#48090 MTP verify target probs on the top-k support instead of a vocabulary-wide +# sort (on with SGLANG_USE_AITER under rejection sampling; the image lacks +# sglang#41916, so the patch carries its top-p rescale helper) +# Already in the image, so not patched: sglang#41683 (strided GDN prefill projection views, merged +# 2026-11-17), the monokernel (--enable-amd-monokernel), the AITER topk_gating router (sglang#40708), +# ratio-3 GDN packing (sglang#44302) and the 128-row hc_mix (sglang#41880). All Python. A patch +# that no longer applies, or a missing FlyDSL module, fails the worker. +set -euo pipefail +# srtctl only looks up setup_script here; the patches live with the single-node +# recipe and are read through the workspace mount. +patches=/infmax-workspace/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches +[[ -d $patches ]] || { echo "qwen3.8next: $patches not found" >&2; exit 1; } +# Later patches touch files of earlier ones, so a per-patch reverse check cannot +# tell a re-run apart; the marker records the script and patch set a container +# already has. +marker=/sgl-workspace/.qwen3.8next-rocm10-patches +digest="$( { cat "${BASH_SOURCE[0]}" "$patches"/*.patch; } | sha256sum | cut -d' ' -f1)" +if [[ -f $marker ]]; then + if [[ "$(cat "$marker")" == "$digest" ]]; then + echo "qwen3.8next patches already applied" + exit 0 + fi + echo "qwen3.8next: $marker is from a different patch set" >&2 + exit 1 +fi + +# The image's AITER must be the editable checkout with the FlyDSL kernels of the four PRs. +python3 - <<'PY' +import importlib.metadata as metadata +import importlib.util +import sys + +for module in ( + "aiter.ops.flydsl.causal_conv1d_flydsl", + "aiter.ops.flydsl.qsa_sparse_decode", + "aiter.ops.flydsl.gdn_fused_prefill", + "aiter.ops.flydsl.hc_mix", +): + if importlib.util.find_spec(module) is None: + sys.exit(f"qwen3.8next: {module} is missing from the image's AITER") +print( + f"qwen3.8next image aiter: amd-aiter {metadata.version('amd-aiter')}, " + f"flydsl {metadata.version('flydsl')}, from {importlib.util.find_spec('aiter').origin}" +) +PY + +apply() { + git -c safe.directory="*" -C "$1" apply "$patches/$2" + echo "qwen3.8next patch applied: $2" +} + +apply /sgl-workspace/sglang 01-sglang-48648-qwen4-fused-hc-decode.patch +apply /sgl-workspace/sglang 02-sglang-45196-qsa-flydsl-sparse-decode.patch +apply /sgl-workspace/sglang 03-sglang-48649-qsa-decode-mqa-launch.patch +apply /sgl-workspace/sglang 04-sglang-45529-qwen35-fuse-selfattn-prepare.patch +apply /sgl-workspace/sglang 05-sglang-41879-aiter-gdn-conv-prefill.patch +apply /sgl-workspace/sglang 06-sglang-44103-aiter-gdn-chunked-prefill.patch +apply /sgl-workspace/sglang 07-sglang-48090-mtp-sparse-rejection-target-probs.patch + +echo "$digest" > "$marker" diff --git a/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/agentic.yaml b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/agentic.yaml index 8057424d83..714510b774 100644 --- a/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/agentic.yaml +++ b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/agentic.yaml @@ -1,6 +1,6 @@ # Qwen3.8-Flash-Next Quark MXFP4 MoE (MTP experts included), FP8 attention and # FP8 PLE, AgentX on MI355X via SGLang with native NEXTN MTP. The ~116 GiB -# checkpoint fits on one MI355X, so TP1. The upstream image is used unpatched. +# checkpoint fits on one MI355X, so TP1. base: schema: 2 name: qwen3.8next-fp4-mi355x-sglang-agentic @@ -15,6 +15,12 @@ base: tachometer: enabled: false engine: sglang + # The image (lmsysorg/sglang-rocm 20261117: SGLang c67db7c762, AITER 581579ab 0.1.29.dev156, + # FlyDSL 0.4.2) already has the AITER FlyDSL kernels this recipe uses (ROCm/aiter#5992, #5993, + # #6496, #6670), so AITER is not touched. The setup script patches SGLang with open upstream + # PRs (sgl-project/sglang #48648, #45196, #48649, #45529, #41879, #44103, #48090); the patch + # files are in patches/ next to this recipe. + setup_script: qwen3.8next-rocm10-patches.sh roles: agg: nodes: 1 @@ -41,6 +47,7 @@ base: scheduler-recv-interval: 10 stream-interval: 50 reasoning-parser: qwen3 + default-chat-template-kwargs: '{"enable_thinking": false}' tool-call-parser: qwen3_coder speculative-algorithm: NEXTN speculative-num-steps: 3 @@ -59,19 +66,26 @@ base: SGLANG_TIMEOUT_KEEP_ALIVE: '1800' SGLANG_ENABLE_SPEC_V2: '1' AITER_GDR_FLYDSL: '1' + # The FlyDSL QSA sparse decode (sglang#45196) is on whenever SGLANG_USE_AITER + # is set on gfx950. The GDN prefill (sglang#41879, #44103) runs AITER's + # FlyDSL causal conv1d and the single fused chunked-prefill kernel + # (ROCm/aiter#6496), which needs the bf16 SSM state set above. + SGLANG_USE_AITER: '1' + SGLANG_AITER_GDN_CONV: '1' + SGLANG_AITER_GDN_PREFILL: '1' + SGLANG_AITER_GDN_PREFILL_H: fused benchmark: env: AIPERF_REQUIRED_SERVER_METRIC_PREFIX: 'sglang:' AIPERF_APPLY_CHAT_TEMPLATE: 'true' -# c1, c2, c4 and c8 run the FlyDSL monokernel (--enable-amd-monokernel) for MTP -# target verify and draft. Its verify writes the per-draft intermediate SSM -# states, so ReplaySSM is off, and its prelude reads the PLE table on the GPU, -# so the table is not offloaded. Admission equals the concurrency. These points -# also set SGLANG_USE_AITER, which the monokernel requires (the image sets it -# too), so they form their own GSM8K eval group. c12 and c16 keep ReplaySSM, -# the PLE offload and 2x CONC admission. Every point uses mem-fraction-static -# as given instead of the aiter backend's 0.85 scaling. +# c1 and c2 run the FlyDSL monokernel (--enable-amd-monokernel) for MTP target verify +# and draft. Its verify writes the per-draft intermediate SSM states, so ReplaySSM is +# off, and its prelude reads the PLE table on the GPU, so the table is not offloaded. +# Admission equals the concurrency. These points also set SGLANG_USE_AITER, which the +# monokernel requires (the image sets it too), so they form their own GSM8K eval group. +# Every point uses mem-fraction-static as given instead of the aiter backend's 0.85 +# scaling. override_c1: roles: agg: @@ -106,110 +120,71 @@ override_c2: CONC: '2' KV_OFFLOADING: none -override_c4: - roles: - agg: - args: - enable-linear-replayssm-spec: null - ple-offload-embedding: null - enable-amd-monokernel: true - max-running-requests: 4 - cuda-graph-max-bs-decode: 4 - env: - SGLANG_AITER_HONOR_EXPLICIT_MEM_FRACTION: '1' - SGLANG_USE_AITER: '1' - benchmark: - env: - CONC: '4' - KV_OFFLOADING: none - -override_c8: - roles: - agg: - args: - enable-linear-replayssm-spec: null - ple-offload-embedding: null - enable-amd-monokernel: true - max-running-requests: 8 - cuda-graph-max-bs-decode: 8 - env: - SGLANG_AITER_HONOR_EXPLICIT_MEM_FRACTION: '1' - SGLANG_USE_AITER: '1' - benchmark: - env: - CONC: '8' - KV_OFFLOADING: none - +# c12, c24, c48 and c80 keep ReplaySSM and the PLE offload, store the target and draft KV +# caches in FP8 (E4M3), and use a Mamba state pool whose checkpoint interval is 262144 +# tokens, so a prompt gets no interior checkpoints (extra_buffer_lazy). mem-fraction-static +# is 0.88, used as given. c12 and c24 admit 2x CONC and serve from GPU KV; c48 and c80 +# add HiCache host-DRAM offload and admit 128 requests. HiCache takes the point's 299 GB +# DRAM share from the matrix generator (hicache-size 298); TOTAL_CPU_DRAM_GB records it. +# SGLANG_OPT_QWEN4_FUSED_HC (sglang#48648) fuses the decode-sized hyper-connection +# norm and inject into the mix. The prefill CUDA graph backend is breakable (the AMD +# reference recipes get it from an SGLang default change that this image lacks), which +# captures the GDN prefill on static per-bucket tables; a batch outside the captured +# buckets runs eagerly through the AITER fused prefill. c80 caches only the prompt on +# finish and keeps at most two Mamba states per path. override_c12: roles: agg: - args: + args: &fp8_args + kv-cache-dtype: fp8_e4m3 + speculative-draft-kv-cache-dtype: fp8_e4m3 + mem-fraction-static: 0.88 max-running-requests: 24 cuda-graph-max-bs-decode: 24 - env: + max-mamba-cache-size: 960 + mamba-radix-cache-strategy: extra_buffer_lazy + mamba-track-interval: 262144 + cuda-graph-backend-prefill: breakable + env: &fp8_env + SGLANG_USE_AITER: '1' + SGLANG_USE_AITER_UNIFIED_ATTN: '1' SGLANG_AITER_HONOR_EXPLICIT_MEM_FRACTION: '1' + SGLANG_OPT_QWEN4_FUSED_HC: '1' benchmark: env: - CONC: '12' KV_OFFLOADING: none + CONC: '12' -override_c16: +override_c24: roles: agg: args: - max-running-requests: 32 - cuda-graph-max-bs-decode: 32 - env: - SGLANG_AITER_HONOR_EXPLICIT_MEM_FRACTION: '1' + <<: *fp8_args + max-running-requests: 48 + cuda-graph-max-bs-decode: 48 + env: *fp8_env benchmark: env: - CONC: '16' KV_OFFLOADING: none + CONC: '24' -# c24, c48 and c80 keep ReplaySSM and the PLE offload, store the target and draft KV -# caches in FP8 (E4M3), and add HiCache host-DRAM offload with a Mamba state pool -# that tracks a checkpoint every 256 tokens (extra_buffer_lazy). HiCache sets -# hicache-size 200 at c24 and 298 at c48 and c80. -# mem-fraction-static is 0.88, used as given. c24 admits 2x CONC; c48 and c80 admit 128 requests. -# c80 caches only the prompt on finish and keeps at most two Mamba states per path. -override_c24: +override_c48: roles: agg: args: &hicache_args - kv-cache-dtype: fp8_e4m3 - speculative-draft-kv-cache-dtype: fp8_e4m3 - mem-fraction-static: 0.88 - max-running-requests: 48 - cuda-graph-max-bs-decode: 48 - max-mamba-cache-size: 960 - mamba-radix-cache-strategy: extra_buffer_lazy - mamba-track-interval: 256 + <<: *fp8_args + max-running-requests: 128 + cuda-graph-max-bs-decode: 128 + max-mamba-cache-size: 720 enable-hierarchical-cache: true - hicache-size: 200 + hicache-size: 298 hicache-io-backend: kernel hicache-mem-layout: page_first hicache-write-policy: write_back - env: &hicache_env - SGLANG_AITER_HONOR_EXPLICIT_MEM_FRACTION: '1' - SGLANG_USE_AITER_UNIFIED_ATTN: '1' + env: *fp8_env benchmark: env: &hicache_client KV_OFFLOADING: dram - CONC: '24' - -override_c48: - roles: - agg: - args: - <<: *hicache_args - max-running-requests: 128 - cuda-graph-max-bs-decode: 128 - max-mamba-cache-size: 720 - hicache-size: 298 - env: *hicache_env - benchmark: - env: - <<: *hicache_client CONC: '48' override_c80: @@ -217,15 +192,12 @@ override_c80: agg: args: <<: *hicache_args - max-running-requests: 128 - cuda-graph-max-bs-decode: 128 max-mamba-cache-size: 640 - hicache-size: 298 # Cache only the prompt on finish; the AgentX replay never re-sends model output. strip-thinking-cache: true # At most two Mamba states per conversation path; stale interior states skip host write-back. mamba-max-states-per-path: 2 - env: *hicache_env + env: *fp8_env benchmark: env: <<: *hicache_client diff --git a/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/01-sglang-48648-qwen4-fused-hc-decode.patch b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/01-sglang-48648-qwen4-fused-hc-decode.patch new file mode 100644 index 0000000000..6f0db48685 --- /dev/null +++ b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/01-sglang-48648-qwen4-fused-hc-decode.patch @@ -0,0 +1,697 @@ +# [Perf] [AMD] Qwen4-Exp HC: fuse decode-sized hyper-connection norm and inject into FlyDSL mix +# https://github.com/sgl-project/sglang/pull/48648 (PR head f6f9c1c41678ec6087a58cf51145b8041460364b) +# Generated against the SGLang checkout of the image (c67db7c762, 2026-11-17); source files only (tests, benchmarks, AOT registry and docs dropped); rebased from the 1ced9a9eb0 version. + +diff --git a/python/sglang/kernels/ops/gemm/hc_fused_flydsl.py b/python/sglang/kernels/ops/gemm/hc_fused_flydsl.py +new file mode 100644 +index 0000000000..0d47a1d2b8 +--- /dev/null ++++ b/python/sglang/kernels/ops/gemm/hc_fused_flydsl.py +@@ -0,0 +1,549 @@ ++"""Fused Qwen gated-residual HC (hc_per_branch_norm, HC=4) for decode-sized M on gfx950. ++ ++Extends AITER's FlyDSL ``hc_mix`` (down split-K -> reduce + SiLU -> up + gate + branch ++mean) so an HC site needs no separate RMSNorm and its combine needs no GEMV: ++ ++* The per-branch Gemma RMSNorm is folded into the down projection. ``(1 + w)`` is folded ++ into the packed down / inject weights, the down kernel multiplies the raw residual ++ ``H``, and the reduce scales each split-K partial by its branch's ++ ``rsqrt(mean(H_b^2) + eps)`` (a split never straddles two branches). The up kernel ++ rebuilds the normed gate operand as ``H * s_b * (1 + w)`` in FP32. ++* The combine's inject projection ``normed @ W_inj^T`` rides along as extra down rows, ++ so the reduce also returns the inject logits ``G`` and the combine is elementwise. ++* The per-branch sums of squares come either from the combine that produced ``H`` ++ (``hc_apply_inject`` returns them) or, when ``H`` has another origin, from extra ++ down-kernel CTAs. ++ ++Numerics differ from the unfused path only by rounding points: the normed input is no ++longer rounded to BF16 before the GEMMs, and ``(1 + w)`` is rounded into the weights. ++""" ++ ++import functools ++ ++import flydsl.compiler as flyc ++import flydsl.expr as fx ++import torch ++from aiter.ops.flydsl.kernels.mxfp4_gemm_common import lds_typed_ptr, lds_vec_load ++from flydsl.expr import const_expr, gpu, math, range_constexpr, rocdl ++ ++HC = 4 ++# Rows in a 16x16x32 MFMA tile. ++_MFMA_M = 16 ++# Elements of one packed 16x32 B fragment (see _pack): 64 lanes x 8 BF16. ++_FRAG = 16 * 32 ++# Same LDS row pad as AITER's hc_mix up projection; gfx950 has 160 KiB of LDS per CU. ++_LDS_ROW_PAD = 8 ++_LDS_BYTES = 160 * 1024 ++# Speculative verify carries requests x draft tokens rows; past this the unfused path is used. ++MAX_M = 128 ++_REDUCE_THREADS = 256 ++# B fragments in flight per wave, as in AITER's hc_mix. ++_PREFETCH = 16 ++# Columns per combine wave (64 lanes x 8); HS splits into HS / _INJECT_BLOCK partial ++# sums of squares per branch. ++_INJECT_BLOCK = 512 ++ ++ ++def _load(tensor, offset, width, dtype): ++ """Buffer load of `width` elements at `offset`; OOB reads return zero.""" ++ if width == 8: ++ kind = fx.rocdl.BufferCopy128b() ++ elif dtype == fx.Float32: ++ kind = fx.rocdl.BufferCopy32b() ++ else: ++ kind = fx.rocdl.BufferCopy16b() ++ view = fx.make_view( ++ fx.get_iter(tensor) + fx.Int32(offset), fx.make_layout(width, 1) ++ ) ++ frag = fx.make_rmem_tensor(width, dtype) ++ fx.copy(fx.make_copy_atom(kind, dtype), view, frag) ++ return fx.Vector(frag.load()) ++ ++ ++def _store(tensor, offset, value, dtype): ++ view = fx.make_view(fx.get_iter(tensor) + fx.Int32(offset), fx.make_layout(1, 1)) ++ atom = fx.make_copy_atom( ++ fx.rocdl.BufferCopy32b() if dtype == fx.Float32 else fx.rocdl.BufferCopy16b(), ++ dtype, ++ ) ++ frag = fx.make_rmem_tensor(1, dtype) ++ frag.store(fx.Vector.from_elements([value], dtype)) ++ fx.copy(atom, frag, view) ++ ++ ++def _store8(tensor, offset, vec): ++ """128-bit store of 8 BF16 at `offset`.""" ++ view = fx.make_view(fx.get_iter(tensor) + fx.Int32(offset), fx.make_layout(8, 1)) ++ frag = fx.make_rmem_tensor(8, fx.BFloat16) ++ frag.store(vec) ++ fx.copy(fx.make_copy_atom(fx.rocdl.BufferCopy128b(), fx.BFloat16), frag, view) ++ ++ ++def _mfma(av, bv, acc): ++ return fx.Vector( ++ rocdl.mfma_f32_16x16x32_bf16( ++ acc.ir_value().type, ++ [av.ir_value(), bv.ir_value(), acc.ir_value(), 0, 0, 0], ++ ) ++ ) ++ ++ ++def _sigmoid(v): ++ return fx.Float32(1.0) / (fx.Float32(1.0) + math.exp(-v)) ++ ++ ++@functools.cache ++def _up_shared(rows, rpad): ++ @fx.struct ++ class UpShared: ++ t: fx.Array[fx.Int32, rows * rpad // 2, 16] ++ ++ return UpShared ++ ++ ++@flyc.kernel ++def _hc_down_fused( ++ A: fx.Tensor, ++ W: fx.Tensor, ++ P: fx.Tensor, ++ SS: fx.Tensor, ++ M: fx.Constexpr[int], ++ R: fx.Constexpr[int], ++ K: fx.Constexpr[int], ++ SPLIT: fx.Constexpr[int], ++ SS_OUT: fx.Constexpr[bool], ++): ++ """H[M,K] against packed down[R,K] -> P[SPLIT,M,R] FP32 split-K partials. ++ ++ One wave per CTA; grid (R / 16 [+ row tiles], SPLIT). With SS_OUT, CTA R / 16 + t ++ also writes row tile t's sums of squares over the split's columns, SS[M, SPLIT]. ++ """ ++ lane = gpu.thread_id("x") % 64 ++ nt = gpu.block_id("x") ++ sp = gpu.block_id("y") ++ a = fx.rocdl.make_buffer_tensor(A, max_size=False) ++ w = fx.rocdl.make_buffer_tensor(W, max_size=False) ++ out = fx.rocdl.make_buffer_tensor(P, max_size=False) ++ row_a = lane % 16 ++ mt = (M + _MFMA_M - 1) // _MFMA_M ++ steps = K // SPLIT // 32 ++ k0 = sp * steps ++ ++ def a_offset(row, kcol): ++ # Descriptor-bound OOB loads return zero for the padded M rows. ++ return (row < M).select(fx.Int32(row * K + kcol), fx.Int32(M * K)) ++ ++ if nt < R // 16: ++ accs = [fx.Vector.filled(4, 0.0, fx.Float32)] * mt ++ for g in range_constexpr(0, steps, _PREFETCH): ++ bvs = [] ++ for ki in range_constexpr(g, min(g + _PREFETCH, steps)): ++ bvs.append( ++ _load( ++ w, (nt * (K // 32) + k0 + ki) * _FRAG + lane * 8, 8, fx.BFloat16 ++ ) ++ ) ++ for j in range_constexpr(len(bvs)): ++ kcol = (k0 + g + j) * 32 + lane // 16 * 8 ++ for t in range_constexpr(mt): ++ row = t * _MFMA_M + row_a ++ av = _load(a, a_offset(row, kcol), 8, fx.BFloat16) ++ accs[t] = _mfma(av, bvs[j], accs[t]) ++ for t in range_constexpr(mt): ++ for i in range_constexpr(4): ++ row = t * _MFMA_M + lane // 16 * 4 + i ++ col = nt * 16 + lane % 16 ++ if row < M: ++ _store(out, (sp * M + row) * R + col, accs[t][i], fx.Float32) ++ if const_expr(SS_OUT): ++ ss = fx.rocdl.make_buffer_tensor(SS, max_size=False) ++ for t in range_constexpr(mt): ++ if nt == R // 16 + t: ++ row = t * _MFMA_M + row_a ++ sq = fx.Float32(0.0) ++ for k in range_constexpr(steps): ++ kcol = (k0 + k) * 32 + lane // 16 * 8 ++ af = _load(a, a_offset(row, kcol), 8, fx.BFloat16).to(fx.Float32) ++ for e in range_constexpr(8): ++ sq = sq + af[e] * af[e] ++ # The 4 lanes holding a row's four 8-column groups are 16 apart. ++ for shift in range_constexpr(2): ++ peer = gpu.shuffle( ++ sq, fx.Int32(16 << shift), fx.Int32(64), mode="xor" ++ ) ++ sq = sq + fx.Float32(peer) ++ if (lane < 16) & (row < M): ++ _store(ss, row * SPLIT + sp, sq, fx.Float32) ++ ++ ++@flyc.kernel ++def _hc_reduce_fused( ++ P: fx.Tensor, ++ SS: fx.Tensor, ++ T: fx.Tensor, ++ G: fx.Tensor, ++ SC: fx.Tensor, ++ M: fx.Constexpr[int], ++ R: fx.Constexpr[int], ++ RL: fx.Constexpr[int], ++ NI: fx.Constexpr[int], ++ K: fx.Constexpr[int], ++ SPLIT: fx.Constexpr[int], ++ NP: fx.Constexpr[int], ++ EPS: fx.Constexpr[float], ++): ++ """Scale each split by its branch's rstd and sum: SiLU(down / HC) -> T[M,RL] BF16, ++ inject logits -> G[M,NI] FP32, branch scales -> SC[M,HC] FP32. ++ ++ SS[M, HC * NP] holds NP partial sums of squares per branch. ++ """ ++ i = gpu.block_id("x") * _REDUCE_THREADS + gpu.thread_id("x") ++ p = fx.rocdl.make_buffer_tensor(P, max_size=False) ++ ss = fx.rocdl.make_buffer_tensor(SS, max_size=False) ++ t = fx.rocdl.make_buffer_tensor(T, max_size=False) ++ g = fx.rocdl.make_buffer_tensor(G, max_size=False) ++ sc = fx.rocdl.make_buffer_tensor(SC, max_size=False) ++ row = i // R ++ c = i % R ++ per = SPLIT // HC ++ acc = fx.Float32(0.0) ++ for b in range_constexpr(HC): ++ total = fx.Float32(0.0) ++ for j in range_constexpr(NP): ++ total = total + _load(ss, row * (HC * NP) + (b * NP + j), 1, fx.Float32)[0] ++ scale = fx.Float32(1.0) / math.sqrt( ++ total * fx.Float32(HC / K) + fx.Float32(EPS) ++ ) ++ part = fx.Float32(0.0) ++ for s in range_constexpr(b * per, (b + 1) * per): ++ part = part + _load(p, fx.Int32(s * M * R) + i, 1, fx.Float32)[0] ++ acc = acc + part * scale ++ if (c == b) & (i < M * R): ++ _store(sc, row * HC + b, scale, fx.Float32) ++ v = acc * fx.Float32(1.0 / HC) ++ v = v * _sigmoid(v) ++ if (i < M * R) & (c < RL): ++ _store(t, row * RL + c, v.to(fx.BFloat16), fx.BFloat16) ++ if const_expr(NI > 0): ++ if (i < M * R) & (c >= RL) & (c < RL + NI): ++ _store(g, row * NI + c - RL, acc, fx.Float32) ++ ++ ++@flyc.kernel ++def _hc_up_fused( ++ A: fx.Tensor, ++ W: fx.Tensor, ++ X: fx.Tensor, ++ SC: fx.Tensor, ++ W1: fx.Tensor, ++ O: fx.Tensor, ++ M: fx.Constexpr[int], ++ N: fx.Constexpr[int], ++ R: fx.Constexpr[int], ++ WAVES: fx.Constexpr[int], ++ STAGE: fx.Constexpr[bool], ++): ++ """T[M,R] against interleaved up[N,R]; gate sigmoid * (H * s_b * (1 + w)), mean over HC.""" ++ tid = gpu.thread_id("x") ++ lane = tid % 64 ++ nt = gpu.block_id("x") * WAVES + tid // 64 ++ a = fx.rocdl.make_buffer_tensor(A, max_size=False) ++ w = fx.rocdl.make_buffer_tensor(W, max_size=False) ++ x = fx.rocdl.make_buffer_tensor(X, max_size=False) ++ sc = fx.rocdl.make_buffer_tensor(SC, max_size=False) ++ w1 = fx.rocdl.make_buffer_tensor(W1, max_size=False) ++ out = fx.rocdl.make_buffer_tensor(O, max_size=False) ++ mt = (M + _MFMA_M - 1) // _MFMA_M ++ ++ bvs = [] ++ for ki in range_constexpr(min(_PREFETCH, R // 32)): ++ bvs.append(_load(w, (nt * (R // 32) + ki) * _FRAG + lane * 8, 8, fx.BFloat16)) ++ col = nt * 16 + lane % 16 ++ # Interleaved up rows: col % HC is the branch, col // HC the hidden unit. ++ n = (col % HC) * (N // HC) + col // HC ++ wn = _load(w1, n, 1, fx.Float32)[0] ++ xvs = [] ++ for t in range_constexpr(mt): ++ for i in range_constexpr(4): ++ row = t * _MFMA_M + lane // 16 * 4 + i ++ # Rows >= M sit past the end of X / SC, so these loads return zero. ++ hv = _load(x, row * N + n, 1, fx.BFloat16)[0].to(fx.Float32) ++ sv = _load(sc, row * HC + col % HC, 1, fx.Float32)[0] ++ xvs.append(hv * sv * wn) ++ ++ if const_expr(STAGE): ++ rows = mt * _MFMA_M ++ rpad = R + _LDS_ROW_PAD ++ threads = 64 * WAVES ++ lds = fx.SharedAllocator().allocate(_up_shared(rows, rpad)).peek() ++ base = fx.Int32(fx.ptrtoint(lds.t.ptr)) ++ chunks = rows * (R // 8) ++ vals = [] ++ for c0 in range_constexpr(0, chunks, threads): ++ vals.append(_load(a, (fx.Int32(c0) + fx.Int32(tid)) * 8, 8, fx.BFloat16)) ++ for j in range_constexpr(len(vals)): ++ c = fx.Int32(j * threads) + fx.Int32(tid) ++ ptr = lds_typed_ptr( ++ base, ++ fx.BFloat16.ir_type, ++ align=16, ++ byte_offset=(c + c // (R // 8)) * fx.Int32(16), ++ ) ++ if const_expr((j + 1) * threads <= chunks): ++ fx.ptr_store(vals[j].ir_value(), ptr) ++ elif c < chunks: ++ fx.ptr_store(vals[j].ir_value(), ptr) ++ gpu.barrier() ++ ++ row_a = lane % 16 ++ steps = R // 32 ++ accs = [fx.Vector.filled(4, 0.0, fx.Float32)] * mt ++ for g in range_constexpr(0, steps, _PREFETCH): ++ if const_expr(g > 0): ++ bvs = [] ++ for ki in range_constexpr(g, min(g + _PREFETCH, steps)): ++ bvs.append( ++ _load(w, (nt * steps + ki) * _FRAG + lane * 8, 8, fx.BFloat16) ++ ) ++ for j in range_constexpr(len(bvs)): ++ ki = g + j ++ for t in range_constexpr(mt): ++ row = t * _MFMA_M + row_a ++ if const_expr(STAGE): ++ av = fx.Vector( ++ lds_vec_load( ++ base, ++ fx.Int32(row * rpad + ki * 32 + lane // 16 * 8) ++ * fx.Int32(2), ++ fx.Vector.make_type(8, fx.BFloat16), ++ fx.BFloat16, ++ align=16, ++ ) ++ ) ++ else: ++ ao = (row < M).select( ++ fx.Int32(row * R + ki * 32 + lane // 16 * 8), ++ fx.Int32(M * R), ++ ) ++ av = _load(a, ao, 8, fx.BFloat16) ++ accs[t] = _mfma(av, bvs[j], accs[t]) ++ for t in range_constexpr(mt): ++ for i in range_constexpr(4): ++ row = t * _MFMA_M + lane // 16 * 4 + i ++ value = xvs[t * 4 + i] * _sigmoid(accs[t][i]) ++ # Four adjacent lanes hold the four branches of one hidden unit. ++ for shift in range_constexpr(2): ++ peer = gpu.shuffle( ++ value, fx.Int32(1 << shift), fx.Int32(64), mode="xor" ++ ) ++ value = value + fx.Float32(peer) ++ if (row < M) & (lane % 4 == 0): ++ _store( ++ out, ++ row * (N // HC) + col // HC, ++ (value * fx.Float32(1.0 / HC)).to(fx.BFloat16), ++ fx.BFloat16, ++ ) ++ ++ ++@flyc.jit ++def _launch( ++ H: fx.Tensor, ++ D: fx.Tensor, ++ U: fx.Tensor, ++ W1: fx.Tensor, ++ P: fx.Tensor, ++ SS: fx.Tensor, ++ T: fx.Tensor, ++ G: fx.Tensor, ++ SC: fx.Tensor, ++ O: fx.Tensor, ++ M: fx.Constexpr[int], ++ K: fx.Constexpr[int], ++ R: fx.Constexpr[int], ++ RL: fx.Constexpr[int], ++ NI: fx.Constexpr[int], ++ S: fx.Constexpr[int], ++ NP: fx.Constexpr[int], ++ WV: fx.Constexpr[int], ++ SS_OUT: fx.Constexpr[bool], ++ STAGE: fx.Constexpr[bool], ++ EPS: fx.Constexpr[float], ++ stream: fx.Stream, ++): ++ if const_expr(SS_OUT): ++ _hc_down_fused(H, D, P, SS, M, R, K, S, True).launch( ++ grid=(R // 16 + (M + _MFMA_M - 1) // _MFMA_M, S), block=(64,), stream=stream ++ ) ++ else: ++ _hc_down_fused(H, D, P, SS, M, R, K, S, False).launch( ++ grid=(R // 16, S), block=(64,), stream=stream ++ ) ++ _hc_reduce_fused(P, SS, T, G, SC, M, R, RL, NI, K, S, NP, EPS).launch( ++ grid=((M * R + _REDUCE_THREADS - 1) // _REDUCE_THREADS,), ++ block=(_REDUCE_THREADS,), ++ stream=stream, ++ ) ++ _hc_up_fused(T, U, H, SC, W1, O, M, K, RL, WV, STAGE).launch( ++ grid=(K // (16 * WV),), block=(64 * WV,), stream=stream ++ ) ++ ++ ++def _pack(w): ++ n, k = w.shape ++ return w.reshape(n // 16, 16, k // 32, 4, 8).permute(0, 2, 3, 1, 4).contiguous() ++ ++ ++class HcFusedWeights: ++ """Packed weights of one HC site; build after weight loading.""" ++ ++ def __init__(self, down, up, inject, norm_weight, eps): ++ r, k = down.shape ++ if k % (32 * HC) or r % 32 or up.shape != (k, r) or norm_weight.shape != (k,): ++ raise ValueError( ++ "fused HC needs K % 128 == 0, R % 32 == 0 and matching weights" ++ ) ++ self.k, self.r, self.eps = k, r, float(eps) ++ self.w1 = (1.0 + norm_weight.float()).contiguous() ++ rows = [down.float() * self.w1] ++ self.ni = 0 ++ if inject is not None: ++ self.ni = inject.shape[0] ++ rows.append(inject.float() * self.w1) ++ d = torch.cat(rows) ++ pad = -d.shape[0] % 16 ++ if pad: ++ d = torch.cat([d, d.new_zeros(pad, k)]) ++ self.rp = d.shape[0] ++ self.down = _pack(d.to(torch.bfloat16)) ++ interleaved = up.reshape(HC, k // HC, r).permute(1, 0, 2).reshape(k, r) ++ self.up = _pack(interleaved.contiguous()) ++ ++ ++# Measured on Qwen K=10240, R=320 with per-layer (cold) weights at M=16 and 64: split-K 32 ++# fills the GPU with single-wave down CTAs; 4 waves per up CTA as in AITER's hc_mix. ++SPLIT_K = 32 ++UP_WAVES = 4 ++ ++ ++def hc_fused_supported(h, weights: HcFusedWeights, split_k=SPLIT_K): ++ """Whether both the site's mix and its combine (``hc_apply_inject``) accept h.""" ++ return ( ++ h.dtype == torch.bfloat16 ++ and h.is_contiguous() ++ and h.dim() == 2 ++ and 1 <= h.shape[0] <= MAX_M ++ and h.shape[1] == weights.k ++ and weights.k % (32 * split_k) == 0 ++ and weights.k % (HC * _INJECT_BLOCK) == 0 ++ and split_k % HC == 0 ++ and weights.ni in (0, HC) ++ ) ++ ++ ++def hc_fused_mix( ++ h, weights: HcFusedWeights, sumsq=None, *, split_k=SPLIT_K, up_waves=UP_WAVES ++): ++ """One HC site on residual h [M, K]: (mixed [M, K/HC] BF16, inject logits [M, NI] FP32 ++ or None). ``sumsq`` is the [M, HC * NP] partial sums of squares ``hc_apply_inject`` ++ returned for h; None makes the down kernel compute them.""" ++ m, k = h.shape ++ dev = h.device ++ f32 = torch.float32 ++ p = torch.empty((split_k, m, weights.rp), device=dev, dtype=f32) ++ t = torch.empty((m, weights.r), device=dev, dtype=h.dtype) ++ g = torch.empty((m, max(weights.ni, 1)), device=dev, dtype=f32) ++ sc = torch.empty((m, HC), device=dev, dtype=f32) ++ out = torch.empty((m, k // HC), device=dev, dtype=h.dtype) ++ if sumsq is None: ++ sumsq = torch.empty((m, split_k), device=dev, dtype=f32) ++ np_, ss_out = split_k // HC, True ++ else: ++ np_, ss_out = sumsq.shape[1] // HC, False ++ stage = -(-m // _MFMA_M) * _MFMA_M * (weights.r + _LDS_ROW_PAD) * 2 <= _LDS_BYTES ++ _launch( ++ h, weights.down, weights.up, weights.w1, p, sumsq, t, g, sc, out, ++ m, k, weights.rp, weights.r, weights.ni, split_k, np_, up_waves, ++ ss_out, stage, weights.eps, ++ torch.cuda.current_stream(dev), ++ ) # fmt: skip ++ return out, (g if weights.ni else None) ++ ++ ++@flyc.kernel ++def _hc_inject_fused( ++ H: fx.Tensor, ++ Y: fx.Tensor, ++ G: fx.Tensor, ++ O: fx.Tensor, ++ SS: fx.Tensor, ++ K: fx.Constexpr[int], ++ NI: fx.Constexpr[int], ++): ++ """O = H + Y * 2 sigmoid(G / HC) per branch, plus each wave's sum of squares of O. ++ ++ One wave per CTA owns _INJECT_BLOCK columns of one branch of one row: grid ++ (M, HC * HS / _INJECT_BLOCK). SS[M, HC * NP] gets NP = HS / _INJECT_BLOCK partials ++ per branch, the layout ``_hc_reduce_fused`` sums. ++ """ ++ lane = gpu.thread_id("x") % 64 ++ row = gpu.block_id("x") ++ part = gpu.block_id("y") ++ hs = K // HC ++ nblk = hs // _INJECT_BLOCK ++ branch = part // nblk ++ col = (part % nblk) * _INJECT_BLOCK + lane * 8 ++ h = fx.rocdl.make_buffer_tensor(H, max_size=False) ++ y = fx.rocdl.make_buffer_tensor(Y, max_size=False) ++ g = fx.rocdl.make_buffer_tensor(G, max_size=False) ++ o = fx.rocdl.make_buffer_tensor(O, max_size=False) ++ ss = fx.rocdl.make_buffer_tensor(SS, max_size=False) ++ gl = _load(g, row * NI + branch, 1, fx.Float32)[0] ++ gate = fx.Float32(2.0) * _sigmoid(gl * fx.Float32(1.0 / HC)) ++ off = row * K + branch * hs + col ++ hv = _load(h, off, 8, fx.BFloat16).to(fx.Float32) ++ yv = _load(y, row * hs + col, 8, fx.BFloat16).to(fx.Float32) ++ ov = (hv + yv * fx.Vector.from_elements([gate] * 8, fx.Float32)).to(fx.BFloat16) ++ _store8(o, off, ov) ++ of = ov.to(fx.Float32) ++ sq = fx.Float32(0.0) ++ for e in range_constexpr(8): ++ sq = sq + of[e] * of[e] ++ for shift in range_constexpr(6): ++ peer = gpu.shuffle(sq, fx.Int32(1 << shift), fx.Int32(64), mode="xor") ++ sq = sq + fx.Float32(peer) ++ if lane == 0: ++ _store(ss, row * (HC * nblk) + part, sq, fx.Float32) ++ ++ ++@flyc.jit ++def _launch_inject( ++ H: fx.Tensor, ++ Y: fx.Tensor, ++ G: fx.Tensor, ++ O: fx.Tensor, ++ SS: fx.Tensor, ++ M: fx.Constexpr[int], ++ K: fx.Constexpr[int], ++ NI: fx.Constexpr[int], ++ stream: fx.Stream, ++): ++ _hc_inject_fused(H, Y, G, O, SS, K, NI).launch( ++ grid=(M, K // _INJECT_BLOCK), block=(64,), stream=stream ++ ) ++ ++ ++def hc_apply_inject(h, y, g): ++ """Elementwise combine h + y * 2 sigmoid(g / HC) per branch, given the inject logits. ++ ++ Returns (combined [M, K] BF16, partial sums of squares [M, HC * HS / 512] FP32 of the ++ combined residual, for the next ``hc_fused_mix``).""" ++ m, k = h.shape ++ if k % (HC * _INJECT_BLOCK) or g.shape != (m, HC) or y.shape != (m, k // HC): ++ raise ValueError("unsupported fused HC combine shape") ++ out = torch.empty_like(h) ++ ss = torch.empty((m, k // _INJECT_BLOCK), device=h.device, dtype=torch.float32) ++ _launch_inject( ++ h, y, g, out, ss, m, k, g.shape[1], torch.cuda.current_stream(h.device) ++ ) ++ return out, ss +diff --git a/python/sglang/srt/environ.py b/python/sglang/srt/environ.py +index 7eba71d046..e5dfe15f8c 100644 +--- a/python/sglang/srt/environ.py ++++ b/python/sglang/srt/environ.py +@@ -1089,6 +1089,9 @@ class Envs: + SGLANG_AITER_INTREE_GEMM_TUNE = EnvBool(True) + # TODO(aiter#6030): remove once ROCm/aiter#6030 is in the aiter pin + SGLANG_AITER_INTREE_MHC_TILE_M16 = EnvBool(True) ++ # Qwen4-Exp decode-sized (<= 128 rows) HC sites on gfx950: the per-branch norm and the ++ # combine's inject GEMV fold into FlyDSL HC mix kernels; the combine becomes elementwise. ++ SGLANG_OPT_QWEN4_FUSED_HC = EnvBool(False) + # Fuse MiniMax-M3 main/index QK norm + RoPE with main KV and index-K cache + # insertion. Requires an AITER build with the fp8_e4m3_unit cache contract. + # Enabled by default for supported configurations; set to 0 to disable. +diff --git a/python/sglang/srt/layers/hyperconnection.py b/python/sglang/srt/layers/hyperconnection.py +index 7be2c1a8fc..cb21322e34 100644 +--- a/python/sglang/srt/layers/hyperconnection.py ++++ b/python/sglang/srt/layers/hyperconnection.py +@@ -7,15 +7,21 @@ import torch.nn as nn + import torch.nn.functional as F + + from sglang.kernels.ops.gemm.hc_mix import fused_hc_mix, fused_hc_mix_supported ++from sglang.srt.environ import envs + from sglang.srt.layers.hc_mix_flydsl import ( + flydsl_hc_mix_supported, + flydsl_hc_mix_weights_supported, + weight_cache_key, + ) + from sglang.srt.utils import is_npu ++from sglang.srt.utils.device import is_gfx95_supported + + _is_npu = is_npu() + ++# (output, partial sums of squares) of the last fused HC combine; a fused mix reuses ++# them only for that same tensor object, otherwise its down kernel recomputes them. ++_last_fused_combine: Optional[tuple[torch.Tensor, torch.Tensor]] = None ++ + + @lru_cache(None) + def _hc_gate_stream(device: int) -> torch.cuda.Stream: +@@ -183,6 +189,17 @@ class GatedResidual(HyperConnectionBase): + self._mix_flydsl_ok = None + self._mix_flydsl_weights = None + self._mix_flydsl_weight_key = None ++ # Decode-sized gfx950 sites: the norm and the inject GEMV fold into the mix, ++ # which hands its combine the inject logits as gate partials. ++ self._fused_hc_ok = ( ++ use_mix ++ and envs.SGLANG_OPT_QWEN4_FUSED_HC.get() ++ and self.hc_count == 4 ++ and self.config.hc_per_branch_norm ++ and is_gfx95_supported() ++ ) ++ self._fused_hc_weights = None ++ self._fused_hc_weight_key = None + + self._gate_stream = None + if use_combine: +@@ -267,6 +284,43 @@ class GatedResidual(HyperConnectionBase): + ) + return self._mix_flydsl_ok + ++ def _fused_mix(self, hyper_input: torch.Tensor): ++ """Fused decode-sized mix, or None when the input does not fit it.""" ++ from sglang.kernels.ops.gemm.hc_fused_flydsl import ( ++ HcFusedWeights, ++ hc_fused_mix, ++ hc_fused_supported, ++ ) ++ ++ down = self.input_mix_weight_down.weight ++ up = self.input_mix_weight_up.weight ++ inject = getattr(self, "block_inject_weight", None) ++ inject = inject.weight if inject is not None else None ++ # The norm and inject weights are folded into the packed copy as well. ++ key = ( ++ weight_cache_key(down, up), ++ weight_cache_key(self.hc_norm.weight, up if inject is None else inject), ++ ) ++ if self._fused_hc_weight_key != key: ++ self._fused_hc_weights = HcFusedWeights( ++ down=down, ++ up=up, ++ inject=inject, ++ norm_weight=self.hc_norm.weight, ++ eps=self.config.rms_norm_eps, ++ ) ++ self._fused_hc_weight_key = key ++ weights = self._fused_hc_weights ++ if not hc_fused_supported(h=hyper_input, weights=weights): ++ return None ++ sumsq = None ++ if _last_fused_combine is not None and _last_fused_combine[0] is hyper_input: ++ sumsq = _last_fused_combine[1] ++ mixed_input, inject_logits = hc_fused_mix( ++ h=hyper_input, weights=weights, sumsq=sumsq ++ ) ++ return mixed_input, (hyper_input, None, inject_logits) ++ + def mix( + self, + hyper_input: torch.Tensor, +@@ -278,6 +332,10 @@ class GatedResidual(HyperConnectionBase): + (*hyper_input.shape[:-1], self.hidden_size), dtype=self.params_dtype + ) + return mixed_input, (hyper_input, hyper_input, None) ++ if self._fused_hc_ok: ++ fused = self._fused_mix(hyper_input) ++ if fused is not None: ++ return fused + + if normalized_input is not None: + assert self.config.hc_per_branch_norm +@@ -383,6 +441,8 @@ class GatedResidual(HyperConnectionBase): + Callers must only pass the norm when no PLE or other update intervenes. + """ + hyper_input, _, partials = residuals ++ if self._fused_hc_ok and partials is not None: ++ return self.combine(block_output, residuals), None + if ( + partials is not None + and next_norm is not None +@@ -412,6 +472,15 @@ class GatedResidual(HyperConnectionBase): + residuals: tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]], + ) -> torch.Tensor: + hyper_input, hyper_input_normed, partials = residuals ++ if self._fused_hc_ok and partials is not None: ++ from sglang.kernels.ops.gemm.hc_fused_flydsl import hc_apply_inject ++ ++ global _last_fused_combine ++ out, sumsq = hc_apply_inject( ++ h=hyper_input, y=block_output.contiguous(), g=partials ++ ) ++ _last_fused_combine = (out, sumsq) ++ return out + if partials is not None: + from sglang.kernels.ops.elementwise.hc_combine_decode import ( + hc_combine_apply, diff --git a/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/02-sglang-45196-qsa-flydsl-sparse-decode.patch b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/02-sglang-45196-qsa-flydsl-sparse-decode.patch new file mode 100644 index 0000000000..957c264b57 --- /dev/null +++ b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/02-sglang-45196-qsa-flydsl-sparse-decode.patch @@ -0,0 +1,160 @@ +# [Perf] [AMD] Qwen3.8: Serve QSA decode with AITER's fused FlyDSL sparse decode on gfx950 +# https://github.com/sgl-project/sglang/pull/45196 (PR head d0d0e41da5fba5c314e8c4a705ab198b23386459) +# Generated against the SGLang checkout of the image (c67db7c762, 2026-11-17); source files only (tests, benchmarks, AOT registry and docs dropped); rebased from the 1ced9a9eb0 version. + +diff --git a/python/sglang/srt/layers/attention/qwen_sparse_attn_backend.py b/python/sglang/srt/layers/attention/qwen_sparse_attn_backend.py +index 9407e50b01..dd373956cb 100644 +--- a/python/sglang/srt/layers/attention/qwen_sparse_attn_backend.py ++++ b/python/sglang/srt/layers/attention/qwen_sparse_attn_backend.py +@@ -16,6 +16,7 @@ import msgspec + import torch + import torch.nn.functional as F + ++from sglang.srt.environ import envs + from sglang.srt.layers.attention.base_attn_backend import AttentionBackend + from sglang.srt.layers.attention.kv_shard_hooks import ( + get_kv_shard_pool, +@@ -56,7 +57,13 @@ from sglang.srt.mem_cache.page_interleave_pool import PageInterleaveKVPoolMixin + from sglang.srt.mem_cache.qsa_kv_pool import QSATokenToKVPool + from sglang.srt.model_executor.forward_mode import ForwardMode + from sglang.srt.runtime_context import get_spec, get_stream +-from sglang.srt.utils import is_hip, is_npu, is_sm100_supported, is_sm120 ++from sglang.srt.utils import ( ++ is_gfx95_supported, ++ is_hip, ++ is_npu, ++ is_sm100_supported, ++ is_sm120, ++) + + logger = logging.getLogger(__name__) + +@@ -114,6 +121,22 @@ def _resolve_trtllm_sparse_decode(): + return trtllm_batch_decode_with_kv_cache + + ++@lru_cache(maxsize=1) ++def _resolve_flydsl_sparse_decode(): ++ """The fused gfx950 FlyDSL decode module, or None when off or unavailable.""" ++ if not (envs.SGLANG_USE_AITER.get() and is_gfx95_supported()): ++ return None ++ try: ++ from aiter.ops.flydsl import qsa_sparse_decode as qsa_flydsl ++ except ImportError: ++ logger.warning( ++ "QSA FlyDSL decode requested but aiter.ops.flydsl.qsa_sparse_decode " ++ "is unavailable" ++ ) ++ return None ++ return qsa_flydsl ++ ++ + @lru_cache(maxsize=1) + def _resolve_flash_attn_varlen_func(): + from sglang.srt.utils import is_hip, is_sm121 +@@ -342,6 +365,7 @@ class QwenSparseAttnBackend(AttentionBackend): + self._mtp_shared_sparse_indices = None + self._trtllm_workspace = None + self._trtllm_counters = {} ++ self._flydsl_decode_workspace = None + self._graph_extend_lens = None + self._graph_extend_lens_pin = None + self._verify_mask = None +@@ -2039,6 +2063,75 @@ class QwenSparseAttnBackend(AttentionBackend): + ) + return output.reshape(q.shape[0], -1) + ++ def _forward_flydsl_fused_sparse( ++ self, ++ flydsl_decode, ++ q: torch.Tensor, ++ k_buffer: torch.Tensor, ++ v_buffer: torch.Tensor, ++ layer, ++ forward_batch, ++ metadata, ++ topk_indices: torch.Tensor, ++ ) -> torch.Tensor: ++ """gfx950 sparse decode straight from the pool: no gather, KV split across CTAs. ++ ++ Each query row is its own length-one sequence, so speculative verify rows ++ need nothing extra. ++ """ ++ batch, topk = topk_indices.shape ++ num_kv_heads = k_buffer.shape[1] ++ num_splits = flydsl_decode.recommended_num_splits( ++ batch, num_kv_heads, topk, q.device ++ ) ++ workspace = self._get_flydsl_decode_workspace( ++ flydsl_decode, ++ batch * q.shape[1] * num_splits, ++ q.shape[1], ++ num_kv_heads, ++ k_buffer.shape[2], ++ topk, ++ q.device, ++ ) ++ output = flydsl_decode.flydsl_qsa_sparse_decode( ++ q.contiguous(), ++ k_buffer, ++ v_buffer, ++ self.req_to_token_pool.req_to_token, ++ ( ++ metadata.row_req_pool_indices ++ if metadata.row_req_pool_indices is not None ++ else forward_batch.req_pool_indices ++ ), ++ topk_indices, ++ metadata.sequence_lengths, ++ layer.scaling, ++ num_splits=num_splits, ++ workspace=workspace, ++ ) ++ return output.reshape(q.shape[0], -1) ++ ++ def _get_flydsl_decode_workspace( ++ self, flydsl_decode, partials, num_q_heads, num_kv_heads, head_dim, topk, device ++ ): ++ # Sized once for every captured batch: graphs keep raw pointers to it, so ++ # it is never reallocated. A larger eager batch gets a per-call workspace. ++ if self._flydsl_decode_workspace is None: ++ capacity = max( ++ partials, ++ flydsl_decode.workspace_partials( ++ self._cuda_graph_max_tokens, num_q_heads, num_kv_heads, topk, device ++ ), ++ ) ++ self._flydsl_decode_workspace = ( ++ torch.empty(capacity, dtype=torch.float32, device=device), ++ torch.empty(capacity, dtype=torch.float32, device=device), ++ torch.empty(capacity * head_dim, dtype=torch.float32, device=device), ++ ) ++ if self._flydsl_decode_workspace[0].numel() < partials: ++ return None ++ return self._flydsl_decode_workspace ++ + def forward_decode( + self, + q: torch.Tensor, +@@ -2099,6 +2192,21 @@ class QwenSparseAttnBackend(AttentionBackend): + trtllm_decode, + ) + ++ flydsl_decode = _resolve_flydsl_sparse_decode() ++ if flydsl_decode is not None and flydsl_decode.can_use_flydsl_qsa_sparse_decode( ++ q, k_buffer, v_buffer ++ ): ++ return self._forward_flydsl_fused_sparse( ++ flydsl_decode, ++ q, ++ k_buffer, ++ v_buffer, ++ layer, ++ forward_batch, ++ metadata, ++ topk_indices, ++ ) ++ + batch, topk = topk_indices.shape + sequence_lens = metadata.sequence_lengths + if metadata.is_cuda_graph: diff --git a/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/03-sglang-48649-qsa-decode-mqa-launch.patch b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/03-sglang-48649-qsa-decode-mqa-launch.patch new file mode 100644 index 0000000000..967928619a --- /dev/null +++ b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/03-sglang-48649-qsa-decode-mqa-launch.patch @@ -0,0 +1,124 @@ +# [Perf] [AMD] qsa: Faster decode MQA logits on ROCm (padded Q, group-strided launch) +# https://github.com/sgl-project/sglang/pull/48649 (PR head 182172f6555504ac6894af5c8ab136e22fa13625) +# Generated against the SGLang checkout of the image (c67db7c762, 2026-11-17); source files only (tests, benchmarks, AOT registry and docs dropped); rebased from the 1ced9a9eb0 version. + +diff --git a/python/sglang/srt/layers/attention/qsa/mqa.py b/python/sglang/srt/layers/attention/qsa/mqa.py +index 7c219fa9ce..2109506010 100644 +--- a/python/sglang/srt/layers/attention/qsa/mqa.py ++++ b/python/sglang/srt/layers/attention/qsa/mqa.py +@@ -313,6 +313,7 @@ if HAS_TILELANG: + min_scored_len: int = 0, + threads: int = 128, + dtype: str = "bfloat16", ++ groups_per_cta: int = 0, + ): + # The MMA layout needs 64 GEMM rows; a compressed page has full_page // ratio, + # so pages are packed as sub-pages of one 64-row tile. +@@ -335,7 +336,15 @@ if HAS_TILELANG: + ): + # A fixed number of CTAs per row strides over that row's groups, so the + # grid no longer scales with the page-table width (the max context). +- with T.Kernel(batch, ctas_per_row, threads=threads) as (bx, cta): ++ # With groups_per_cta > 0 (ROCm) each CTA scores that many consecutive ++ # groups instead and the grid spans the page table; CTAs past a row's ++ # context exit at once. ++ grid_y = ( ++ T.ceildiv(T.ceildiv(max_pages, sub_pages), groups_per_cta) ++ if groups_per_cta > 0 ++ else ctas_per_row ++ ) ++ with T.Kernel(batch, grid_y, threads=threads) as (bx, cta): + q_shared = T.alloc_shared([heads, head_dim], dtype) + k_shared = T.alloc_shared([GROUP, head_dim], dtype) + scores = T.alloc_fragment([GROUP, heads], T.float32) +@@ -346,10 +355,18 @@ if HAS_TILELANG: + + # Rows at or below min_scored_len select every block, so their + # scores are never read. +- if context_len > min_scored_len: ++ if context_len > min_scored_len and cta * groups_per_cta < num_groups: + T.copy(Q[bx, 0, :, :], q_shared) +- for step in T.serial(T.ceildiv(num_groups, ctas_per_row)): +- group = step * ctas_per_row + cta ++ for step in ( ++ T.Pipelined(groups_per_cta, num_stages=1) ++ if groups_per_cta > 0 ++ else T.serial(T.ceildiv(num_groups, ctas_per_row)) ++ ): ++ group = ( ++ cta * groups_per_cta + step ++ if groups_per_cta > 0 ++ else step * ctas_per_row + cta ++ ) + if group < num_groups: + # TileLang's pipeliner rejects dynamic loops around smem + # copies; unroll the sub-pages at the Python level. +@@ -541,6 +558,14 @@ def tilelang_qsa_mqa_prefill_relative( + # CTAs per decode row: few enough levels to bound the TileLang specializations, and + # a grid of about four waves (at least one CTA per row). + _DECODE_CTAS_PER_ROW_LEVELS = (1, 16, 256) ++# CUDA MMA accepts an eight-wide N dimension, while ROCm MFMA requires sixteen; ++# the indexer pads Q to this in its fused prep so the wrapper need not copy it. ++QSA_DECODE_HEAD_ALIGNMENT = 16 if is_hip() else 8 ++# Four wavefronts per CTA on ROCm: about 1.5x faster than 128 threads on MI355X. ++_DECODE_THREADS = 256 if is_hip() else 128 ++# ROCm: four consecutive groups per CTA over a page-table-wide grid is 1.2-1.7x ++# faster than the fixed CTAs per row on MI355X at 50k-200k context (bit-exact). ++_DECODE_GROUPS_PER_CTA = 4 if is_hip() else 0 + + + @functools.lru_cache(maxsize=None) +@@ -595,10 +620,9 @@ def tilelang_qsa_mqa_decode( + ) + if not q.shape[0] or not max_model_len: + return logits +- # CUDA MMA accepts an eight-wide N dimension, while ROCm MFMA requires +- # sixteen. Zero-padding preserves the weight-free head sum on both paths. ++ # Zero-padding preserves the weight-free head sum. + query_heads, head_dim = q.shape[1:] +- head_alignment = 16 if is_hip() else 8 ++ head_alignment = QSA_DECODE_HEAD_ALIGNMENT + kernel_heads = max( + head_alignment, + ((query_heads + head_alignment - 1) // head_alignment) * head_alignment, +@@ -617,9 +641,15 @@ def tilelang_qsa_mqa_decode( + heads=kernel_heads, + head_dim=head_dim, + page_size=page_size, +- ctas_per_row=_decode_ctas_per_row(q.shape[0], q.device), ++ ctas_per_row=( ++ 1 ++ if _DECODE_GROUPS_PER_CTA ++ else _decode_ctas_per_row(q.shape[0], q.device) ++ ), + min_scored_len=min_scored_len, ++ threads=_DECODE_THREADS, + dtype=_TILELANG_DTYPES[scoring_dtype], ++ groups_per_cta=_DECODE_GROUPS_PER_CTA, + )( + q_kernel.unsqueeze(1).contiguous(), + k_cache.to(scoring_dtype).contiguous(), +diff --git a/python/sglang/srt/layers/attention/qsa/qsa_indexer.py b/python/sglang/srt/layers/attention/qsa/qsa_indexer.py +index f9e2d499e0..79d5087104 100644 +--- a/python/sglang/srt/layers/attention/qsa/qsa_indexer.py ++++ b/python/sglang/srt/layers/attention/qsa/qsa_indexer.py +@@ -19,6 +19,7 @@ from sglang.srt.layers.attention.qsa.metadata import ( + ) + from sglang.srt.layers.attention.qsa.mqa import ( + HAS_TILELANG, ++ QSA_DECODE_HEAD_ALIGNMENT, + qsa_mqa_decode, + qsa_mqa_prefill, + qsa_mqa_prefill_relative, +@@ -744,8 +745,9 @@ class QSAIndexer(MultiPlatformOp): + pool=indexer_metadata.token_to_kv_pool, + cache_loc=state_slots, + q_heads_padded=( +- # The tilelang decode MQA kernel needs query heads in multiples of 8. +- ((self.index_n_heads + 7) // 8) * 8 ++ # Pad to the tilelang decode MQA kernel's head alignment. ++ -(-self.index_n_heads // QSA_DECODE_HEAD_ALIGNMENT) ++ * QSA_DECODE_HEAD_ALIGNMENT + if (forward_mode.is_decode() or is_target_verify or is_draft_extend) + else None + ), diff --git a/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/04-sglang-45529-qwen35-fuse-selfattn-prepare.patch b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/04-sglang-45529-qwen35-fuse-selfattn-prepare.patch new file mode 100644 index 0000000000..5929f7aaf8 --- /dev/null +++ b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/04-sglang-45529-qwen35-fuse-selfattn-prepare.patch @@ -0,0 +1,90 @@ +# [Perf] [AMD] qwen3.5: Fuse self-attn prepare on gfx950 (norm+RoPE+gate) +# https://github.com/sgl-project/sglang/pull/45529 (PR head e4fd7d2ee6cd3f86b0eede68cf4c6447e4cbdb00) +# Generated against the SGLang checkout of the image (c67db7c762, 2026-11-17); source files only (tests, benchmarks, AOT registry and docs dropped); rebased from the 1ced9a9eb0 version. + +diff --git a/python/sglang/kernels/ops/attention/fused_qk_rmsnorm_rope_gate.py b/python/sglang/kernels/ops/attention/fused_qk_rmsnorm_rope_gate.py +index e9eb2423f9..b6a7598b3f 100644 +--- a/python/sglang/kernels/ops/attention/fused_qk_rmsnorm_rope_gate.py ++++ b/python/sglang/kernels/ops/attention/fused_qk_rmsnorm_rope_gate.py +@@ -12,7 +12,14 @@ from typing import Optional, Tuple + import torch + import triton + import triton.language as tl +-from triton.language.extra.cuda import libdevice ++ ++try: ++ from triton.language.extra.cuda import libdevice ++except Exception: # noqa: BLE001 ++ # ROCm / non-CUDA Triton may not ship the CUDA libdevice shim. libdevice is ++ # only dereferenced under EXPLICIT_ROPE_FMA (constexpr, default False), which ++ # Triton prunes, so a None placeholder keeps the kernel importable on gfx950. ++ libdevice = None + + from sglang.kernels.arch import current_arch + +diff --git a/python/sglang/srt/models/qwen3_5.py b/python/sglang/srt/models/qwen3_5.py +index f3cf967076..ae29520344 100644 +--- a/python/sglang/srt/models/qwen3_5.py ++++ b/python/sglang/srt/models/qwen3_5.py +@@ -259,10 +259,26 @@ def _qwen3_5_stage_facts( + ) + + ++# Single-launch fused QK-GemmaRMSNorm + partial-RoPE + gate-deinterleave kernel, ++# the same Triton kernel the CUDA path uses. It replaces the aiter/HIP 2-kernel ++# prepare (fused_qk_gemma_rmsnorm_with_gate + rotary_emb). It is plain Triton and ++# handles mrope + partial rotary + the Gemma norm, so it is not gfx-specific. ++# Import it defensively on aiter: a ROCm Triton that cannot import it leaves the ++# name None, and _prepare_qkv_gate falls back to the 2-kernel path with no ++# regression. (aiter's fused_qk_norm_rope_gate_fp8_quant is NOT a fit: it takes ++# 1-D positions only -> no mrope, and always emits an FP8 prefill suffix.) ++fused_qk_gemma_rmsnorm_rope_gate = None + if _is_cuda: + from sglang.kernels.ops.attention.fused_qk_rmsnorm_rope_gate import ( + fused_qk_gemma_rmsnorm_rope_gate, + ) ++elif _use_aiter: ++ try: ++ from sglang.kernels.ops.attention.fused_qk_rmsnorm_rope_gate import ( ++ fused_qk_gemma_rmsnorm_rope_gate, ++ ) ++ except Exception: ++ pass + + if _is_cpu: + _fused_sigmoid_mul_cpu = torch.ops.sgl_kernel.fused_sigmoid_mul_cpu +@@ -1457,6 +1473,15 @@ class Qwen3_5AttentionDecoderLayer(nn.Module): + + def forward_prepare_cuda_fused(self, positions, hidden_states): + """Fused QK GemmaRMSNorm + NeoX RoPE + gate deinterleave.""" ++ # The aiter fused AR+RMSNorm(+quant) path hands down a (bf16, fp8, scale) ++ # tuple; unpack it to the side qkv_proj consumes, exactly as ++ # forward_prepare_native / forward_prepare_fused_gate do. No-op on CUDA ++ # (where _use_aiter is False), required on HIP where this path is now ++ # reached with fused AR enabled. ++ if _use_aiter and isinstance(hidden_states, tuple): ++ hidden_states = _select_fused_ar_input_for_linear( ++ hidden_states, self.qkv_proj ++ ) + qkv, _ = self.qkv_proj(hidden_states) + if self.attn_output_gate: + q_gate, k, v = qkv.split( +@@ -1594,6 +1619,18 @@ class Qwen3_5AttentionDecoderLayer(nn.Module): + positions=positions, + hidden_states=hidden_states, + ) ++ if ( ++ _use_aiter ++ and self.attn_output_gate ++ and fused_qk_gemma_rmsnorm_rope_gate is not None ++ ): ++ # One fused Triton kernel (norm + partial RoPE + gate) in place of ++ # fused_qk_gemma_rmsnorm_with_gate + rotary_emb. Enabled on any aiter ++ # HIP GPU; the import leaves the name None where it is unsupported. ++ return self.forward_prepare_cuda_fused( ++ positions=positions, ++ hidden_states=hidden_states, ++ ) + if (_is_hip or _is_xpu or _is_cpu) and self.attn_output_gate: + return self.forward_prepare_fused_gate( + positions=positions, diff --git a/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/05-sglang-41879-aiter-gdn-conv-prefill.patch b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/05-sglang-41879-aiter-gdn-conv-prefill.patch new file mode 100644 index 0000000000..5fc262fdc6 --- /dev/null +++ b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/05-sglang-41879-aiter-gdn-conv-prefill.patch @@ -0,0 +1,101 @@ +# [Perf] [AMD] Qwen3.5/Qwen3.8: Opt-in AITER FlyDSL causal conv1d prefill +# https://github.com/sgl-project/sglang/pull/41879 (PR head 5a2bc3760b46e6c29a2aa12c59d3e71804f930c5) +# Generated against the SGLang checkout of the image (c67db7c762, 2026-11-17); source files only (tests, benchmarks, AOT registry and docs dropped); rebased from the 1ced9a9eb0 version. + +diff --git a/python/sglang/srt/layers/attention/linear/gdn_backend.py b/python/sglang/srt/layers/attention/linear/gdn_backend.py +index 24fd722665..2cf6a0f935 100644 +--- a/python/sglang/srt/layers/attention/linear/gdn_backend.py ++++ b/python/sglang/srt/layers/attention/linear/gdn_backend.py +@@ -1,3 +1,4 @@ ++import logging + import time + from typing import Optional, Tuple, Union + +@@ -62,9 +63,12 @@ from sglang.srt.runtime_context import ( + ) + from sglang.srt.speculative.ragged_verify import ragged_verify_compact_enabled + from sglang.srt.utils import is_cpu, is_cuda, is_hip, is_npu, is_xpu ++from sglang.srt.utils.common import get_bool_env_var + from sglang.srt.utils.device import is_pin_memory_available + from sglang.srt.utils.log_utils import rank0_log + ++logger = logging.getLogger(__name__) ++ + _is_hip = is_hip() + + if not is_cpu(): +@@ -370,6 +374,54 @@ def _validate_gdn_target_verify_layout(model_runner: ModelRunner) -> None: + ) + + ++_AITER_GDN_CONV_UNAVAILABLE = False ++ ++ ++def _aiter_gdn_prefill_conv(): ++ """AITER's FlyDSL prefill causal conv, or None if it cannot be used. ++ ++ Opt-in: SGLANG_USE_AITER plus SGLANG_AITER_GDN_CONV. It implements the same ++ ``causal_conv1d_fn`` contract (one output, ``conv_states`` updated in place), ++ mapping channels to lanes instead of going through an implicit GEMM. ++ Measured on MI355X at ISL 32768 it is ~1.8x the Triton prefill convolution. ++ """ ++ global _AITER_GDN_CONV_UNAVAILABLE ++ if _AITER_GDN_CONV_UNAVAILABLE: ++ return None ++ if not ( ++ get_bool_env_var("SGLANG_USE_AITER") ++ and get_bool_env_var("SGLANG_AITER_GDN_CONV") ++ ): ++ _AITER_GDN_CONV_UNAVAILABLE = True ++ return None ++ try: ++ from aiter.ops.flydsl.causal_conv1d_flydsl import ( ++ causal_conv1d_prefill_flydsl_fn, ++ ) ++ except ImportError: ++ logger.info( ++ "aiter FlyDSL prefill conv unavailable; keeping the Triton convolution" ++ ) ++ _AITER_GDN_CONV_UNAVAILABLE = True ++ return None ++ return causal_conv1d_prefill_flydsl_fn ++ ++ ++def _prefill_causal_conv1d(*args, **kwargs): ++ """Dispatch the GDN prefill convolution, falling back to Triton. ++ ++ The AITER kernel raises on shapes or dtypes it does not cover rather than ++ degrading silently, so an unsupported batch simply lands on Triton here. ++ """ ++ fn = _aiter_gdn_prefill_conv() ++ if fn is not None: ++ try: ++ return fn(*args, **kwargs) ++ except ValueError as exc: ++ logger.debug("aiter FlyDSL prefill conv declined this batch: %s", exc) ++ return causal_conv1d_fn(*args, **kwargs) ++ ++ + class GDNKernelDispatcher: + """Dispatches GDN kernel calls to the appropriate backend per mode.""" + +@@ -1298,12 +1350,13 @@ class GDNAttnBackend(MambaAttnBackendBase): + ) -> torch.Tensor: + block_table = self.forward_metadata.conv_block_table + conv_kwargs = {"block_table": block_table} if block_table is not None else {} +- # The compiled CUDA conv assumes packed slots; Triton follows the strides. +- conv_fn = ( +- causal_conv1d_fn_triton +- if not conv_states.is_contiguous() and not is_cpu() +- else causal_conv1d_fn +- ) ++ strided_slots = not conv_states.is_contiguous() and not is_cpu() ++ if block_table is not None or strided_slots: ++ # The block-table launch and strided state slots are Triton-only (the compiled ++ # CUDA conv assumes packed slots); the AITER conv never sees them. ++ conv_fn = causal_conv1d_fn_triton if strided_slots else causal_conv1d_fn ++ else: ++ conv_fn = _prefill_causal_conv1d + return conv_fn( + mixed_qkv.transpose(0, 1), + layer.conv_weights, diff --git a/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/06-sglang-44103-aiter-gdn-chunked-prefill.patch b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/06-sglang-44103-aiter-gdn-chunked-prefill.patch new file mode 100644 index 0000000000..2e6e23bf61 --- /dev/null +++ b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/06-sglang-44103-aiter-gdn-chunked-prefill.patch @@ -0,0 +1,443 @@ +# [Perf] [AMD] Qwen3.8-flash-next: Opt-in AITER GDN chunked prefill (opt_vk stages and fused FlyDSL) +# https://github.com/sgl-project/sglang/pull/44103 (PR head 7bd6b56d543574f4cde696585ad18b77a59b57b4) +# Generated against the SGLang checkout of the image (c67db7c762, 2026-11-17); source files only (tests, benchmarks, AOT registry and docs dropped); rebased from the 1ced9a9eb0 version. +# Adapted to the image: its GDN extend() takes **kwargs (CUDA-graph chunk tables), so the new _extend() receives them too, and the AITER prefill is skipped for a captured prefill graph. + +diff --git a/python/sglang/srt/environ.py b/python/sglang/srt/environ.py +index e5dfe15f8c..e2005a6985 100644 +--- a/python/sglang/srt/environ.py ++++ b/python/sglang/srt/environ.py +@@ -1096,6 +1096,16 @@ class Envs: + # insertion. Requires an AITER build with the fp8_e4m3_unit cache contract. + # Enabled by default for supported configurations; set to 0 to disable. + SGLANG_M3_USE_AITER_FUSED_QKNORM = EnvBool(True) ++ # Run GDN chunked prefill through AITER's opt_vk stages (fused FlyDSL prepare, ++ # tuned hidden-state kernel) instead of the Triton FLA chunk path. Requires ++ # SGLANG_USE_AITER. Measured on MI355X: 1.4x on the chunk stage, GSM8K unchanged. ++ SGLANG_AITER_GDN_PREFILL = EnvBool(False) ++ # Hidden-state kernel for SGLANG_AITER_GDN_PREFILL: "triton", "hip" or "flydsl". ++ # Measured on MI355X at T=16384: all three within 6%, but hip/flydsl land at ++ # 1.8x the final-state error of triton against an fp32 recurrence. ++ # "fused" instead runs the whole chunked prefill as one FlyDSL kernel ++ # (state kept on chip, l2norm and track snapshot in-kernel). ++ SGLANG_AITER_GDN_PREFILL_H = EnvStr("triton") + SGLANG_USE_AITER_AG = EnvBool(True) + # Run the gfx950 TP4 quick all-reduce on the JIT build (quick_all_reduce_hip) instead of + # sgl-kernel's; off by default, MiniMax-M3.1 turns it on at TP4 under INT4 or INT8. +diff --git a/python/sglang/srt/layers/attention/linear/gdn_backend.py b/python/sglang/srt/layers/attention/linear/gdn_backend.py +index 2cf6a0f935..5baa15a77e 100644 +--- a/python/sglang/srt/layers/attention/linear/gdn_backend.py ++++ b/python/sglang/srt/layers/attention/linear/gdn_backend.py +@@ -1718,6 +1718,7 @@ class GDNAttnBackend(MambaAttnBackendBase): + output=kwargs.get("linear_attn_output"), + layer_id=layer.layer_id, + extend_prefix_lens=forward_batch.extend_prefix_lens, ++ seq_lens_cpu=forward_batch.extend_seq_lens_cpu, + track_state=h_track_buf, + needs_track_state=( + forward_metadata.has_mamba_track_mask +diff --git a/python/sglang/srt/layers/attention/linear/kernels/gdn_aiter_prefill.py b/python/sglang/srt/layers/attention/linear/kernels/gdn_aiter_prefill.py +new file mode 100644 +index 0000000000..e78681a343 +--- /dev/null ++++ b/python/sglang/srt/layers/attention/linear/kernels/gdn_aiter_prefill.py +@@ -0,0 +1,209 @@ ++"""GDN chunked prefill on ROCm through AITER. ++ ++Two paths: the opt_vk stages (prepare, hidden-state kernel, output kernel), ++mirroring ``aiter.ops.triton.gated_delta_net.chunk_gated_delta_rule_opt_vk`` ++but called stage by stage because that entry point drops the per-chunk states ++``h`` that radix state tracking reads; and a single fused FlyDSL kernel that ++keeps the state on chip and writes the tracked chunk-boundary state itself. ++""" ++ ++from __future__ import annotations ++ ++import logging ++from collections.abc import Sequence ++ ++import torch ++ ++logger = logging.getLogger(__name__) ++ ++H_KERNELS = ("hip", "flydsl", "triton", "fused") ++FUSED = "fused" ++ ++ ++class AiterGDNPrefill: ++ """AITER GDN prefill: the opt_vk stages, or the single fused FlyDSL kernel.""" ++ ++ def __init__(self, h_kernel: str): ++ if h_kernel not in H_KERNELS: ++ raise ValueError( ++ f"SGLANG_AITER_GDN_PREFILL_H must be one of {H_KERNELS}, " ++ f"got {h_kernel!r}" ++ ) ++ self._h_kernel = h_kernel ++ # Only the fused kernel writes the fp32 chunk-boundary snapshot itself. ++ self.writes_track_state = h_kernel == FUSED ++ if h_kernel == FUSED: ++ from aiter.ops.flydsl.gdn_fused_prefill import ( ++ gdn_fused_prefill_fwd, ++ gdn_fused_prefill_supported, ++ ) ++ ++ self._fused = gdn_fused_prefill_fwd ++ self._fused_supported = gdn_fused_prefill_supported ++ logger.info("Using AITER fused FlyDSL GDN chunked prefill") ++ return ++ from aiter.ops.flydsl.linear_attention_prefill_kernels import ( ++ gdn_prepare_flydsl_supported, ++ gdn_prepare_fwd_flydsl, ++ ) ++ from aiter.ops.triton._triton_kernels.gated_delta_net.prefill.chunk import ( ++ chunk_fwd_o_opt_vk, ++ chunk_gated_delta_rule_fwd_h_opt_vk, ++ fused_chunk_local_cumsum_scaled_dot_kkt_fwd, ++ fused_solve_tril_recompute_w_u, ++ ) ++ from aiter.ops.triton._triton_kernels.gated_delta_net.utils import ( ++ build_gated_delta_rule_prefill_metadata, ++ l2norm_fwd, ++ ) ++ ++ self._prepare_supported = gdn_prepare_flydsl_supported ++ self._prepare_flydsl = gdn_prepare_fwd_flydsl ++ self._cumsum_kkt = fused_chunk_local_cumsum_scaled_dot_kkt_fwd ++ self._solve_w_u = fused_solve_tril_recompute_w_u ++ self._fwd_o = chunk_fwd_o_opt_vk ++ self._build_metadata = build_gated_delta_rule_prefill_metadata ++ self._l2norm = l2norm_fwd ++ if h_kernel == "hip": ++ from aiter.ops.chunk_gated_delta_rule_fwd_h import ( ++ chunk_gated_delta_rule_fwd_h_hip_fn, ++ ) ++ ++ self._fwd_h = chunk_gated_delta_rule_fwd_h_hip_fn ++ elif h_kernel == "flydsl": ++ from aiter.ops.flydsl.linear_attention_prefill_kernels import ( ++ chunk_gated_delta_rule_fwd_h_flydsl_opt, ++ ) ++ ++ self._fwd_h = chunk_gated_delta_rule_fwd_h_flydsl_opt ++ else: ++ self._fwd_h = chunk_gated_delta_rule_fwd_h_opt_vk ++ self._metadata_key: tuple[int, ...] | None = None ++ self._metadata = None ++ self._metadata_cu_seqlens: torch.Tensor | None = None ++ logger.info("Using AITER opt_vk GDN prefill (hidden state: %s)", h_kernel) ++ ++ def _prefill_metadata(self, seq_lens_cpu: Sequence[int], cu_seqlens: torch.Tensor): ++ # Built from host lengths only, so one build serves every GDN layer of a ++ # forward without a device-to-host read. AITER binds the metadata to the ++ # exact cu_seqlens tensor object, hence the identity check. ++ key = tuple(int(n) for n in seq_lens_cpu) ++ if key != self._metadata_key or cu_seqlens is not self._metadata_cu_seqlens: ++ self._metadata = self._build_metadata( ++ key, cu_seqlens=cu_seqlens, chunk_size=64 ++ ) ++ self._metadata_key = key ++ self._metadata_cu_seqlens = cu_seqlens ++ return self._metadata ++ ++ def extend( ++ self, ++ q: torch.Tensor, ++ k: torch.Tensor, ++ v: torch.Tensor, ++ g: torch.Tensor, ++ beta: torch.Tensor, ++ *, ++ ssm_states: torch.Tensor, ++ cache_indices: torch.Tensor, ++ cu_seqlens: torch.Tensor, ++ seq_lens_cpu: Sequence[int], ++ track_state: torch.Tensor | None = None, ++ track_chunk_idx: torch.Tensor | None = None, ++ ) -> tuple[torch.Tensor, torch.Tensor | None] | None: ++ """Run prefill with the pool state updated in place; returns (o, h). ++ ++ q/k: [1, T, Hg, K]; v: [1, T, H, V]; g (natural-log decay), beta: ++ [1, T, H]; ssm_states: [slots, H, V, K]; h: [1, num_chunks, H, V, K], ++ or None from the fused kernel, which instead fills ``track_state`` ++ (fp32 [N, H, V, K]) at ``track_chunk_idx`` when those are given. ++ Returns None, touching nothing, when the fused kernel declines the ++ operands. ++ """ ++ if self._h_kernel == FUSED: ++ if not self._fused_supported(q, k, v, g, beta, ssm_states): ++ return None ++ o = self._fused( ++ q, ++ k, ++ v, ++ g, ++ beta, ++ ssm_states=ssm_states, ++ cache_indices=cache_indices, ++ cu_seqlens=cu_seqlens, ++ track_state=track_state, ++ track_chunk_idx=track_chunk_idx, ++ ) ++ return o, None ++ metadata = self._prefill_metadata(seq_lens_cpu, cu_seqlens) ++ # q/k may be strided views of the packed projection; AITER's l2norm ++ # flattens with view(). ++ q, _ = self._l2norm(q.contiguous()) ++ k, _ = self._l2norm(k.contiguous()) ++ v = v.contiguous() ++ # Padded rows carry -1; slot 0 is the reserved padding slot, and the HIP ++ # kernel does not guard negative slots. ++ state_indices = cache_indices.clamp(min=0).to(torch.int32) ++ ++ if self._prepare_supported(k, v): ++ w, u, g_cumsum = self._prepare_flydsl( ++ k=k, ++ v=v, ++ g=g, ++ beta=beta, ++ cu_seqlens=cu_seqlens, ++ use_exp2=True, ++ prefill_metadata=metadata, ++ ) ++ else: ++ g_cumsum, A_raw = self._cumsum_kkt( ++ k=k, ++ beta=beta, ++ g=g, ++ cu_seqlens=cu_seqlens, ++ use_exp2=True, ++ prefill_metadata=metadata, ++ ) ++ w, u = self._solve_w_u( ++ A_raw=A_raw, ++ k=k, ++ v=v, ++ beta=beta, ++ g_cumsum=g_cumsum, ++ cu_seqlens=cu_seqlens, ++ use_exp2=True, ++ prefill_metadata=metadata, ++ ) ++ ++ h_kwargs = dict( ++ k=k, ++ w=w, ++ u=u, ++ g=g_cumsum, ++ initial_state=ssm_states, ++ output_final_state=True, ++ cu_seqlens=cu_seqlens, ++ state_dtype=ssm_states.dtype, ++ use_exp2=True, ++ prefill_metadata=metadata, ++ initial_state_indices=state_indices, ++ inplace_final_state=True, ++ ) ++ if self._h_kernel != "triton": ++ h_kwargs["g_head_major"] = True ++ h, v_new, _ = self._fwd_h(**h_kwargs) ++ ++ o = self._fwd_o( ++ q=q, ++ k=k, ++ v=v_new, ++ o=v.new_empty(v.shape), ++ h=h, ++ g=g_cumsum, ++ scale=k.shape[-1] ** -0.5, ++ cu_seqlens=cu_seqlens, ++ use_exp2=True, ++ prefill_metadata=metadata, ++ ) ++ return o, h +diff --git a/python/sglang/srt/layers/attention/linear/kernels/gdn_triton.py b/python/sglang/srt/layers/attention/linear/kernels/gdn_triton.py +index 90709c9b89..184264d303 100644 +--- a/python/sglang/srt/layers/attention/linear/kernels/gdn_triton.py ++++ b/python/sglang/srt/layers/attention/linear/kernels/gdn_triton.py +@@ -1,11 +1,20 @@ ++import logging + from typing import Optional + + import torch + ++from sglang.srt.environ import envs ++from sglang.srt.layers.attention.linear.kernels.gdn_aiter_prefill import ( ++ FUSED as AITER_GDN_PREFILL_FUSED, ++) + from sglang.srt.layers.attention.linear.kernels.kernel_backend import ( + LinearAttnKernelBase, + ) +-from sglang.srt.utils import is_cpu, is_npu, is_xpu ++from sglang.srt.utils import is_cpu, is_hip, is_npu, is_xpu ++ ++logger = logging.getLogger(__name__) ++ ++_is_hip = is_hip() + + if not is_cpu(): + from sglang.kernels.ops.attention.fla.chunk import chunk_gated_delta_rule +@@ -39,6 +48,59 @@ elif is_xpu(): + ) + + ++_AITER_GDN_PREFILL = None ++_AITER_GDN_PREFILL_UNAVAILABLE = False ++ ++ ++def _aiter_gdn_prefill_requested() -> bool: ++ return envs.SGLANG_USE_AITER.get() and envs.SGLANG_AITER_GDN_PREFILL.get() ++ ++ ++def _aiter_gdn_prefill(): ++ """AITER's chunked prefill, or None if it cannot be used. ++ ++ Opt-in: SGLANG_USE_AITER plus SGLANG_AITER_GDN_PREFILL. It replaces the five ++ Triton FLA prefill kernels with either the opt_vk stages (fused FlyDSL ++ prepare, a tuned hidden-state kernel, the VK output kernel) or, with ++ SGLANG_AITER_GDN_PREFILL_H=fused, one FlyDSL kernel for the whole chunk loop. ++ """ ++ global _AITER_GDN_PREFILL, _AITER_GDN_PREFILL_UNAVAILABLE ++ if _AITER_GDN_PREFILL is not None or _AITER_GDN_PREFILL_UNAVAILABLE: ++ return _AITER_GDN_PREFILL ++ if not _aiter_gdn_prefill_requested(): ++ _AITER_GDN_PREFILL_UNAVAILABLE = True ++ return None ++ try: ++ from sglang.srt.layers.attention.linear.kernels.gdn_aiter_prefill import ( ++ AiterGDNPrefill, ++ ) ++ ++ _AITER_GDN_PREFILL = AiterGDNPrefill(envs.SGLANG_AITER_GDN_PREFILL_H.get()) ++ except ImportError as exc: ++ logger.info("aiter opt_vk GDN prefill unavailable (%s); keeping Triton", exc) ++ _AITER_GDN_PREFILL_UNAVAILABLE = True ++ return _AITER_GDN_PREFILL ++ ++ ++def _fill_track_state_from_h( ++ h: torch.Tensor, ++ track_state: torch.Tensor, ++ track_chunk_idx: torch.Tensor, ++ query_start_loc: torch.Tensor, ++) -> None: ++ """Copy each sequence's tracked chunk-start state out of the per-chunk ``h``. ++ ++ ``h`` is [1, total_chunks, H, V, K] with each sequence's chunks contiguous; ++ rows with ``track_chunk_idx < 0`` receive an arbitrary chunk and are never ++ read. Index math stays on the device so the copy does not sync the stream. ++ """ ++ seq_lens = query_start_loc[1:] - query_start_loc[:-1] ++ num_chunks = (seq_lens + 63) // 64 ++ first_chunk = torch.cumsum(num_chunks, 0) - num_chunks ++ src = (first_chunk + track_chunk_idx.clamp(min=0)).clamp(max=h.shape[1] - 1) ++ track_state.copy_(h[0].index_select(0, src.long())) ++ ++ + class TritonGDNKernel(LinearAttnKernelBase): + """Triton-based kernel for GDN (Gated Delta Network) linear attention.""" + +@@ -47,6 +109,15 @@ class TritonGDNKernel(LinearAttnKernelBase): + # The chunk kernel steps slots by the pool's stride(0) in int64. + extend_honors_slot_pitch: bool = True + ++ def __init__(self): ++ # The AITER fused prefill writes the fp32 track snapshot in-kernel; any ++ # batch it declines falls back to a kernel whose h fills the snapshot. ++ self.supports_track_state_snapshot = ( ++ _is_hip ++ and _aiter_gdn_prefill_requested() ++ and envs.SGLANG_AITER_GDN_PREFILL_H.get() == AITER_GDN_PREFILL_FUSED ++ ) ++ + def packed_decode( + self, + mixed_qkv: torch.Tensor, +@@ -185,6 +256,51 @@ class TritonGDNKernel(LinearAttnKernelBase): + use_qk_l2norm_in_kernel: bool = True, + out: Optional[torch.Tensor] = None, + output_indices: Optional[torch.Tensor] = None, ++ seq_lens_cpu: list[int] | None = None, ++ track_state: torch.Tensor | None = None, ++ track_chunk_idx: torch.Tensor | None = None, ++ **kwargs, ++ ) -> tuple: ++ o, last_state, h = self._extend( ++ q, ++ k, ++ v, ++ g, ++ beta, ++ ssm_states=ssm_states, ++ cache_indices=cache_indices, ++ query_start_loc=query_start_loc, ++ inplace_update=inplace_update, ++ use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, ++ out=out, ++ output_indices=output_indices, ++ seq_lens_cpu=seq_lens_cpu, ++ track_state=track_state, ++ track_chunk_idx=track_chunk_idx, ++ **kwargs, ++ ) ++ if track_state is not None and h is not None: ++ _fill_track_state_from_h(h, track_state, track_chunk_idx, query_start_loc) ++ return o, last_state, h ++ ++ def _extend( ++ self, ++ q: torch.Tensor, ++ k: torch.Tensor, ++ v: torch.Tensor, ++ g: torch.Tensor, ++ beta: torch.Tensor, ++ *, ++ ssm_states: torch.Tensor, ++ cache_indices: torch.Tensor, ++ query_start_loc: torch.Tensor, ++ inplace_update: bool, ++ use_qk_l2norm_in_kernel: bool, ++ out: Optional[torch.Tensor], ++ output_indices: Optional[torch.Tensor], ++ seq_lens_cpu: list[int] | None, ++ track_state: torch.Tensor | None, ++ track_chunk_idx: torch.Tensor | None, + **kwargs, + ) -> tuple: + recurrent_state = ssm_states +@@ -222,6 +338,35 @@ class TritonGDNKernel(LinearAttnKernelBase): + # The external NPU kernel does not expose the optional write-back + # control. Its existing behavior is equivalent to True. + inplace_update_args = {} ++ elif ( ++ _is_hip ++ and inplace_update ++ and seq_lens_cpu is not None ++ and len(seq_lens_cpu) == query_start_loc.numel() - 1 ++ and ssm_states.is_contiguous() ++ # A captured prefill graph needs static metadata; AITER's is built per forward. ++ and not graph_table_args ++ # The AITER prefill is the plain l2-normed chunk kernel with its own output. ++ and out is None ++ and use_qk_l2norm_in_kernel ++ and _aiter_gdn_prefill() is not None ++ ): ++ aiter_result = _aiter_gdn_prefill().extend( ++ q, ++ k, ++ v, ++ g, ++ beta, ++ ssm_states=ssm_states, ++ cache_indices=cache_indices, ++ cu_seqlens=query_start_loc, ++ seq_lens_cpu=seq_lens_cpu, ++ track_state=track_state, ++ track_chunk_idx=track_chunk_idx, ++ ) ++ if aiter_result is not None: ++ o, h = aiter_result ++ return o, None, h + + return chunk_gated_delta_rule( + q=q, diff --git a/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/07-sglang-48090-mtp-sparse-rejection-target-probs.patch b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/07-sglang-48090-mtp-sparse-rejection-target-probs.patch new file mode 100644 index 0000000000..9d656f4904 --- /dev/null +++ b/inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/qwen3.8next/sglang/mi355x-fp4-mtp/patches/07-sglang-48090-mtp-sparse-rejection-target-probs.patch @@ -0,0 +1,161 @@ +# [Perf] [AMD] spec: Skip the vocabulary-wide sort in MTP rejection-sampling verify +# https://github.com/sgl-project/sglang/pull/48090 (PR head 3d0601e162756717ede35abd092c9e1889f33bf5) +# Generated against the SGLang checkout of the image (c67db7c762, 2026-11-17); source files only (tests, benchmarks, AOT registry and docs dropped); rebased from the 1ced9a9eb0 version. +# Backport: the PR sits on a newer main. The image lacks sglang#41916, so the top-p rescale helper +# (_adjust_top_p_for_top_k) is copied into eagle_utils.py instead of imported from dflash_utils. + +diff --git a/python/sglang/srt/speculative/eagle_utils.py b/python/sglang/srt/speculative/eagle_utils.py +index a775dd3425..1c5e927737 100644 +--- a/python/sglang/srt/speculative/eagle_utils.py ++++ b/python/sglang/srt/speculative/eagle_utils.py +@@ -62,9 +62,11 @@ if TYPE_CHECKING: + + _is_cuda = is_cuda() + _is_hip = is_hip() ++_use_aiter = envs.SGLANG_USE_AITER.get() and _is_hip + _is_xpu = is_xpu() + _is_cpu = is_cpu() + _COMPACT_VERIFY_SAMPLING = envs.SGLANG_OPT_SPEC_COMPACT_VERIFY_SAMPLING.get() ++_COMPACT_VERIFY_SAMPLING_SET = envs.SGLANG_OPT_SPEC_COMPACT_VERIFY_SAMPLING.is_set() + _PACKED_VERIFY_BCAST = envs.SGLANG_OPT_SPEC_PACKED_VERIFY_BCAST.get() + + # The binding defaults probe this explicit capability once instead of relying on +@@ -603,11 +605,71 @@ def _apply_joint_top_k_top_p( + return probs + + ++@torch.compile(dynamic=True) ++def _adjust_top_p_for_top_k( ++ scaled_topk_logits: torch.Tensor, ++ full_logits: torch.Tensor, ++ top_ps: torch.Tensor, ++ temperatures: Optional[torch.Tensor] = None, ++) -> torch.Tensor: ++ """Rescale top-p to retained top-k mass for unseeded sampling (the same helper ++ as dflash_utils._adjust_top_p_for_top_k of sglang#41916, which the image lacks).""" ++ if temperatures is not None: ++ full_logits = full_logits.float() / temperatures ++ max_logits = scaled_topk_logits.amax(dim=-1, keepdim=True) ++ topk_sum = (scaled_topk_logits - max_logits).exp().sum(dim=-1, keepdim=True) ++ full_sum = (full_logits - max_logits).exp().sum(dim=-1, keepdim=True) ++ return torch.clamp(top_ps * (full_sum / topk_sum), max=1.0) ++ ++ ++def _sparse_rejection_target_probs( ++ next_token_logits: torch.Tensor, ++ sampling_info: SamplingBatchInfo, ++ rows_per_request: int, ++ max_top_k: int, ++) -> torch.Tensor: ++ """The dense rejection target probs (softmax, top-k and top-p renorm) built on ++ each row's top-k support, ties kept, without a vocabulary-wide sort.""" ++ rows, vocab_size = next_token_logits.shape ++ ++ def per_row(x): ++ return x.repeat_interleave(rows_per_request, dim=0).view(rows, 1) ++ ++ # ties with the k-th logit stay in, as in top_k_renorm_prob ++ width = min(vocab_size, max_top_k + 32) ++ logits, token_ids = torch.topk(next_token_logits, width, dim=-1) ++ temperatures = per_row(sampling_info.temperatures) ++ logits = logits.float() / temperatures ++ top_ks = per_row(sampling_info.top_ks).long() ++ pivots = logits.gather(1, (top_ks - 1).clamp_(0, width - 1)) ++ logits.masked_fill_(logits < pivots, float("-inf")) ++ probs = torch.softmax(logits, dim=-1) ++ if sampling_info.need_top_p_sampling: ++ # The nucleus is cut on the full distribution, so the top-k mass it must ++ # reach is top_p scaled by the top-k share of the vocabulary's mass. ++ top_ps = _adjust_top_p_for_top_k( ++ logits, next_token_logits, per_row(sampling_info.top_ps), temperatures ++ ) ++ ascending = probs.flip(-1) ++ cutoff = torch.searchsorted(ascending.cumsum(-1), 1.0 - top_ps).clamp_( ++ max=width - 1 ++ ) ++ probs = probs.masked_fill(probs < ascending.gather(1, cutoff), 0.0) ++ probs.div_(probs.sum(-1, keepdim=True)) ++ target_probs = torch.zeros_like(next_token_logits, dtype=torch.float32) ++ return target_probs.scatter_(1, token_ids, probs) ++ ++ + def compact_verify_max_top_k(batch: ScheduleBatch) -> Optional[int]: +- """The support for eagle_sample's compact top-k branch under +- SGLANG_OPT_SPEC_COMPACT_VERIFY_SAMPLING, or None for the dense branch: every +- request must sample with a finite top-k within the compact limit.""" +- if not _COMPACT_VERIFY_SAMPLING or batch.forward_mode.is_idle(): ++ """The top-k support for eagle_sample's top-k branches, or None for dense. On when ++ SGLANG_OPT_SPEC_COMPACT_VERIFY_SAMPLING is set, or unset with rejection sampling ++ on the AITER path. Every request needs a finite top-k within the compact limit.""" ++ enabled = _COMPACT_VERIFY_SAMPLING or ( ++ _use_aiter ++ and not _COMPACT_VERIFY_SAMPLING_SET ++ and get_spec().speculative_use_rejection_sampling ++ ) ++ if not enabled or batch.forward_mode.is_idle(): + return None + from sglang.srt.speculative.uno_utils import _SPARSE_TOP_K_LIMIT + +@@ -1064,19 +1126,28 @@ def eagle_sample( + else: + sampling_fn = tree_speculative_sampling_target_only + +- target_probs = sampling_softmax( +- next_token_logits, +- temperatures=sampling_info.temperatures, +- rows_per_request=verify_input.draft_token_num, +- ) # (bs * num_draft_tokens, vocab_size) +- maybe_detect_nan(target_probs, "v2 verify: target_probs after softmax") +- target_probs = _apply_joint_top_k_top_p( +- target_probs, +- sampling_info, +- verify_input.draft_token_num, +- top_k_renorm_prob, +- top_p_renorm_prob, +- ) ++ sparse_target = use_rejection_sampling and uno_target_max_top_k is not None ++ if sparse_target: ++ target_probs = _sparse_rejection_target_probs( ++ next_token_logits, ++ sampling_info, ++ verify_input.draft_token_num, ++ uno_target_max_top_k, ++ ) # (bs * num_draft_tokens, vocab_size) ++ else: ++ target_probs = sampling_softmax( ++ next_token_logits, ++ temperatures=sampling_info.temperatures, ++ rows_per_request=verify_input.draft_token_num, ++ ) # (bs * num_draft_tokens, vocab_size) ++ maybe_detect_nan(target_probs, "v2 verify: target_probs after softmax") ++ target_probs = _apply_joint_top_k_top_p( ++ target_probs, ++ sampling_info, ++ verify_input.draft_token_num, ++ top_k_renorm_prob, ++ top_p_renorm_prob, ++ ) + target_probs = target_probs.reshape(bs, verify_input.draft_token_num, -1) + draft_probs = ( + verify_input.draft_probs +diff --git a/python/sglang/srt/speculative/uno_utils.py b/python/sglang/srt/speculative/uno_utils.py +index 968a7456c8..7ac7a6e927 100644 +--- a/python/sglang/srt/speculative/uno_utils.py ++++ b/python/sglang/srt/speculative/uno_utils.py +@@ -4,7 +4,6 @@ from dataclasses import dataclass + from typing import Any + + import torch +-from flashinfer import top_k as _flashinfer_top_k + + from sglang.kernels.ops.speculative.reject_sampling import ( + chain_speculative_sampling_triton, +@@ -142,6 +141,8 @@ def _build_sparse_target_support_tensors( + """Build compact support using the fastest available top-k primitive.""" + # Runs outside torch.compile: Dynamo cannot trace FlashInfer's stream-keyed + # scratch-buffer lookup, which calls torch._C._cuda_getCurrentRawStream since 0.7.4. ++ from flashinfer import top_k as _flashinfer_top_k ++ + topk_logits, topk_ids = _flashinfer_top_k( + next_token_logits.contiguous(), + max_top_k, diff --git a/inferencex-e2e/configs/amd-master.yaml b/inferencex-e2e/configs/amd-master.yaml index 24e5d20b8a..72be20db4d 100644 --- a/inferencex-e2e/configs/amd-master.yaml +++ b/inferencex-e2e/configs/amd-master.yaml @@ -283,10 +283,10 @@ qwen3.5-fp4-mi355x-sglang-agentic-mtp: # Qwen3.8-Flash-Next Quark MXFP4 MoE (MTP experts included), FP8 attention and # FP8 PLE, AgentX on MI355X via SGLang with native NEXTN MTP (3 steps, # eagle-topk 1, 4 draft tokens). TP1: the ~116 GiB checkpoint fits on one MI355X. -# Concurrency 1-16 serve from GPU KV; 24, 48 and 80 add an FP8 KV cache and HiCache -# host-DRAM offload. +# Concurrency 1, 2, 12 and 24 serve from GPU KV (12 and 24 with an FP8 KV cache); 48 and +# 80 add HiCache host-DRAM offload. qwen3.8next-fp4-mi355x-sglang-agentic-mtp: - image: lmsysorg/sglang-rocm:v0.5.23-rocm10-mi35x-20261110@sha256:fc800d4329d49631b0e7228d79cd02274a831eab12eb9ec00e5cbdafc8edfd0a + image: lmsysorg/sglang-rocm:v0.5.23-rocm10-mi35x-20261117@sha256:09b8237296024285e6286ffb54d75c3af6d59342bbbb3558dea56bed86798814 model: amd/Qwen3.8-Flash-Next-Quark-MXFP4-AttnFP8-PLEFP8 model-prefix: qwen3.8next runner: cluster:mi355x-amds @@ -297,8 +297,8 @@ qwen3.8next-fp4-mi355x-sglang-agentic-mtp: scenarios: agentic-coding: - search-space: - - { gpus-per-worker: 1, tp: 1, ep: 1, spec-decoding: mtp, kv-offloading: none, conc-list: [1, 2, 4, 8, 12, 16], srt-recipe: agentic.yaml } - - { gpus-per-worker: 1, tp: 1, ep: 1, spec-decoding: mtp, kv-offloading: dram, kv-offload-backend: { name: hicache }, conc-list: [24, 48, 80], srt-recipe: agentic.yaml } + - { gpus-per-worker: 1, tp: 1, ep: 1, spec-decoding: mtp, kv-offloading: none, conc-list: [1, 2, 12, 24], srt-recipe: agentic.yaml } + - { gpus-per-worker: 1, tp: 1, ep: 1, spec-decoding: mtp, kv-offloading: dram, kv-offload-backend: { name: hicache }, conc-list: [48, 80], srt-recipe: agentic.yaml } # AgentX Pareto sweep for Qwen3.5 FP8 on MI300X. The fast discovery run peaks # at c24; c32 records the post-knee throughput and latency cliff. diff --git a/inferencex-e2e/perf-changelog.yaml b/inferencex-e2e/perf-changelog.yaml index a3253569f3..78776a68f9 100644 --- a/inferencex-e2e/perf-changelog.yaml +++ b/inferencex-e2e/perf-changelog.yaml @@ -13333,3 +13333,17 @@ - "Bump utils/srt-slurm from 2d9079c to cc9db05 (21 commits), which adds NVIDIA/srt-slurm#669: one bootstrap port per prefill engine and Router start after every worker's health check. The shared vllm-router.sh setup script now raises the worker parent shell's soft RLIMIT_MEMLOCK to its hard limit." - "Draft data type unchanged: the DSpark draft from the checkpoint's dspark/ subfolder runs as shipped, with MXFP8 attention and MLP projections, BF16 fc, norms and the shared target embedding and LM head, and an FP8 E4M3 draft KV cache." pr-link: https://github.com/SemiAnalysisAI/InferenceX/pull/5090 + +- config-keys: + - qwen3.8next-fp4-mi355x-sglang-agentic-mtp + scenario-type: + - agentic-coding + description: + - "Best-performance Qwen3.8-Flash-Next Quark MXFP4 (FP8 attention, FP8 PLE) AgentX recipe on MI355X: SGLang native NEXTN MTP (3 steps, eagle-topk 1, 4 draft tokens), TP1/EP1, concurrency 1/2/12/24 with GPU-resident KV and 48/80 with HiCache DRAM KV offload. TP1 because the ~116 GiB checkpoint fits on one MI355X." + - "Serve amd/Qwen3.8-Flash-Next-Quark-MXFP4-AttnFP8-PLEFP8 from lmsysorg/sglang-rocm:v0.5.23-rocm10-mi35x-20261117@sha256:09b8237296024285e6286ffb54d75c3af6d59342bbbb3558dea56bed86798814 (SGLang c67db7c762, AITER 581579ab 0.1.29.dev156 with FlyDSL 0.4.2) with quark quantization, the aiter attention backend, page-size 64, chunked-prefill-size 16384 and mamba-ssm-dtype bfloat16. The PLE n-gram table is offloaded to CPU pinned memory (--ple-offload-embedding, ple_embedding_dtype float8_e4m3fn), which cuts GPU weight memory from ~130 GB to ~82 GB and grows the KV pool from ~2.1M to ~3.7M tokens." + - "Apply 7 SGLang patches, each a source-only conversion of an open upstream PR onto the image's SGLang checkout, with an idempotent setup_script (qwen3.8next-rocm10-patches.sh) that fails the job if the image's AITER lacks one of the FlyDSL modules or if a patch stops applying. The image's AITER is not touched: it already contains the FlyDSL causal conv1d prefill and GDN decode/verify kernels (aiter #5992), the fused QSA sparse decode (aiter #6670, required by sglang #45196), the FlyDSL fused GDN chunked prefill (aiter #6496) and the FlyDSL hc_mix kernels (aiter #5993), which earlier revisions of this recipe patched into the image's AITER or installed from the v0.1.29 release wheel. SGLang: fused decode-sized hyper-connection norm and inject (sglang #48648), FlyDSL QSA sparse decode (sglang #45196), faster QSA decode MQA logits (sglang #48649), fused QK norm + RoPE + gate on HIP (sglang #45529), AITER FlyDSL GDN causal conv1d prefill (sglang #41879), AITER GDN chunked prefill (sglang #44103) and MTP verify target probabilities built on each row's top-k support instead of a vocabulary-wide sort (sglang #48090, backported: the image lacks sglang #41916, so the top-p rescale helper is copied in). The image already has the strided GDN prefill projection views (sglang #41683, merged), the monokernel, the AITER topk gating router (sglang #40708), ratio-3 GDN packing (sglang #44302) and the 128-row hc_mix (sglang #41880), so those are not patched." + + - "Env: SGLANG_USE_AITER, SGLANG_AITER_GDN_CONV, SGLANG_AITER_GDN_PREFILL and SGLANG_AITER_GDN_PREFILL_H=fused (the single fused FlyDSL chunked-prefill kernel of aiter #6496, in the image's AITER; the sglang #44103 default is the triton stages) at every concurrency; SGLANG_OPT_QWEN4_FUSED_HC, SGLANG_USE_AITER_UNIFIED_ATTN and SGLANG_AITER_HONOR_EXPLICIT_MEM_FRACTION at 12/24/48/80. The FlyDSL QSA decode needs no flag: sglang #45196 turns it on whenever SGLANG_USE_AITER is set on gfx950. Likewise sglang #48090 turns on by default when SGLANG_USE_AITER is set and the MTP verify uses rejection sampling (every request carries top_k 20 from the model's generation_config.json); it falls back to the dense path for requests without a top-k of 2 to 128. ROCM_QUICK_REDUCE_QUANTIZATION=NONE (the image defaults to INT8) at every concurrency. This replaces the earlier 17-patch and 7-patch stacks of this recipe." + - "c1 and c2 run the FlyDSL monokernel for MTP target verify and draft that the image ships (--enable-amd-monokernel, 3 steps / 4 draft tokens). Its verify writes the per-draft SSM states and its prelude reads the PLE table on the GPU, so these points drop ReplaySSM and the PLE offload, admit CONC requests (max-running-requests = cuda-graph-max-bs-decode) and use mem-fraction-static 0.9 as given." + - "c12 and c24 join c1 and c2 in the GPU-KV search-space entry (kv-offloading: none, no HiCache); c48 and c80 are a second entry with HiCache DRAM KV offload (kv-offloading: dram, backend hicache) that takes the 299 GB DRAM share of dram-utilization 0.80 (hicache-size 298). c12, c24, c48 and c80 store the target and draft KV caches in FP8 E4M3, use mem-fraction-static 0.88 as given, keep ReplaySSM and the PLE offload, and set the Mamba checkpoint interval to 262144 tokens (extra_buffer_lazy, max-mamba-cache-size 960, 720 and 640). Admission is 24 requests at c12 and 48 at c24 (2x CONC) and 128 at c48 and c80, with decode CUDA graphs up to the same size; at c48 and c80 HiCache uses the kernel IO backend, page_first layout and write_back policy. c80 also sets strip-thinking-cache and mamba-max-states-per-path 2. Prefill CUDA graphs use the breakable backend (--cuda-graph-backend-prefill breakable)." + pr-link: https://github.com/SemiAnalysisAI/InferenceX/pull/4832