Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
sglang · 4 changed files
Base commit: 340db9201005fc64635bb25db1d2538f955761c3
diff --git a/python/sglang/srt/hardware_backend/npu/memory_pool_npu.py b/python/sglang/srt/hardware_backend/npu/memory_pool_npu.pyindex a685406f2bffff4efddd8bc093558322e8b45b74..b88debf59f06382dadb5d9ae19b2067580bc639c 100644--- a/python/sglang/srt/hardware_backend/npu/memory_pool_npu.py+++ b/python/sglang/srt/hardware_backend/npu/memory_pool_npu.py@@ -170,6 +170,27 @@ class NPUMHATokenToKVPool(MHATokenToKVPool): ] return kv_data_ptrs, kv_data_lens, kv_item_lens + def get_direct_write_kv_buffers(self, layer_id: int):+ """Return cache storage suitable for a fused per-token NHD write.++ This deliberately excludes FIA and quantized/bitcast cache variants,+ whose physical layouts or write conversions differ from a dense row+ indexed by ``out_cache_loc``.+ """+ if (+ self.use_fia+ or self.kv_cache_layout != "nhd"+ or self.store_dtype != self.dtype+ or self.is_quantized_kv_cache+ or self.head_dim != self.v_head_dim+ ):+ return None++ if self.layer_transfer_counter is not None:+ self.layer_transfer_counter.wait_until(layer_id - self.start_layer)+ local_layer_id = layer_id - self.start_layer+ return self.k_buffer[local_layer_id], self.v_buffer[local_layer_id]+ def set_kv_buffer( self, layer: "RadixAttention",diff --git a/python/sglang/srt/models/qwen3.py b/python/sglang/srt/models/qwen3.pyindex 9fbd046709e6d2d557b005f22d8b8586727fcec4..dbbed9fcb3e6df88d3e40d18c68021b0bde66a72 100644--- a/python/sglang/srt/models/qwen3.py+++ b/python/sglang/srt/models/qwen3.py@@ -24,7 +24,11 @@ from sglang.srt.model_executor.cuda_graph_config import ( Phase, check_cuda_graph_backend, )-from sglang.srt.model_executor.forward_batch_info import ForwardBatch, PPProxyTensors+from sglang.srt.model_executor.forward_batch_info import (+ ForwardBatch,+ ForwardMode,+ PPProxyTensors,+) from sglang.srt.model_executor.forward_context import get_token_to_kv_pool from sglang.srt.model_loader.weight_utils import ( default_weight_loader,@@ -188,6 +192,51 @@ class Qwen3Attention(nn.Module): if self.attn.layer_id == self.start_layer: self.rotary_emb.get_cos_sin_with_position(positions)++ cache_kwargs = {}+ if (+ forward_batch.forward_mode == ForwardMode.EXTEND+ and forward_batch.dcp_kv_mask is None+ and get_exec().deterministic.rl_on_policy_target is None+ ):+ token_to_kv_pool = get_token_to_kv_pool()+ get_direct_buffers = getattr(+ token_to_kv_pool, "get_direct_write_kv_buffers", None+ )+ if get_direct_buffers is not None:+ buffers = get_direct_buffers(self.attn.layer_id)+ cache_loc = forward_batch.out_cache_loc+ if buffers is not None:+ k_cache, v_cache = buffers+ cache_row_size_matches = (+ k_cache.shape[-2] * k_cache.shape[-1] == self.kv_size+ and v_cache.shape[-2] * v_cache.shape[-1] == self.kv_size+ )+ cache_storage_matches = (+ k_cache.dtype == qkv.dtype+ and v_cache.dtype == qkv.dtype+ and k_cache.device == qkv.device+ and v_cache.device == qkv.device+ and k_cache.is_contiguous()+ and v_cache.is_contiguous()+ )+ cache_loc_matches = (+ cache_loc.device == qkv.device+ and cache_loc.dtype in (torch.int32, torch.int64)+ and cache_loc.is_contiguous()+ and cache_loc.numel() == qkv.shape[0]+ )+ if (+ cache_row_size_matches+ and cache_storage_matches+ and cache_loc_matches+ ):+ cache_kwargs = {+ "k_cache": k_cache,+ "v_cache": v_cache,+ "cache_loc": cache_loc,+ }+ q, k, v = split_qkv_rmsnorm_rope( qkv, self.rotary_emb.position_sin,@@ -200,6 +249,7 @@ class Qwen3Attention(nn.Module): k_weight=self.k_norm.weight, q_bias=getattr(self.q_norm, "bias", None), k_bias=getattr(self.k_norm, "bias", None),+ **cache_kwargs, ) return q, k, v @@ -297,6 +347,9 @@ class Qwen3Attention(nn.Module): hidden_states=hidden_states, forward_batch=forward_batch, )+ if k is None:+ assert v is None+ save_kv_cache = False if get_exec().deterministic.rl_on_policy_target is not None: q = q.to(torch.bfloat16)diff --git a/sgl-kernel-npu/python/sgl_kernel_npu/sgl_kernel_npu/norm/split_qkv_rmsnorm_rope.py b/sgl-kernel-npu/python/sgl_kernel_npu/sgl_kernel_npu/norm/split_qkv_rmsnorm_rope.pyindex 2b41121ef1893a48688206a8b7594792477e35cc..79adbff279d49221d7c0a6a9d3bcb80c0a44521b 100644--- a/sgl-kernel-npu/python/sgl_kernel_npu/sgl_kernel_npu/norm/split_qkv_rmsnorm_rope.py+++ b/sgl-kernel-npu/python/sgl_kernel_npu/sgl_kernel_npu/norm/split_qkv_rmsnorm_rope.py@@ -13,6 +13,7 @@ def split_qkv_rmsnorm_rope_kernel( q_ptr, k_ptr, v_ptr,+ cache_loc_ptr, q_weight_ptr, q_bias_ptr, k_weight_ptr,@@ -32,6 +33,7 @@ def split_qkv_rmsnorm_rope_kernel( PASS_DIM: tl.constexpr, DO_PARTIAL: tl.constexpr, DO_HALF: tl.constexpr,+ WRITE_KV_CACHE: tl.constexpr, ): row_pid = tl.program_id(0) col_pid = tl.program_id(1)@@ -205,6 +207,10 @@ def split_qkv_rmsnorm_rope_kernel( for row_idx in tl.range(row_pid, batch_size, row_step): col_indices = col_pid * KV_BLOCK_SIZE + tl.arange(0, KV_BLOCK_SIZE) valid_mask = col_indices < kv_hidden_size+ if WRITE_KV_CACHE:+ cache_loc = tl.load(cache_loc_ptr + row_idx).to(tl.int32)+ output_offset = cache_loc * kv_hidden_size+ valid_mask = valid_mask & (cache_loc >= 0) input_values = ( tl.load(input_ptr + input_offset + col_indices, mask=valid_mask, other=0.0) .to(tl.float32)@@ -352,20 +358,26 @@ def split_qkv_rmsnorm_rope_kernel( mask=valid_mask, ) input_offset += input_offset_step- output_offset += output_offset_step+ if not WRITE_KV_CACHE:+ output_offset += output_offset_step # v input_offset = row_pid * total_hidden_size + q_hidden_size + kv_hidden_size output_offset = row_pid * kv_hidden_size- for _ in tl.range(row_pid, batch_size, row_step):+ for row_idx in tl.range(row_pid, batch_size, row_step): col_indices = col_pid * KV_BLOCK_SIZE + tl.arange(0, KV_BLOCK_SIZE) valid_mask = col_indices < kv_hidden_size+ if WRITE_KV_CACHE:+ cache_loc = tl.load(cache_loc_ptr + row_idx).to(tl.int32)+ output_offset = cache_loc * kv_hidden_size+ valid_mask = valid_mask & (cache_loc >= 0) input_values = tl.load( input_ptr + input_offset + col_indices, mask=valid_mask, other=0.0 ) tl.store(v_ptr + output_offset + col_indices, input_values, mask=valid_mask) input_offset += input_offset_step- output_offset += output_offset_step+ if not WRITE_KV_CACHE:+ output_offset += output_offset_step kernels = {}@@ -384,7 +396,17 @@ def split_qkv_rmsnorm_rope( q_bias=None, k_bias=None, is_neox_style=True,+ k_cache=None,+ v_cache=None,+ cache_loc=None, ):+ """Split QKV, normalize Q/K, and apply rotary embeddings.++ When ``k_cache``, ``v_cache``, and ``cache_loc`` are supplied, the kernel+ writes K/V directly to cache rows selected by ``cache_loc``. In that mode+ it returns ``(q, None, None)`` and avoids both temporary K/V tensors and a+ subsequent cache-scatter kernel launch.+ """ _, num_vectorcore = get_device_properties() KV_BLOCK_SIZE = triton.next_power_of_2(head_dim)@@ -396,12 +418,39 @@ def split_qkv_rmsnorm_rope( q_output = torch.empty( batch_size, q_hidden_size, device=input.device, dtype=input.dtype )- k_output = torch.empty(- batch_size, kv_hidden_size, device=input.device, dtype=input.dtype- )- v_output = torch.empty(- batch_size, kv_hidden_size, device=input.device, dtype=input.dtype- )+ cache_args = (k_cache, v_cache, cache_loc)+ write_kv_cache = all(arg is not None for arg in cache_args)+ if any(arg is not None for arg in cache_args) and not write_kv_cache:+ raise ValueError("k_cache, v_cache, and cache_loc must be provided together")++ if write_kv_cache:+ if not k_cache.is_contiguous() or not v_cache.is_contiguous():+ raise ValueError("K/V cache tensors must be contiguous")+ if k_cache.dtype != input.dtype or v_cache.dtype != input.dtype:+ raise ValueError("K/V cache and input dtypes must match")+ if k_cache.device != input.device or v_cache.device != input.device:+ raise ValueError("K/V cache and input devices must match")+ if cache_loc.device != input.device:+ raise ValueError("cache_loc and input devices must match")+ if cache_loc.dtype not in (torch.int32, torch.int64):+ raise ValueError("cache_loc must have int32 or int64 dtype")+ if not cache_loc.is_contiguous() or cache_loc.numel() != batch_size:+ raise ValueError("cache_loc must be contiguous with one entry per token")+ if k_cache.numel() % kv_hidden_size != 0:+ raise ValueError("K cache rows must have kv_hidden_size elements")+ if v_cache.numel() % kv_hidden_size != 0:+ raise ValueError("V cache rows must have kv_hidden_size elements")+ k_output = k_cache+ v_output = v_cache+ else:+ k_output = torch.empty(+ batch_size, kv_hidden_size, device=input.device, dtype=input.dtype+ )+ v_output = torch.empty(+ batch_size, kv_hidden_size, device=input.device, dtype=input.dtype+ )+ # The pointer is unused in the compile-time-disabled branch.+ cache_loc = input n_cols = kv_hidden_size // KV_BLOCK_SIZE n_rows = (num_vectorcore + n_cols - 1) // n_cols BIAS = q_bias is not None@@ -414,6 +463,7 @@ def split_qkv_rmsnorm_rope( q_output, k_output, v_output,+ cache_loc, q_weight, q_bias, k_weight,@@ -433,8 +483,11 @@ def split_qkv_rmsnorm_rope( head_dim - rope_dim, DO_PARTIAL=(head_dim != rope_dim), DO_HALF=is_neox_style,+ WRITE_KV_CACHE=write_kv_cache, ) + if write_kv_cache:+ return q_output, None, None return q_output, k_output, v_output diff --git a/sgl-kernel-npu/tests/python/sgl_kernel_npu/test_split_qkv_rmsnorm_rope.py b/sgl-kernel-npu/tests/python/sgl_kernel_npu/test_split_qkv_rmsnorm_rope.pyindex f923d4e339442e6dae44b715c6db9cee3a08386a..ca51fc986c89f89bf9fa0eb19776094cc33ea1ae 100644--- a/sgl-kernel-npu/tests/python/sgl_kernel_npu/test_split_qkv_rmsnorm_rope.py+++ b/sgl-kernel-npu/tests/python/sgl_kernel_npu/test_split_qkv_rmsnorm_rope.py@@ -135,6 +135,67 @@ def test_split_qkv_rmsnorm_rope(): ) +def test_split_qkv_rmsnorm_rope_direct_cache_write():+ q_hidden_size = 2048+ kv_hidden_size = 1024+ head_dim = 128+ bsz = 7+ eps = 1e-6++ qkv = torch.randn(+ bsz, q_hidden_size + kv_hidden_size * 2, dtype=torch.bfloat16, device="npu"+ )+ q_weight = torch.randn(head_dim, dtype=torch.bfloat16, device="npu")+ k_weight = torch.randn(head_dim, dtype=torch.bfloat16, device="npu")+ sin = torch.randn(bsz, 1, 1, head_dim, dtype=torch.bfloat16, device="npu")+ cos = torch.randn(bsz, 1, 1, head_dim, dtype=torch.bfloat16, device="npu")++ expected_q, expected_k, expected_v = split_qkv_rmsnorm_rope(+ qkv,+ sin,+ cos,+ q_hidden_size,+ kv_hidden_size,+ head_dim,+ eps=eps,+ q_weight=q_weight,+ k_weight=k_weight,+ )++ cache_rows = 32+ cache_loc = torch.tensor(+ [17, 2, 31, 8, 5, 22, 1], dtype=torch.int64, device="npu"+ )+ k_cache = torch.full(+ (cache_rows, kv_hidden_size), 11, dtype=torch.bfloat16, device="npu"+ )+ v_cache = torch.full(+ (cache_rows, kv_hidden_size), 13, dtype=torch.bfloat16, device="npu"+ )+ q, k, v = split_qkv_rmsnorm_rope(+ qkv,+ sin,+ cos,+ q_hidden_size,+ kv_hidden_size,+ head_dim,+ eps=eps,+ q_weight=q_weight,+ k_weight=k_weight,+ k_cache=k_cache,+ v_cache=v_cache,+ cache_loc=cache_loc,+ )++ assert k is None+ assert v is None+ assert torch.equal(q, expected_q)+ assert torch.equal(k_cache[cache_loc], expected_k)+ assert torch.equal(v_cache[cache_loc], expected_v)+ assert torch.all(k_cache[0] == 11)+ assert torch.all(v_cache[0] == 13)++ def test_split_qkv_rope(): q_hidden_size = 6144 kv_hidden_size = 1024