diff --git a/python/sglang/kernels/jit/csrc/diffusion/qknorm_rope.cuh b/python/sglang/kernels/jit/csrc/diffusion/qknorm_rope.cuh index 13ffbca318..dbd478c863 100644 --- a/python/sglang/kernels/jit/csrc/diffusion/qknorm_rope.cuh +++ b/python/sglang/kernels/jit/csrc/diffusion/qknorm_rope.cuh @@ -469,6 +469,146 @@ __global__ void fused_qknorm_rope_warp(const QKNormRopeParamsT(); } +/// \brief `fused_qknorm_rope_warp` for head_dim 128 with the norm rounded before +/// NeoX RoPE, two rows per warp: 16 lanes per row, 16 B per lane. Each lane keeps +/// the partial sums of the two warp-kernel lanes it covers and replays their xor +/// butterfly, so the output is bit-identical to the one-row-per-warp kernel. +template +__global__ void fused_qknorm_rope_half_warp(const QKNormRopeParamsT __grid_constant__ params) { + using namespace device; + + constexpr int64_t kHeadDim = 128; + constexpr uint32_t kRowLanes = 16; + constexpr uint32_t kElems = kHeadDim / kRowLanes; + constexpr uint32_t kRotaryLanes = kRopeDim / kElems; + constexpr uint32_t kHalfRotaryLanes = kRotaryLanes / 2; + constexpr int64_t kCosSinStrideBytes = kRopeDim * sizeof(CacheDType); + static_assert(kRopeDim > 0 && kRopeDim <= kHeadDim && kRopeDim % (2 * kElems) == 0); + + using Packed = packed_t; + using Storage = AlignedVector; + + const auto& [q_ptr, k_ptr, q_weight_ptr, k_weight_ptr, cos_sin_cache_ptr, positions, q_stride_bytes, k_stride_bytes, head_stride_bytes, num_qo_heads, num_kv_heads, num_tokens, eps] = + static_cast(params); + + const uint32_t lane_id = threadIdx.x % kWarpThreads; + const uint32_t row_lane = lane_id % kRowLanes; + const uint32_t row_base = lane_id - row_lane; + const uint32_t start_worker_id = blockIdx.x * kWarpsPerBlock + threadIdx.x / kWarpThreads; + const uint32_t num_workers = gridDim.x * kWarpsPerBlock; + const uint32_t num_qk_heads = num_qo_heads + num_kv_heads; + const uint32_t num_rows = num_qk_heads * num_tokens; + const uint32_t num_pairs = div_ceil(num_rows, 2u); + const uint32_t partner_lane = row_base + (row_lane < kHalfRotaryLanes ? row_lane + kHalfRotaryLanes + : row_lane < kRotaryLanes ? row_lane - kHalfRotaryLanes + : row_lane); + + PDLWaitPrimary(); + + for (uint32_t pair = start_worker_id; pair < num_pairs; pair += num_workers) { + // a missing second row recomputes the last one and skips the store + const uint32_t wanted_row = 2 * pair + lane_id / kRowLanes; + const uint32_t row = wanted_row < num_rows ? wanted_row : num_rows - 1; + const uint32_t token_id = row / num_qk_heads; + const uint32_t head_id = row % num_qk_heads; + const bool load_q = head_id < num_qo_heads; + const void* input = load_q ? pointer::offset(q_ptr, token_id * q_stride_bytes, head_id * head_stride_bytes) + : pointer::offset(k_ptr, token_id * k_stride_bytes, head_id * head_stride_bytes); + void* output = const_cast(input); + if constexpr (kOutOfPlace) { + output = + load_q ? pointer::offset( + params.q_out_ptr, token_id * params.q_out_stride_bytes, head_id * params.out_head_stride_bytes) + : pointer::offset( + params.k_out_ptr, token_id * params.k_out_stride_bytes, head_id * params.out_head_stride_bytes); + } + + auto vec = load_as(input, row_lane); + const auto weight_vec = load_as(load_q ? q_weight_ptr : k_weight_ptr, row_lane); + + // part[h] is the sum of warp-kernel lane 2 * row_lane + h, and the shuffles + // below are that kernel's 16..2 xor steps; its final step adds the pair. + float part[2] = {0.0f, 0.0f}; +#pragma unroll + for (uint32_t j = 0; j < kElems / 2; ++j) { + const auto x = cast(vec[j]); + part[j / 2] += x.x * x.x; + part[j / 2] += x.y * x.y; + } +#pragma unroll + for (uint32_t mask = kRowLanes / 2; mask >= 1; mask >>= 1) { + part[0] += __shfl_xor_sync(0xffffffffu, part[0], mask); + part[1] += __shfl_xor_sync(0xffffffffu, part[1], mask); + } + const float norm_factor = math::rsqrt((part[0] + part[1]) / kHeadDim + eps); + +#pragma unroll + for (uint32_t j = 0; j < kElems / 2; ++j) { + const auto x = cast(vec[j]); + const auto w = cast(weight_vec[j]); + vec[j] = cast({x.x * norm_factor * w.x, x.y * norm_factor * w.y}); + } + + Storage partner_vec; +#pragma unroll + for (uint32_t j = 0; j < kElems / 2; ++j) { + auto bits = reinterpret_cast(vec[j]); + bits = __shfl_sync(0xffffffffu, bits, partner_lane); + reinterpret_cast(partner_vec[j]) = bits; + } + if (row_lane < kRotaryLanes) { + const auto pos = static_cast(static_cast(positions)[token_id]); + const auto cos_ptr = static_cast(pointer::offset(cos_sin_cache_ptr, pos * kCosSinStrideBytes)); + const auto sin_ptr = cos_ptr + kRopeDim / 2; + const uint32_t cache_base = (row_lane % kHalfRotaryLanes) * kElems; + // one 16 B load per lane for a 16-bit cache; FP32 rows take two + CacheDType cos_vals[kElems]; + CacheDType sin_vals[kElems]; + constexpr uint32_t kCacheVecElems = 16 / sizeof(CacheDType); + using CacheVec = AlignedVector; +#pragma unroll + for (uint32_t c = 0; c < kElems / kCacheVecElems; ++c) { + const auto cos_vec = load_as(cos_ptr + cache_base, c); + const auto sin_vec = load_as(sin_ptr + cache_base, c); +#pragma unroll + for (uint32_t e = 0; e < kCacheVecElems; ++e) { + cos_vals[c * kCacheVecElems + e] = cos_vec[e]; + sin_vals[c * kCacheVecElems + e] = sin_vec[e]; + } + } +#pragma unroll + for (uint32_t j = 0; j < kElems / 2; ++j) { + auto& values = unpack(vec[j]); + const auto& partner_values = unpack(partner_vec[j]); +#pragma unroll + for (uint32_t i = 0; i < 2; ++i) { + const auto cos = cos_vals[2 * j + i]; + const auto sin = sin_vals[2 * j + i]; + if constexpr (std::is_same_v) { + values[i] = row_lane < kHalfRotaryLanes ? rotary_sub_fp32(values[i], cos, partner_values[i], sin) + : rotary_add_fp32(values[i], cos, partner_values[i], sin); + } else { + values[i] = row_lane < kHalfRotaryLanes ? rotary_sub(values[i], cos, partner_values[i], sin) + : rotary_add(values[i], cos, partner_values[i], sin); + } + } + } + } + if (wanted_row < num_rows) store_as(output, vec, row_lane); + } + + PDLTriggerSecondary(); +} + +/// \brief Whether `fused_qknorm_rope_half_warp` covers this instantiation. +template +inline constexpr bool kUseHalfWarp = +#ifdef USE_ROCM + false; +#else + kHeadDim == 128 && kIsNeox && kRoundNormBeforeRope && !kCacheHasFullWidth && kRopeDim > 0 && kRopeDim % 16 == 0; +#endif + /// \brief Shared launch tail of the three host runners: pick the index-type /// instantiation, size the persistent grid from the occupancy table, launch. template @@ -494,21 +634,31 @@ template < typename DType, typename CacheDType, bool kRoundNormBeforeRope, - bool kCacheHasFullWidth> + bool kCacheHasFullWidth, + bool kAllowHalfWarp = true> struct QKNormRopeKernel { static_assert(kHeadDim <= 256, "Only head_dim <= 256 is supported"); + // kAllowHalfWarp = false keeps the one-row-per-warp kernel, which tests compare against + static constexpr bool kHalfWarp = + kAllowHalfWarp && kUseHalfWarp; template - static constexpr auto kernel = fused_qknorm_rope_warp< - kHeadDim, - kRopeDim, - kIsNeox, - kUsePDL, - DType, - CacheDType, - kRoundNormBeforeRope, - false, - kCacheHasFullWidth, - IdType>; + static constexpr auto kernel = [] { + if constexpr (kHalfWarp) { + return fused_qknorm_rope_half_warp; + } else { + return fused_qknorm_rope_warp< + kHeadDim, + kRopeDim, + kIsNeox, + kUsePDL, + DType, + CacheDType, + kRoundNormBeforeRope, + false, + kCacheHasFullWidth, + IdType>; + } + }(); static void run(const tvm::ffi::TensorView q, @@ -568,7 +718,8 @@ struct QKNormRopeKernel { .eps = eps, }; - const auto num_works = (num_qo_heads + num_kv_heads) * num_tokens; + const auto num_rows = (num_qo_heads + num_kv_heads) * num_tokens; + const auto num_works = kHalfWarp ? div_ceil(num_rows, 2u) : num_rows; launch_qknorm_rope, kernel>( params, id_type.is_type(), num_works, device.unwrap(), kUsePDL); } @@ -582,22 +733,32 @@ template < typename DType, typename CacheDType, bool kRoundNormBeforeRope, - bool kCacheHasFullWidth> + bool kCacheHasFullWidth, + bool kAllowHalfWarp = true> struct QKNormRopeOutOfPlaceKernel { static_assert(kHeadDim <= 256, "Only head_dim <= 256 is supported"); + // kAllowHalfWarp = false keeps the one-row-per-warp kernel, which tests compare against + static constexpr bool kHalfWarp = + kAllowHalfWarp && kUseHalfWarp; template - static constexpr auto kernel = fused_qknorm_rope_warp< - kHeadDim, - kRopeDim, - kIsNeox, - kUsePDL, - DType, - CacheDType, - kRoundNormBeforeRope, - false, - kCacheHasFullWidth, - IdType, - true>; + static constexpr auto kernel = [] { + if constexpr (kHalfWarp) { + return fused_qknorm_rope_half_warp; + } else { + return fused_qknorm_rope_warp< + kHeadDim, + kRopeDim, + kIsNeox, + kUsePDL, + DType, + CacheDType, + kRoundNormBeforeRope, + false, + kCacheHasFullWidth, + IdType, + true>; + } + }(); /// \brief QK-norm + RoPE from q/k into q_out/k_out; q and k are left untouched. static void @@ -665,7 +826,8 @@ struct QKNormRopeOutOfPlaceKernel { params.k_out_stride_bytes = static_cast(Dko.unwrap() * sizeof(DType)); params.out_head_stride_bytes = out_head_stride_bytes; - const auto num_works = (num_qo_heads + num_kv_heads) * num_tokens; + const auto num_rows = (num_qo_heads + num_kv_heads) * num_tokens; + const auto num_works = kHalfWarp ? div_ceil(num_rows, 2u) : num_rows; launch_qknorm_rope, kernel>( params, id_type.is_type(), num_works, device.unwrap(), kUsePDL); } diff --git a/python/sglang/kernels/ops/diffusion/rope/qknorm_rope_jit.py b/python/sglang/kernels/ops/diffusion/rope/qknorm_rope_jit.py index 9ba926be98..1d1311cdb3 100644 --- a/python/sglang/kernels/ops/diffusion/rope/qknorm_rope_jit.py +++ b/python/sglang/kernels/ops/diffusion/rope/qknorm_rope_jit.py @@ -34,8 +34,11 @@ def _jit_qknorm_rope_module( pack_kv: bool = False, cache_has_full_width: bool = False, out_of_place: bool = False, + half_warp: bool = True, ) -> Module: - args = make_cpp_args( + """``half_warp=False`` keeps the one-row-per-warp kernel where the two-rows + variant would apply; tests use it as the bit-exactness oracle.""" + template_args = [ head_dim, rope_dim, is_neox, @@ -44,13 +47,16 @@ def _jit_qknorm_rope_module( cache_dtype, round_norm_before_rope, cache_has_full_width, - ) + ] if pack_kv: op_name, kernel_name = "qknorm_rope_pack_kv", "QKNormRopePackKVKernel" elif out_of_place: op_name, kernel_name = "qknorm_rope_out_of_place", "QKNormRopeOutOfPlaceKernel" else: op_name, kernel_name = "qknorm_rope", "QKNormRopeKernel" + if not pack_kv: + template_args.append(half_warp) + args = make_cpp_args(*template_args) return load_jit( op_name, *args, diff --git a/test/registered/kernels/benchmark/diffusion/bench_qknorm_rope.py b/test/registered/kernels/benchmark/diffusion/bench_qknorm_rope.py index 3a73d39f36..afdcbb7d1f 100644 --- a/test/registered/kernels/benchmark/diffusion/bench_qknorm_rope.py +++ b/test/registered/kernels/benchmark/diffusion/bench_qknorm_rope.py @@ -41,6 +41,9 @@ BENCH_CASES = ( # Z-Image-Turbo default 1024x1024 config: dim=3840, num_heads=30 -> head_dim=128. CaseSpec("zimage_1024", 1, 4096, 30, 128, 128, False), CaseSpec("longcat_1024", 1, 4608, 24, 128, 128, False, True, True), + # MiniMax-H3 Ref2VA at Ulysses 2: 24826 tokens per rank, NeoX over the first + # 96 of 128 dims, norm rounded before RoPE (the two-rows-per-warp kernel). + CaseSpec("minimax_h3_ref2va", 1, 24826, 56, 128, 96, True, False, True), CaseSpec("batch2_medium", 2, 2048, 24, 128, 128, False), ) CASE_BY_NAME = {case.name: case for case in BENCH_CASES} diff --git a/test/registered/kernels/ops/diffusion/test_qknorm_rope_out_of_place.py b/test/registered/kernels/ops/diffusion/test_qknorm_rope_out_of_place.py index 6eee339892..e20a5820e3 100644 --- a/test/registered/kernels/ops/diffusion/test_qknorm_rope_out_of_place.py +++ b/test/registered/kernels/ops/diffusion/test_qknorm_rope_out_of_place.py @@ -10,7 +10,8 @@ from sglang.kernels.ops.diffusion import ( ) from sglang.test.ci.ci_register import register_cuda_ci -register_cuda_ci(est_time=20, stage="base-b-kernel-unit", runner_config="4-gpu-b200") +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="4-gpu-b200") +register_cuda_ci(est_time=60, stage="base-b-kernel-unit", runner_config="1-gpu-large") def test_out_of_place_qknorm_rope_matches_inplace_and_keeps_inputs() -> None: @@ -44,5 +45,68 @@ def test_out_of_place_qknorm_rope_matches_inplace_and_keeps_inputs() -> None: assert torch.equal(q_out, q_ref) and torch.equal(k_out, k_ref) +# each case JIT-builds two modules, so these cover the branches, not the product: +# H3's own config both ways, then the FP32-cache, FP16, int32 and rope-width paths +@pytest.mark.parametrize( + "out_of_place,rope_dim,dtype,cache_dtype,pos_dtype", + [ + (False, 96, torch.bfloat16, torch.bfloat16, torch.int64), + (True, 96, torch.bfloat16, torch.bfloat16, torch.int64), + (True, 32, torch.bfloat16, torch.float32, torch.int32), + (False, 128, torch.float16, torch.float16, torch.int32), + ], +) +def test_two_rows_per_warp_match_one_row_per_warp( + out_of_place: bool, + rope_dim: int, + dtype: torch.dtype, + cache_dtype: torch.dtype, + pos_dtype: torch.dtype, +) -> None: + """head_dim 128 with the norm rounded before NeoX RoPE runs two rows per + warp; its bytes must equal the one-row-per-warp kernel's on every arch.""" + from sglang.kernels.ops.diffusion.rope.qknorm_rope_jit import ( + _jit_qknorm_rope_module, + ) + + T, H, D = 1037, 7, 128 # an odd row count leaves the last warp one row + g = torch.Generator(device="cpu").manual_seed(rope_dim) + qkv = (3 * torch.randn(T, 3 * H * D, generator=g)).to("cuda", dtype) + q = qkv[:, : H * D].view(T, H, D) + k = qkv[:, H * D : 2 * H * D].view(T, H, D) + qw = (torch.rand(D, generator=g) + 0.5).to("cuda", dtype) + kw = (torch.rand(D, generator=g) + 0.5).to("cuda", dtype) + freqs = 50 * torch.randn(T, rope_dim // 2, generator=g) + cache = torch.cat((freqs.cos(), freqs.sin()), -1).to("cuda", cache_dtype) + pos = torch.randperm(T, generator=g).to("cuda", pos_dtype) + outputs = [] + for half_warp in (False, True): + module = _jit_qknorm_rope_module( + D, + rope_dim, + True, + dtype, + cache_dtype, + True, + False, + False, + out_of_place, + half_warp=half_warp, + ) + if out_of_place: + q_out = torch.empty(T, H, D, device="cuda", dtype=dtype) + k_out = torch.empty_like(q_out) + module.qknorm_rope_out_of_place( + q, k, q_out, k_out, qw, kw, cache, pos, 1e-5 + ) + outputs.append((q_out, k_out)) + else: + q2, k2 = q.clone(), k.clone() + module.qknorm_rope(q2, k2, qw, kw, cache, pos, 1e-5) + outputs.append((q2, k2)) + (q_ref, k_ref), (q_new, k_new) = outputs + assert torch.equal(q_ref, q_new) and torch.equal(k_ref, k_new) + + if __name__ == "__main__": sys.exit(pytest.main([__file__, "-v"]))