diff --git a/docs/cookbook/autoregressive/Qwen/Qwen3.mdx b/docs/cookbook/autoregressive/Qwen/Qwen3.mdx index 52410ec43a4c6..5b72707db9c10 100644 --- a/docs/cookbook/autoregressive/Qwen/Qwen3.mdx +++ b/docs/cookbook/autoregressive/Qwen/Qwen3.mdx @@ -47,6 +47,7 @@ import { Qwen3Deployment } from "/src/snippets/autoregressive/qwen3-deployment.j - **Expert Parallelism:** SGLang supports Expert Parallelism (EP) via `--ep`, allowing experts in MoE models to be deployed on separate GPUs for better throughput. One thing to note is that, for quantized models, you need to set `--ep` to a value that satisfies the requirement: `(moe_intermediate_size / moe_tp_size) % weight_block_size_n == 0, where moe_tp_size is equal to tp_size divided by ep_size.` Note that EP may perform worse in low concurrency scenarios due to additional communication overhead. Check out [Expert Parallelism Deployment](../../../docs/advanced_features/expert_parallelism) for more details. - **Kernel Tuning:** For MoE Triton kernel tuning on your specific hardware, refer to [fused_moe_triton](https://github.com/sgl-project/sglang/tree/main/benchmark/kernels/fused_moe_triton). - **Qwen3-4B and Qwen3-8B on H200:** For concurrent requests with long prompts, benchmark `--enable-mixed-chunk` to mix decode requests into chunked-prefill batches. This can reduce median time to first token (TTFT), but may increase time per output token (TPOT) and end-to-end tail latency. Compare these metrics and throughput on your workload before enabling it. +- **Opt-in fused dense prefill:** `--enable-fused-qk-norm-rope` also fuses QK normalization and cached RoPE for ordinary dense-Qwen3 prefill on Hopper, with FP16/BF16, head dimension 128, TP1, no quantization, and FA3 or FlashInfer. It produces contiguous Q while updating packed K; attention and KV-cache handling are unchanged. Other prefill configurations, mixed batches, speculative decoding, scaled RoPE, and deterministic inference retain the separate path. CUDA fusion remains disabled by default; `--no-enable-fused-qk-norm-rope` disables it. - **Speculative Decoding:** Using Speculative Decoding for latency-sensitive scenarios. - `--speculative-algorithm EAGLE3`: Speculative decoding algorithm - `--speculative-num-steps 3`: Number of speculative verification rounds diff --git a/python/sglang/kernels/jit/csrc/attention/qk_norm_rope.cuh b/python/sglang/kernels/jit/csrc/attention/qk_norm_rope.cuh new file mode 100644 index 0000000000000..324cc08d70295 --- /dev/null +++ b/python/sglang/kernels/jit/csrc/attention/qk_norm_rope.cuh @@ -0,0 +1,173 @@ +#include + +#include +#include + +#include + +#include +#include + +namespace sglang { + +template +__global__ void qk_norm_rope_kernel( + const T* __restrict__ q, + T* __restrict__ k, + T* __restrict__ out, + const T* __restrict__ qw, + const T* __restrict__ kw, + const float* __restrict__ cache, + const IdType* __restrict__ positions, + int64_t q_stride, + int64_t k_stride, + uint32_t q_heads, + uint32_t k_heads, + uint32_t num_rows, + float eps) { + using namespace device; + constexpr uint32_t kLanes = kHeadDim == 128 ? 16 : 32; + constexpr uint32_t kPairs = kHeadDim / (2 * kLanes); + using Storage = AlignedVector, kPairs>; + const auto lane = get_lane_id(); + const auto worker = (blockIdx.x * blockDim.x + threadIdx.x) / kLanes; + const auto stride = gridDim.x * blockDim.x / kLanes; + PDLWaitPrimary(); + // Both half-warps participate in shuffles, including an unmatched final row. + const auto padded_rows = num_rows + (kHeadDim == 128 && num_rows % 2); + for (uint64_t row = worker; row < padded_rows; row += stride) { + const bool valid = row < num_rows; + const int64_t token = valid ? row / (q_heads + k_heads) : 0; + const auto head = valid ? static_cast(row % (q_heads + k_heads)) : 0; + const bool is_q = head < q_heads; + const auto head_offset = int64_t{is_q ? head : head - q_heads} * kHeadDim; + const auto src = is_q ? q + token * q_stride + head_offset : k + token * k_stride + head_offset; + const auto dst = is_q ? out + (token * q_heads + head) * kHeadDim : k + token * k_stride + head_offset; + Storage input; + if (valid) + input = load_as(src, lane); + else + input.fill(cast, fp32x2_t>({0.0f, 0.0f})); + const auto weight = load_as(is_q ? qw : kw, lane); + const int64_t pos = positions[token]; + fp32x2_t cos[kPairs], sin[kPairs]; +#pragma unroll + for (auto i = 0u; i < kPairs; ++i) { + const auto dim = (lane % (kLanes / 2)) * (2 * kPairs) + 2 * i; + cos[i] = load_as(cache + pos * kHeadDim + dim); + sin[i] = load_as(cache + pos * kHeadDim + kHeadDim / 2 + dim); + } + auto normalized = [&] { + if constexpr (kHeadDim == 128) { + return norm::apply_norm_half_warp(input, weight, eps); + } else { + return norm::apply_norm_warp(input, weight, eps); + } + }(); +#pragma unroll + for (auto i = 0u; i < kPairs; ++i) { + const auto x = cast(normalized[i]); + const auto partner_lane = lane ^ (kLanes / 2); + const auto bits = __shfl_sync(0xffffffffu, load_as(&normalized[i]), partner_lane, kLanes); + packed_t partner; + store_as(&partner, bits); + const auto y = cast(partner); + const auto sign = lane < kLanes / 2 ? -1.0f : 1.0f; + normalized[i] = cast, fp32x2_t>( + {__fmaf_rn(x.x, cos[i].x, sign * __fmul_rn(y.x, sin[i].x)), + __fmaf_rn(x.y, cos[i].y, sign * __fmul_rn(y.y, sin[i].y))}); + } + if (valid) store_as(dst, normalized, lane); + } + PDLTriggerSecondary(); +} + +/** + * \brief Normalize and apply cached full-head NeoX RoPE; write separate Q and in-place K. + * \tparam T FP16 or BF16 activation and weight type + * \tparam kHeadDim Head dimension: 64, 128, or 256 + * \tparam kUsePDL Whether to use programmatic dependent launch + * \param q Read-only query heads, with contiguous columns and aligned row strides + * \param k Key heads, overwritten in their original storage + * \param out Contiguous query output, disjoint from Q and K + * \param qw Query norm weights + * \param kw Key norm weights + * \param cache Contiguous FP32 cosine/sine table; positions must index valid rows + * \param positions Contiguous int32/int64 position indices + * \param eps Shared Q/K normalization epsilon + */ +template +void qk_norm_rope( + tvm::ffi::TensorView q, + tvm::ffi::TensorView k, + tvm::ffi::TensorView out, + tvm::ffi::TensorView qw, + tvm::ffi::TensorView kw, + tvm::ffi::TensorView cache, + tvm::ffi::TensorView positions, + float eps) { + using namespace host; + static_assert(kHeadDim == 64 || kHeadDim == 128 || kHeadDim == 256); + static_assert(std::is_same_v || std::is_same_v); + constexpr int64_t kLanes = kHeadDim == 128 ? 16 : 32; + constexpr auto kAlignment = kHeadDim * sizeof(T) / kLanes; + auto N = SymbolicSize{"tokens"}; + auto Q = SymbolicSize{"query_heads"}; + auto K = SymbolicSize{"key_heads"}; + auto Sq = SymbolicSize{"query_stride"}; + auto Sk = SymbolicSize{"key_stride"}; + auto P = SymbolicSize{"positions"}; + auto device = SymbolicDevice{}; + device.set_options(); + TensorMatcher({N, Q, kHeadDim}) + .with_strides({Sq, kHeadDim, 1}) + .with_dtype() + .with_device(device) + .ensure_alignment(kAlignment) + .verify(q); + TensorMatcher({N, K, kHeadDim}) + .with_strides({Sk, kHeadDim, 1}) + .with_dtype() + .with_device(device) + .ensure_alignment(kAlignment) + .verify(k); + TensorMatcher({N, Q, kHeadDim}).with_dtype().with_device(device).ensure_alignment(kAlignment).verify(out); + TensorMatcher({kHeadDim}).with_dtype().with_device(device).ensure_alignment(kAlignment).verify(qw).verify(kw); + TensorMatcher({P, kHeadDim}).with_dtype().with_device(device).ensure_alignment(8).verify(cache); + TensorMatcher({N}).with_dtype().with_device(device).verify(positions); + CHECK_HOST(Q.unwrap() > 0 && K.unwrap() > 0 && P.unwrap() > 0); + CHECK_HOST(Sq.unwrap() >= Q.unwrap() * kHeadDim && Sk.unwrap() >= K.unwrap() * kHeadDim); + const auto rows = N.unwrap() * (Q.unwrap() + K.unwrap()); + CHECK_HOST(rows < std::numeric_limits::max()); + if (rows == 0) return; + const auto launch = [&]() { + constexpr auto kernel = qk_norm_rope_kernel; + constexpr uint32_t kThreads = 256; + static const auto max_occupancy = runtime::get_blocks_per_sm(kernel, kThreads); + const auto blocks = std::min( + runtime::get_sm_count(device.unwrap().device_id) * max_occupancy, + div_ceil(static_cast(rows), static_cast(kThreads / kLanes))); + LaunchKernel(blocks, kThreads, device.unwrap()) + .enable_pdl(kUsePDL)( + kernel, + static_cast(q.data_ptr()), + static_cast(k.data_ptr()), + static_cast(out.data_ptr()), + static_cast(qw.data_ptr()), + static_cast(kw.data_ptr()), + static_cast(cache.data_ptr()), + static_cast(positions.data_ptr()), + Sq.unwrap(), + Sk.unwrap(), + static_cast(Q.unwrap()), + static_cast(K.unwrap()), + static_cast(rows), + eps); + }; + if (is_type(positions.dtype())) + launch.template operator()(); + else + launch.template operator()(); +} + +} // namespace sglang diff --git a/python/sglang/kernels/jit/csrc/elementwise/qknorm.cuh b/python/sglang/kernels/jit/csrc/elementwise/qknorm.cuh index 291cba0b739fd..21725fd2fb703 100644 --- a/python/sglang/kernels/jit/csrc/elementwise/qknorm.cuh +++ b/python/sglang/kernels/jit/csrc/elementwise/qknorm.cuh @@ -105,25 +105,7 @@ __global__ void fused_qknorm_half_warp(const QKNormParams __grid_constant__ para auto vec = load_as(input, row_lane); const auto weight_vec = load_as(weight, row_lane); - // part[h] is the sum of warp-kernel lane 2 * row_lane + h, and reduce_sum below - // is that kernel's 16..2 xor steps; its final xor-1 step adds the pair. - float part[2] = {0.0f, 0.0f}; -#pragma unroll - for (auto i = 0u; i < kPacks; ++i) { - const auto x = cast(vec[i]); - part[i / 2] += x.x * x.x; - part[i / 2] += x.y * x.y; - } - part[0] = warp::reduce_sum(part[0]); - part[1] = warp::reduce_sum(part[1]); - const float norm_factor = math::rsqrt((part[0] + part[1]) / kHeadDim + eps); - -#pragma unroll - for (auto i = 0u; i < kPacks; ++i) { - const auto x = cast(vec[i]); - const auto w = cast(weight_vec[i]); - vec[i] = cast({x.x * norm_factor * w.x, x.y * norm_factor * w.y}); - } + vec = norm::apply_norm_half_warp(vec, weight_vec, eps); if (wanted_row < num_rows) store_as(input, vec, row_lane); } diff --git a/python/sglang/kernels/jit/include/sgl_kernel/impl/norm.cuh b/python/sglang/kernels/jit/include/sgl_kernel/impl/norm.cuh index e3cf09201cfdd..5f34b8626ffdb 100644 --- a/python/sglang/kernels/jit/include/sgl_kernel/impl/norm.cuh +++ b/python/sglang/kernels/jit/include/sgl_kernel/impl/norm.cuh @@ -127,6 +127,37 @@ SGL_DEVICE T apply_norm_warp(const T& input, const T& weight, float eps) { return details::apply_norm_impl(input, weight, eps, nullptr, 0); } +/** + * \brief Normalize a 128-element row with 16 lanes, preserving the warp reduction. + * \param input Eight FP16/BF16 elements per lane, packed into four pairs + * \param weight Matching normalization weights + * \param eps Normalization epsilon + * \return Rounded normalized pairs + */ +template +SGL_DEVICE AlignedVector +apply_norm_half_warp(AlignedVector input, const AlignedVector& weight, float eps) { + // Each lane retains the two original warp-lane partials; the last addition + // reproduces the original xor-1 step after the xor-16..2 butterfly. + float part[2] = {0.0f, 0.0f}; +#pragma unroll + for (auto i = 0u; i < 4; ++i) { + const auto x = cast(input[i]); + part[i / 2] += x.x * x.x; + part[i / 2] += x.y * x.y; + } + part[0] = warp::reduce_sum<16>(part[0]); + part[1] = warp::reduce_sum<16>(part[1]); + const float norm_factor = math::rsqrt((part[0] + part[1]) / 128 + eps); +#pragma unroll + for (auto i = 0u; i < 4; ++i) { + const auto x = cast(input[i]); + const auto w = cast(weight[i]); + input[i] = cast({x.x * norm_factor * w.x, x.y * norm_factor * w.y}); + } + return input; +} + /** * \brief Apply norm using CTA-level implementation. * \tparam kDim Dimension size diff --git a/python/sglang/kernels/ops/attention/__init__.py b/python/sglang/kernels/ops/attention/__init__.py index 10e54a5e1db2b..7b70c86290e1c 100644 --- a/python/sglang/kernels/ops/attention/__init__.py +++ b/python/sglang/kernels/ops/attention/__init__.py @@ -73,6 +73,15 @@ ) del _mod, _fn +register_kernel( + KernelSpec( + op="attention.qk_norm_rope", + backend=KernelBackend.JIT, + target="sglang.kernels.ops.attention.qk_norm_rope:qk_norm_rope", + capabilities=CUDA_ONLY, + ) +) + register_kernel( KernelSpec( op="attention.kda_qwen38_qsa_sm121", diff --git a/python/sglang/kernels/ops/attention/qk_norm_rope.py b/python/sglang/kernels/ops/attention/qk_norm_rope.py new file mode 100644 index 0000000000000..fefa5028aad73 --- /dev/null +++ b/python/sglang/kernels/ops/attention/qk_norm_rope.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +from sglang.kernels.jit.utils import ( + cache_once, + is_arch_support_pdl, + load_jit, + make_cpp_args, +) +from sglang.srt.utils.custom_op import register_custom_op + +if TYPE_CHECKING: + from tvm_ffi.module import Module + + +@cache_once +def _module(dtype: torch.dtype, head_dim: int) -> Module: + if dtype not in (torch.float16, torch.bfloat16) or head_dim not in (64, 128, 256): + raise ValueError( + "qk_norm_rope requires FP16/BF16 and head dimension 64/128/256" + ) + args = make_cpp_args(dtype, head_dim, is_arch_support_pdl()) + return load_jit( + "qk_norm_rope", + *args, + cuda_files=["attention/qk_norm_rope.cuh"], + cuda_wrappers=[("run", f"qk_norm_rope<{args}>")], + ) + + +@register_custom_op(mutates_args=["k", "out"]) +def _qk_norm_rope_out( + q: torch.Tensor, + k: torch.Tensor, + out: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + cos_sin_cache: torch.Tensor, + positions: torch.Tensor, + head_dim: int, + eps: float, +) -> None: + _module(q.dtype, head_dim).run( + q.view(q.shape[0], q.shape[1] // head_dim, head_dim), + k.view(k.shape[0], k.shape[1] // head_dim, head_dim), + out.view(out.shape[0], out.shape[1] // head_dim, head_dim), + q_weight, + k_weight, + cos_sin_cache, + positions, + eps, + ) + + +def qk_norm_rope( + q: torch.Tensor, + k: torch.Tensor, + q_weight: torch.Tensor, + k_weight: torch.Tensor, + cos_sin_cache: torch.Tensor, + positions: torch.Tensor, + head_dim: int, + eps: float, +) -> torch.Tensor: + """Cached full-head NeoX RoPE after QK RMSNorm, for FP16/BF16 CUDA tensors. + + Returns a separate contiguous Q; modifies K in its original storage and + leaves Q unchanged. Q/K are [tokens, heads * head_dim] with aligned row + strides and contiguous columns. Weights have the activation dtype, the + table is contiguous FP32, and int32/int64 positions index valid table rows. + Q/K may share packed QKV storage, but their elements must not overlap. + Normalized values are rounded before rotation, as in separate CUDA kernels. + """ + out = torch.empty(q.shape, dtype=q.dtype, device=q.device) + _qk_norm_rope_out( + q, k, out, q_weight, k_weight, cos_sin_cache, positions, head_dim, eps + ) + return out diff --git a/python/sglang/srt/models/qwen3.py b/python/sglang/srt/models/qwen3.py index ab985aae519e1..29e98bed21df7 100644 --- a/python/sglang/srt/models/qwen3.py +++ b/python/sglang/srt/models/qwen3.py @@ -5,6 +5,7 @@ import torch from torch import nn +from sglang.kernels.ops.attention.qk_norm_rope import qk_norm_rope from sglang.kernels.ops.attention.table_qk_norm_rope import table_qk_norm_rope_ from sglang.srt.environ import envs from sglang.srt.layers.aux_hidden_states import AuxHiddenStateList @@ -31,6 +32,7 @@ ) from sglang.srt.model_executor.forward_batch_info import ForwardBatch, PPProxyTensors from sglang.srt.model_executor.forward_context import get_kv_layers +from sglang.srt.model_executor.forward_mode import ForwardMode from sglang.srt.model_loader.weight_utils import ( default_weight_loader, maybe_remap_kv_scale_name, @@ -40,7 +42,13 @@ from sglang.srt.models.qwen2 import Qwen2Model from sglang.srt.models.utils import apply_qk_norm from sglang.srt.platforms import current_platform -from sglang.srt.runtime_context import get_exec, get_parallel, get_stream +from sglang.srt.runtime_context import ( + attention_backends, + get_exec, + get_parallel, + get_spec, + get_stream, +) from sglang.srt.utils import add_prefix, get_bool_env_var, is_cuda, is_hip, is_npu Qwen3Config = None @@ -179,6 +187,7 @@ def __init__( attention_bias: bool = False, prefix: str = "", alt_stream: Optional[torch.cuda.Stream] = None, + enable_prefill_qk_norm_rope: bool = False, ) -> None: super().__init__() self.hidden_size = hidden_size @@ -277,6 +286,23 @@ def __init__( 2 if type(self.rotary_emb) is MRotaryEmbedding else 1 ) + # Only the ordinary dense-Qwen3 caller opts in; inherited callers stay native. + self.use_prefill_qk_norm_rope = ( + enable_prefill_qk_norm_rope + and self.use_table_qk_norm_rope + and type(self) is Qwen3Attention + and type(self.rotary_emb) is RotaryEmbedding + and quant_config is None + and attn_tp_size == 1 + and self.head_dim == 128 + and torch.cuda.get_device_capability()[0] == 9 + and attention_backends()[0] in ("fa3", "flashinfer") + and get_spec().speculative_algorithm is None + and self.rotary_emb.is_neox_style + and self.rotary_emb.rotary_dim == self.head_dim + and self.q_norm.variance_epsilon == self.k_norm.variance_epsilon + ) + self.use_fused_qk_norm_mrope = ( _has_fused_qk_norm_mrope and isinstance(self.rotary_emb, MRotaryEmbedding) @@ -339,6 +365,29 @@ def forward_prepare_native(self, positions, hidden_states, forward_batch): match_cuda=True, axis_map=axis_map, ) + elif ( + self.use_prefill_qk_norm_rope + and forward_batch.forward_mode == ForwardMode.EXTEND + and not torch.compiler.is_compiling() + and qkv.is_cuda + and qkv.is_contiguous() + and qkv.dtype in (torch.bfloat16, torch.float16) + and self.q_norm.weight.dtype == qkv.dtype + and self.k_norm.weight.dtype == qkv.dtype + and self.rotary_emb.cos_sin_cache.dtype == torch.float32 + and positions.is_contiguous() + and positions.dtype in (torch.int32, torch.int64) + ): + q = qk_norm_rope( + q=q, + k=k, + q_weight=self.q_norm.weight, + k_weight=self.k_norm.weight, + cos_sin_cache=self.rotary_emb.cos_sin_cache, + positions=positions, + head_dim=self.head_dim, + eps=self.q_norm.variance_epsilon, + ) else: q, k = apply_qk_norm( q=q, @@ -484,6 +533,9 @@ def __init__( attention_bias=config.attention_bias, prefix=add_prefix("self_attn", prefix), alt_stream=alt_stream, + enable_prefill_qk_norm_rope=( + type(self) is Qwen3DecoderLayer and config.model_type == "qwen3" + ), ) self.mlp = Qwen3MLP( hidden_size=self.hidden_size, diff --git a/test/registered/kernels/benchmark/attention/bench_qk_norm_rope.py b/test/registered/kernels/benchmark/attention/bench_qk_norm_rope.py new file mode 100644 index 0000000000000..f924ce00a3b86 --- /dev/null +++ b/test/registered/kernels/benchmark/attention/bench_qk_norm_rope.py @@ -0,0 +1,42 @@ +import torch + +from sglang.kernels.jit.benchmark import marker +from sglang.kernels.ops.attention.qk_norm_rope import qk_norm_rope +from sglang.kernels.ops.attention.rope import apply_rope_inplace +from sglang.kernels.ops.layernorm.norm import fused_inplace_qknorm +from sglang.test.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=6, stage="base-b-kernel-benchmark", runner_config="1-gpu-large" +) + + +def prepare(qkv, qw, kw, cache, positions, fused): + q, k, _ = qkv.split([32 * 128, 8 * 128, 8 * 128], dim=-1) + if fused: + return qk_norm_rope(q, k, qw, kw, cache, positions, 128, 1e-6) + q = q.view(q.shape[0], 32, 128) + k = k.view(k.shape[0], 8, 128) + fused_inplace_qknorm(q, k, qw, kw, 1e-6) + apply_rope_inplace(q, k, cache, positions, is_neox=True) + return q.contiguous() + + +@marker.parametrize("tokens", [512, 4096, 8192], [512, 4096]) +@marker.parametrize("dtype", [torch.bfloat16, torch.float16]) +@marker.benchmark("fused", [False, True]) +def benchmark(tokens, dtype, fused): + qkv = torch.randn(tokens, 48 * 128, device="cuda", dtype=dtype) + qw = torch.ones(128, device="cuda", dtype=dtype) + kw = torch.ones_like(qw) + cache = torch.randn(32768, 128, device="cuda", dtype=torch.float32) + positions = torch.arange(tokens, device="cuda") + return marker.do_bench( + prepare, + input_args=(qkv, qw, kw, cache, positions, fused), + graph_clone_args=(0, 1, 2, 3, 4), + ) + + +if __name__ == "__main__": + benchmark.run() diff --git a/test/registered/kernels/ops/attention/test_table_qk_norm_rope.py b/test/registered/kernels/ops/attention/test_table_qk_norm_rope.py index 4c808deb4be0d..0ea652b5daef9 100644 --- a/test/registered/kernels/ops/attention/test_table_qk_norm_rope.py +++ b/test/registered/kernels/ops/attention/test_table_qk_norm_rope.py @@ -4,6 +4,7 @@ import pytest import torch +from sglang.kernels.ops.attention.qk_norm_rope import qk_norm_rope from sglang.kernels.ops.attention.rope import apply_rope_inplace from sglang.kernels.ops.attention.rotary_triton import triton_mrope_fused from sglang.kernels.ops.attention.table_qk_norm_rope import table_qk_norm_rope_ @@ -179,5 +180,40 @@ def test_cuda_mode_rejects_invalid_inputs(invalid): table_qk_norm_rope_(x, pos, qw, kw, cache, 8, 2, 128, 1e-6, match_cuda=True) +@pytest.mark.parametrize( + "d,dtype,batch", + [ + (64, torch.bfloat16, 17), + (128, torch.bfloat16, 17), + (256, torch.bfloat16, 17), + (64, torch.float16, 17), + (128, torch.float16, 17), + (256, torch.float16, 17), + (128, torch.bfloat16, 0), + ], +) +def test_hybrid_ownership_and_native_parity(d, dtype, batch): + """Only packed K may change; contiguous Q must match separate CUDA norm/RoPE.""" + storage, x, pos, qw, kw, cache = inputs(d, batch, 7, 2, 19, padded=True) + storage = storage.to(dtype) + x = storage[:, 8:-8] + qw, kw = qw.to(dtype), kw.to(dtype) + before = storage.clone() + expected = x.clone() + if batch: + separate(expected, pos, qw, kw, cache, 7, 2, d, 1e-6) + q, k, v = x.split([7 * d, 2 * d, 2 * d], dim=-1) + out = qk_norm_rope(q, k, qw, kw, cache, pos, d, 1e-6) + assert out.is_contiguous() + if batch: + assert out.untyped_storage().data_ptr() != storage.untyped_storage().data_ptr() + assert_same_bits(out, expected[:, : 7 * d]) + assert_same_bits(k, expected[:, 7 * d : 9 * d]) + assert_same_bits(q, before[:, 8 : 8 + 7 * d]) + assert_same_bits(v, before[:, 8 + 9 * d : -8]) + assert_same_bits(storage[:, :8], before[:, :8]) + assert_same_bits(storage[:, -8:], before[:, -8:]) + + if __name__ == "__main__": sys.exit(pytest.main([__file__])) diff --git a/test/registered/unit/models/test_qwen3_qk_norm_rope.py b/test/registered/unit/models/test_qwen3_qk_norm_rope.py index a555279b3cb16..fee62c220f86b 100644 --- a/test/registered/unit/models/test_qwen3_qk_norm_rope.py +++ b/test/registered/unit/models/test_qwen3_qk_norm_rope.py @@ -24,6 +24,7 @@ def runtime(): defaults = dict( enable_fused_qk_norm_rope=True, bf16_gemm_backend="torch", + attention_backend="fa3", cuda_graph_config=CudaGraphConfig(), ) with ( @@ -37,7 +38,7 @@ def runtime(): yield defaults -def make_layer(d=128, dtype=torch.bfloat16, **kwargs): +def make_layer(d=128, dtype=torch.bfloat16, enable_prefill_qk_norm_rope=True, **kwargs): layer = qwen3.Qwen3Attention( hidden_size=8 * d, num_heads=8, @@ -45,6 +46,7 @@ def make_layer(d=128, dtype=torch.bfloat16, **kwargs): head_dim=d, rms_norm_eps=1e-6, max_position_embeddings=4096, + enable_prefill_qk_norm_rope=enable_prefill_qk_norm_rope, **kwargs, ) # Moving model parameters must not downcast the FP32 RoPE table. @@ -76,7 +78,10 @@ def decode_positions(layer, positions): def separate(layer, positions, x, batch): - with patch.object(layer, "use_table_qk_norm_rope", False): + with ( + patch.object(layer, "use_table_qk_norm_rope", False), + patch.object(layer, "use_prefill_qk_norm_rope", False), + ): return layer.forward_prepare_native(positions, x, batch) @@ -92,12 +97,23 @@ def assert_same_qkv(actual, expected): (ForwardMode.DECODE, torch.bfloat16, True), (ForwardMode.EXTEND, torch.bfloat16, False), (ForwardMode.TARGET_VERIFY, torch.bfloat16, False), + (ForwardMode.MIXED, torch.bfloat16, False), + (ForwardMode.DRAFT_EXTEND_V2, torch.bfloat16, False), (ForwardMode.DECODE, torch.float16, False), ], ) def test_model_dispatch(rope_scaling, mode, dtype, should_fuse): layer = make_layer(dtype=dtype, rope_scaling=rope_scaling) assert layer.use_table_qk_norm_rope + should_prefill = ( + rope_scaling is None + and mode == ForwardMode.EXTEND + and torch.cuda.get_device_capability()[0] == 9 + ) + if rope_scaling is not None: + assert not layer.use_prefill_qk_norm_rope + if should_prefill: + assert layer.use_prefill_qk_norm_rope x = torch.randn(4, layer.hidden_size, device="cuda", dtype=dtype) positions = decode_positions(layer, torch.arange(4, device="cuda") + 17) batch = SimpleNamespace(forward_mode=mode) @@ -108,12 +124,19 @@ def test_model_dispatch(rope_scaling, mode, dtype, should_fuse): patch.object( qwen3, "table_qk_norm_rope_", wraps=qwen3.table_qk_norm_rope_ ) as fused, + patch.object(qwen3, "qk_norm_rope", wraps=qwen3.qk_norm_rope) as prefill, ): layer(positions, x, batch) assert fused.call_count == int(should_fuse) + if should_prefill: + prefill.assert_called_once() + else: + prefill.assert_not_called() if should_fuse: assert fused.call_args.kwargs["match_cuda"] is True assert_same_qkv(attn.call_args.args[:3], expected) + if should_prefill: + assert attn.call_args.args[0].is_contiguous() @pytest.mark.parametrize( @@ -146,7 +169,37 @@ def test_constructor_exclusions(runtime, settings, layer_args, deterministic_env get_context().override_server_args(**{**runtime, **settings}), envs.SGLANG_ENABLE_DETERMINISTIC_INFERENCE.override(deterministic_env), ): - assert not make_layer(**layer_args).use_table_qk_norm_rope + layer = make_layer(**layer_args) + assert not layer.use_table_qk_norm_rope + assert not layer.use_prefill_qk_norm_rope + + +@pytest.mark.parametrize("excluded", ["caller", "backend", "head_dim", "weights"]) +def test_prefill_fallbacks(runtime, excluded): + settings = ( + {**runtime, "attention_backend": "triton"} if excluded == "backend" else runtime + ) + with get_context().override_server_args(**settings): + layer = make_layer( + d=64 if excluded == "head_dim" else 128, + enable_prefill_qk_norm_rope=excluded != "caller", + ) + if excluded == "weights": + layer.q_norm.weight = torch.nn.Parameter(layer.q_norm.weight.float()) + layer.k_norm.weight = torch.nn.Parameter(layer.k_norm.weight.float()) + x = torch.randn(4, layer.hidden_size, device="cuda", dtype=torch.bfloat16) + positions = torch.arange(4, device="cuda") + batch = SimpleNamespace(forward_mode=ForwardMode.EXTEND) + if excluded == "weights": + # The separate CUDA norm also rejects mixed activation/weight dtypes. + with pytest.raises(RuntimeError, match="Dtype value"): + layer.forward_prepare_native(positions, x, batch) + with pytest.raises(RuntimeError, match="Dtype value"): + separate(layer, positions, x, batch) + return + actual = layer.forward_prepare_native(positions, x, batch) + assert_same_qkv(actual, separate(layer, positions, x, batch)) + assert not actual[0].is_contiguous() def test_mrope_one_d_positions_stay_separate(): @@ -158,13 +211,24 @@ def test_mrope_one_d_positions_stay_separate(): fused.assert_not_called() -@pytest.mark.parametrize("rope_scaling", [None, MROPE]) -@pytest.mark.parametrize("batch_size", [1, 4, 128]) -def test_changing_input_graph_replay(rope_scaling, batch_size): - layer = make_layer(rope_scaling=rope_scaling) - x = torch.randn(batch_size, layer.hidden_size, device="cuda", dtype=torch.bfloat16) +@pytest.mark.parametrize( + "rope_scaling,mode,dtype,batch_size", + [ + (None, ForwardMode.DECODE, torch.bfloat16, 1), + (None, ForwardMode.DECODE, torch.bfloat16, 4), + (None, ForwardMode.DECODE, torch.bfloat16, 128), + (MROPE, ForwardMode.DECODE, torch.bfloat16, 1), + (MROPE, ForwardMode.DECODE, torch.bfloat16, 4), + (MROPE, ForwardMode.DECODE, torch.bfloat16, 128), + (None, ForwardMode.EXTEND, torch.bfloat16, 17), + (None, ForwardMode.EXTEND, torch.float16, 17), + ], +) +def test_changing_input_graph_replay(rope_scaling, mode, dtype, batch_size): + layer = make_layer(dtype=dtype, rope_scaling=rope_scaling) + x = torch.randn(batch_size, layer.hidden_size, device="cuda", dtype=dtype) positions = decode_positions(layer, torch.arange(batch_size, device="cuda")) - batch = SimpleNamespace(forward_mode=ForwardMode.DECODE) + batch = SimpleNamespace(forward_mode=mode) layer.forward_prepare_native(positions, x, batch) # JIT warmup before capture. graph = torch.cuda.CUDAGraph() with ( @@ -174,7 +238,7 @@ def test_changing_input_graph_replay(rope_scaling, batch_size): torch.cuda.graph(graph), ): actual = layer.forward_prepare_native(positions, x, batch) - fused.assert_called_once() + assert fused.call_count == int(mode == ForwardMode.DECODE) for offset in (0, 17, 2048): x.normal_() positions.copy_(