Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/cookbook/autoregressive/Qwen/Qwen3.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,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
Expand Down
173 changes: 173 additions & 0 deletions python/sglang/kernels/jit/csrc/attention/qk_norm_rope.cuh
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
#include <sgl_kernel/tensor.h>

#include <sgl_kernel/runtime.cuh>
#include <sgl_kernel/utils.cuh>

#include <sgl_kernel/impl/norm.cuh>

#include <cstdint>
#include <limits>

namespace sglang {

template <typename T, int64_t kHeadDim, typename IdType, bool kUsePDL>
__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<packed_t<T>, kPairs>;
const auto lane = get_lane_id<kLanes>();
const auto worker = (blockIdx.x * blockDim.x + threadIdx.x) / kLanes;
const auto stride = gridDim.x * blockDim.x / kLanes;
PDLWaitPrimary<kUsePDL>();
// 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<uint32_t>(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<Storage>(src, lane);
else
input.fill(cast<packed_t<T>, fp32x2_t>({0.0f, 0.0f}));
const auto weight = load_as<Storage>(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<fp32x2_t>(cache + pos * kHeadDim + dim);
sin[i] = load_as<fp32x2_t>(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<kHeadDim>(input, weight, eps);
}
}();
#pragma unroll
for (auto i = 0u; i < kPairs; ++i) {
const auto x = cast<fp32x2_t>(normalized[i]);
const auto partner_lane = lane ^ (kLanes / 2);
const auto bits = __shfl_sync(0xffffffffu, load_as<uint32_t>(&normalized[i]), partner_lane, kLanes);
packed_t<T> partner;
store_as<uint32_t>(&partner, bits);
const auto y = cast<fp32x2_t>(partner);
const auto sign = lane < kLanes / 2 ? -1.0f : 1.0f;
normalized[i] = cast<packed_t<T>, 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<Storage>(dst, normalized, lane);
}
PDLTriggerSecondary<kUsePDL>();
}

/**
* \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 <typename T, int64_t kHeadDim, bool kUsePDL>
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<T, fp16_t> || std::is_same_v<T, bf16_t>);
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<kDLCUDA>();
TensorMatcher({N, Q, kHeadDim})
.with_strides({Sq, kHeadDim, 1})
.with_dtype<T>()
.with_device(device)
.ensure_alignment(kAlignment)
.verify(q);
TensorMatcher({N, K, kHeadDim})
.with_strides({Sk, kHeadDim, 1})
.with_dtype<T>()
.with_device(device)
.ensure_alignment(kAlignment)
.verify(k);
TensorMatcher({N, Q, kHeadDim}).with_dtype<T>().with_device(device).ensure_alignment(kAlignment).verify(out);
TensorMatcher({kHeadDim}).with_dtype<T>().with_device(device).ensure_alignment(kAlignment).verify(qw).verify(kw);
TensorMatcher({P, kHeadDim}).with_dtype<float>().with_device(device).ensure_alignment(8).verify(cache);
TensorMatcher({N}).with_dtype<int32_t, int64_t>().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<uint32_t>::max());
if (rows == 0) return;
const auto launch = [&]<typename IdType>() {
constexpr auto kernel = qk_norm_rope_kernel<T, kHeadDim, IdType, kUsePDL>;
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<uint32_t>(rows), static_cast<uint32_t>(kThreads / kLanes)));
LaunchKernel(blocks, kThreads, device.unwrap())
.enable_pdl(kUsePDL)(
kernel,
static_cast<const T*>(q.data_ptr()),
static_cast<T*>(k.data_ptr()),
static_cast<T*>(out.data_ptr()),
static_cast<const T*>(qw.data_ptr()),
static_cast<const T*>(kw.data_ptr()),
static_cast<const float*>(cache.data_ptr()),
static_cast<const IdType*>(positions.data_ptr()),
Sq.unwrap(),
Sk.unwrap(),
static_cast<uint32_t>(Q.unwrap()),
static_cast<uint32_t>(K.unwrap()),
static_cast<uint32_t>(rows),
eps);
};
if (is_type<int32_t>(positions.dtype()))
launch.template operator()<int32_t>();
else
launch.template operator()<int64_t>();
}

} // namespace sglang
20 changes: 1 addition & 19 deletions python/sglang/kernels/jit/csrc/elementwise/qknorm.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -105,25 +105,7 @@ __global__ void fused_qknorm_half_warp(const QKNormParams __grid_constant__ para
auto vec = load_as<Storage>(input, row_lane);
const auto weight_vec = load_as<Storage>(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<fp32x2_t>(vec[i]);
part[i / 2] += x.x * x.x;
part[i / 2] += x.y * x.y;
}
part[0] = warp::reduce_sum<kRowLanes>(part[0]);
part[1] = warp::reduce_sum<kRowLanes>(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<fp32x2_t>(vec[i]);
const auto w = cast<fp32x2_t>(weight_vec[i]);
vec[i] = cast<Packed, fp32x2_t>({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<Storage>(input, vec, row_lane);
}

Expand Down
31 changes: 31 additions & 0 deletions python/sglang/kernels/jit/include/sgl_kernel/impl/norm.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,37 @@ SGL_DEVICE T apply_norm_warp(const T& input, const T& weight, float eps) {
return details::apply_norm_impl<kDim, false>(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 <typename PackedFloat>
SGL_DEVICE AlignedVector<PackedFloat, 4>
apply_norm_half_warp(AlignedVector<PackedFloat, 4> input, const AlignedVector<PackedFloat, 4>& 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<fp32x2_t>(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<fp32x2_t>(input[i]);
const auto w = cast<fp32x2_t>(weight[i]);
input[i] = cast<PackedFloat, fp32x2_t>({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
Expand Down
9 changes: 9 additions & 0 deletions python/sglang/kernels/ops/attention/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
81 changes: 81 additions & 0 deletions python/sglang/kernels/ops/attention/qk_norm_rope.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading