Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
sglang · 5 changed files
Base commit: 340db9201005fc64635bb25db1d2538f955761c3
diff --git a/python/sglang/srt/hardware_backend/npu/attention/ascend_hybrid_linear_attn_backend.py b/python/sglang/srt/hardware_backend/npu/attention/ascend_hybrid_linear_attn_backend.pyindex 90a52a121cc49d607f506f5bd4a5185730b7f9c6..11f0061472e963a9942594bab5f1ad8b60ec712f 100644--- a/python/sglang/srt/hardware_backend/npu/attention/ascend_hybrid_linear_attn_backend.py+++ b/python/sglang/srt/hardware_backend/npu/attention/ascend_hybrid_linear_attn_backend.py@@ -12,10 +12,13 @@ from sglang.srt.layers.attention.hybrid_linear_attn_backend import ( HybridLinearAttnBackend, MambaAttnBackendBase, )+from sglang.srt.layers.attention.linear.short_conv_backend import (+ ShortConvAttnBackend,+) from sglang.srt.layers.attention.mamba.mamba2_metadata import ( ForwardMetadata, )-from sglang.srt.model_executor.forward_batch_info import ForwardMode+from sglang.srt.model_executor.forward_batch_info import ForwardBatch, ForwardMode from sglang.srt.model_executor.model_runner import ModelRunner from sglang.srt.speculative.eagle_info import EagleDraftInput, EagleVerifyInput from sglang.srt.speculative.spec_info import SpecInput@@ -217,6 +220,21 @@ class AscendMamba2AttnBackend(AscendMambaAttnBackendBase): pass +class AscendShortConvAttnBackend(+ ShortConvAttnBackend, AscendMambaAttnBackendBase+):+ """Ascend state sidecar for short-convolution hybrid models.++ ``ShortConvAttnBackend`` owns the model-independent state handle while+ ``AscendMambaAttnBackendBase`` supplies Ascend's graph-safe metadata+ buffers. Keeping the cache indices as int32 also matches the native NPU+ causal-convolution kernels and avoids a cast in every convolution layer.+ """++ cache_indices_dtype = torch.int32+ needs_extend_host_mirrors = False++ class AscendHybridLinearAttnBackend(HybridLinearAttnBackend): def __init__( self,@@ -320,3 +338,19 @@ class AscendHybridLinearAttnBackend(HybridLinearAttnBackend): self, spec_info: SpecInput, cuda_graph_bs: Optional[int] ): pass+++class AscendShortConvHybridAttnBackend(AscendHybridLinearAttnBackend):+ """Ascend hybrid wrapper exposing the short-conv state sidecar to models."""++ def __init__(+ self,+ full_attn_backend: AttentionBackend,+ short_conv_backend: AscendShortConvAttnBackend,+ full_attn_layers: list[int],+ ):+ super().__init__(full_attn_backend, short_conv_backend, full_attn_layers)+ self.short_conv_backend = short_conv_backend++ def conv_state_metadata(self, layer_id: int, forward_batch: ForwardBatch):+ return self.short_conv_backend.conv_state_metadata(layer_id, forward_batch)diff --git a/python/sglang/srt/hardware_backend/npu/short_conv.py b/python/sglang/srt/hardware_backend/npu/short_conv.pynew file mode 100644index 0000000000000000000000000000000000000000..dc675419a3acd0327dc911deb87116fd820d854e--- /dev/null+++ b/python/sglang/srt/hardware_backend/npu/short_conv.py@@ -0,0 +1,90 @@+# Copyright 2023-2026 SGLang Team+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ==============================================================================+"""Ascend helpers for LFM2 short-convolution hybrid models."""++from typing import Optional, Sequence++import torch++from sglang.kernels.ops.mamba.causal_conv1d_triton import (+ causal_conv1d_fn as causal_conv1d_fn_triton,+)+++def short_conv_npu(+ x: torch.Tensor,+ conv_state: torch.Tensor,+ weight: torch.Tensor,+ bias: Optional[torch.Tensor],+ cache_indices: torch.Tensor,+ *,+ query_start_loc: Optional[torch.Tensor] = None,+ seq_lens_cpu: Optional[Sequence[int]] = None,+ has_initial_state: Optional[torch.Tensor] = None,+ activation: Optional[str] = None,+) -> torch.Tensor:+ """Run short conv against Ascend's ``[slot, K-1, dim]`` state layout.++ Decode performs the stock BF16 window reduction directly against Ascend's+ state layout. Prefill exposes that storage as a stride-only channel-major+ view to SGLang's packed causal-conv kernel; this preserves the portable+ kernel's numerics and updates every row in a ragged continuous batch.+ """++ if query_start_loc is None:+ # Ascend stores state as [slot, K-1, dim]. Build the same contiguous+ # [batch, dim, K] window used by causal_conv1d_update_npu, but avoid its+ # second advanced-index gather and both full-state contiguous+ # transposes. Besides halving this update's latency, keeping the+ # multiply + reduction unchanged preserves its BF16 token numerics.+ active_state = conv_state.index_select(0, cache_indices)+ state_len = active_state.shape[1]+ window = torch.cat(+ (active_state.transpose(1, 2), x.unsqueeze(-1)), dim=-1+ )+ window = window.to(weight.dtype)+ out = torch.sum(window * weight.unsqueeze(0), dim=-1)+ if bias is not None:+ out = out + bias+ if activation in ("silu", "swish"):+ out = torch.nn.functional.silu(out)+ conv_state.index_copy_(+ 0,+ cache_indices,+ window[:, :, -state_len:].transpose(1, 2),+ )+ return out.to(x.dtype)++ if seq_lens_cpu is None:+ raise ValueError("seq_lens_cpu is required for packed short-conv prefill")+ seq_lens = [int(value) for value in seq_lens_cpu]+ if not seq_lens:+ return x++ # The packed kernel is fully stride-aware. Expose Ascend's+ # [slot, K-1, dim] pool as a [slot, dim, K-1] view so it can gather and+ # update the live slots in place, without copying the pool through a+ # compact channel-major buffer in every model layer.+ out = causal_conv1d_fn_triton(+ x.transpose(0, 1),+ weight,+ bias,+ conv_states=conv_state.transpose(1, 2),+ query_start_loc=query_start_loc,+ seq_lens_cpu=seq_lens,+ cache_indices=cache_indices,+ has_initial_state=has_initial_state,+ activation=activation,+ ).transpose(0, 1)+ return outdiff --git a/python/sglang/srt/layers/attention/attention_registry.py b/python/sglang/srt/layers/attention/attention_registry.pyindex 9af985d73765d55f812d40af43986ebdeb783619..3bf80b1387bc300d3c80e2a19ff48648206dbc7a 100644--- a/python/sglang/srt/layers/attention/attention_registry.py+++ b/python/sglang/srt/layers/attention/attention_registry.py@@ -436,27 +436,34 @@ def attn_backend_wrapper(runner: "ModelRunner", full_attn_backend: "AttentionBac ) if isinstance(mamba2_config(runner.model_config), short_conv_cfgs): if is_npu():- # The model conv layers call- # get_attn_backend().conv_state_metadata() unconditionally,- # but the Ascend hybrid/mamba backend has no such method.- # Fail here (before model execution) with a clear message- # rather than an AttributeError deep in the first conv layer.- raise NotImplementedError(- "Short-conv hybrid models (ZAYA1 CCA, LFM2 / LFM2-MoE) "- "are not yet supported on NPU: the conv-state sidecar "- "(ShortConvAttnBackend.conv_state_metadata) has no Ascend "- "implementation. Add an Ascend conv-state backend before "- "serving these models on NPU."+ if isinstance(mamba2_config(runner.model_config), ZayaConfig):+ # Ascend stores short-conv state as [slot, window, dim],+ # whereas ZAYA's two-stage CCA kernels currently require+ # [slot, dim, window]. Keep the pre-existing explicit+ # rejection instead of silently exposing a transposed+ # state buffer to that unrelated model.+ raise NotImplementedError(+ "ZAYA1 CCA is not yet supported on NPU: its grouped "+ "convolution kernels require a channel-major state "+ "layout, but Ascend uses a window-major state layout."+ )+ from sglang.srt.hardware_backend.npu.attention.ascend_hybrid_linear_attn_backend import (+ AscendShortConvAttnBackend,+ AscendShortConvHybridAttnBackend,+ )++ linear_attn_backend = AscendShortConvAttnBackend(runner)+ hybrid_backend_cls = AscendShortConvHybridAttnBackend+ else:+ from sglang.srt.layers.attention.hybrid_linear_attn_backend import (+ ShortConvHybridAttnBackend,+ )+ from sglang.srt.layers.attention.linear.short_conv_backend import (+ ShortConvAttnBackend, )- from sglang.srt.layers.attention.hybrid_linear_attn_backend import (- ShortConvHybridAttnBackend,- )- from sglang.srt.layers.attention.linear.short_conv_backend import (- ShortConvAttnBackend,- ) - linear_attn_backend = ShortConvAttnBackend(runner)- hybrid_backend_cls = ShortConvHybridAttnBackend+ linear_attn_backend = ShortConvAttnBackend(runner)+ hybrid_backend_cls = ShortConvHybridAttnBackend else: linear_attn_backend = Mamba2AttnBackend(runner) elif kimi_linear_config(runner.model_config) is not None:diff --git a/python/sglang/srt/models/lfm2.py b/python/sglang/srt/models/lfm2.pyindex 765bc6b39dd9b9aa95784f906aa89db9f8ded0ea..ad150ea205d51976808e1460777f28b65dbc835e 100644--- a/python/sglang/srt/models/lfm2.py+++ b/python/sglang/srt/models/lfm2.py@@ -47,7 +47,12 @@ from sglang.srt.model_loader.weight_utils import ( sharded_weight_loader, ) from sglang.srt.runtime_context import get_parallel-from sglang.srt.utils import add_prefix, make_layers, set_weight_attrs+from sglang.srt.utils import add_prefix, is_npu, make_layers, set_weight_attrs++_is_npu = is_npu()++if _is_npu:+ from sglang.srt.hardware_backend.npu.short_conv import short_conv_npu logger = logging.getLogger(__name__) @@ -279,7 +284,23 @@ class Lfm2ShortConv(nn.Module): B_gate, C_gate, x = proj.chunk(3, dim=-1) Bx = B_gate * x - if forward_batch.forward_mode.is_decode():+ if _is_npu:+ query_start_loc = (+ None+ if forward_batch.forward_mode.is_decode()+ else meta.query_start_loc+ )+ conv_out = short_conv_npu(+ Bx,+ conv_state=conv_state,+ weight=self.conv_weight,+ bias=self.conv_bias,+ cache_indices=meta.cache_indices,+ query_start_loc=query_start_loc,+ seq_lens_cpu=forward_batch.extend_seq_lens_cpu,+ has_initial_state=meta.has_initial_state,+ )+ elif forward_batch.forward_mode.is_decode(): # Decode: single token per request, use optimized update kernel conv_out = causal_conv1d_update( Bx,diff --git a/python/sglang/srt/models/lfm2_moe.py b/python/sglang/srt/models/lfm2_moe.pyindex 59e71583be6add7b64da8684d0e0c8e6b1bc3ae3..a711bff116b689880f44b31a2cf71a8c99187313 100644--- a/python/sglang/srt/models/lfm2_moe.py+++ b/python/sglang/srt/models/lfm2_moe.py@@ -48,7 +48,12 @@ from sglang.srt.model_loader.weight_utils import ( sharded_weight_loader, ) from sglang.srt.runtime_context import get_parallel-from sglang.srt.utils import add_prefix, make_layers, set_weight_attrs+from sglang.srt.utils import add_prefix, is_npu, make_layers, set_weight_attrs++_is_npu = is_npu()++if _is_npu:+ from sglang.srt.hardware_backend.npu.short_conv import short_conv_npu class Lfm2MoeMLP(nn.Module):@@ -338,7 +343,23 @@ class Lfm2MoeShortConv(nn.Module): B_gate, C_gate, x = proj.chunk(3, dim=-1) Bx = B_gate * x - if forward_batch.forward_mode.is_decode():+ if _is_npu:+ query_start_loc = (+ None+ if forward_batch.forward_mode.is_decode()+ else meta.query_start_loc+ )+ conv_out = short_conv_npu(+ Bx,+ conv_state=conv_state,+ weight=self.conv_weight,+ bias=self.conv_bias,+ cache_indices=meta.cache_indices,+ query_start_loc=query_start_loc,+ seq_lens_cpu=forward_batch.extend_seq_lens_cpu,+ has_initial_state=meta.has_initial_state,+ )+ elif forward_batch.forward_mode.is_decode(): conv_out = causal_conv1d_update( Bx, conv_state,