Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
sglang · 3 changed files
Base commit: 340db9201005fc64635bb25db1d2538f955761c3
diff --git a/python/sglang/srt/hardware_backend/npu/attention/ascend_short_conv_backend.py b/python/sglang/srt/hardware_backend/npu/attention/ascend_short_conv_backend.pynew file mode 100644index 0000000000000000000000000000000000000000..801e2a8ad6cd3085ac3fbe00de87f338f965c5c3--- /dev/null+++ b/python/sglang/srt/hardware_backend/npu/attention/ascend_short_conv_backend.py@@ -0,0 +1,103 @@+"""Ascend short-conv (LFM2 / LFM2-MoE / ZAYA1 CCA) state sidecar.++The generic :class:`ShortConvAttnBackend+<sglang.srt.layers.attention.linear.short_conv_backend.ShortConvAttnBackend>`+owns the per-request conv-state plumbing and is platform agnostic; the only+Ascend-specific part is the *layout* of the state it hands out. The NPU mamba+pool allocates conv state as ``(slots, kernel - 1, dim)`` -- dim last, which is+what the Ascend grouped-conv AscendC ops want (see ``_init_npu_conv_state``) --+while the short-conv models consume ``(slots, dim, kernel - 1)``. This backend+transposes the per-layer pool views into that canonical layout and leaves every+other behaviour (slot resolution, prefix mask, cu-seqlens) to the base class.+"""++from __future__ import annotations++from typing import Any, NamedTuple++import torch++from sglang.srt.hardware_backend.npu.attention.ascend_hybrid_linear_attn_backend import (+ AscendHybridLinearAttnBackend,+)+from sglang.srt.layers.attention.linear.short_conv_backend import (+ ShortConvAttnBackend,+ ShortConvMetadata,+)+from sglang.srt.model_executor.forward_batch_info import ForwardBatch+++class AscendLayerConvCache(NamedTuple):+ """Canonical-layout stand-in for a :class:`MambaPool.State` layer view."""++ conv: list+ temporal: Any+++class AscendShortConvAttnBackend(ShortConvAttnBackend):+ """``ShortConvAttnBackend`` with the NPU conv-state layout transposed."""++ # The Ascend short-conv kernels run the whole ragged window on device; the+ # base class' host mirrors cost a device->host sync per extend step that+ # nothing on Ascend reads.+ needs_extend_host_mirrors: bool = False++ def __init__(self, model_runner):+ super().__init__(model_runner)+ # Base class derived this from the NPU pool shape, where the trailing+ # axis is ``dim``; swap the last two so consumers read ``kernel - 1``.+ self.conv_states_shape = self._canonical_conv_states_shape(+ self.conv_states_shape+ )+ self._layer_conv_views: dict[int, AscendLayerConvCache] = {}++ @staticmethod+ def _canonical_conv_states_shape(pool_shape: torch.Size) -> torch.Size:+ # (..., kernel - 1, dim) -> (..., dim, kernel - 1)+ return torch.Size((*pool_shape[:-2], pool_shape[-1], pool_shape[-2]))++ def conv_state_metadata(+ self, layer_id: int, forward_batch: ForwardBatch+ ) -> ShortConvMetadata:+ meta = super().conv_state_metadata(layer_id, forward_batch)+ pool_index = self.req_to_token_pool.mamba2_layer_index(layer_id)+ cache = self._layer_conv_views.get(pool_index)+ if cache is None:+ layer_cache = self.req_to_token_pool.mamba_pool.mamba_cache.at_layer_idx(+ pool_index+ )+ cache = AscendLayerConvCache(+ # A view, so the kernels' in-place slot writes land in the pool.+ conv=[t.transpose(-2, -1) for t in layer_cache.conv],+ temporal=layer_cache.temporal,+ )+ self._layer_conv_views[pool_index] = cache+ return ShortConvMetadata(+ layer_cache=cache,+ cache_indices=meta.cache_indices,+ query_start_loc=meta.query_start_loc,+ has_initial_state=meta.has_initial_state,+ slot_ids_cpu=meta.slot_ids_cpu,+ has_prefix_cpu=meta.has_prefix_cpu,+ )+++class AscendShortConvHybridAttnBackend(AscendHybridLinearAttnBackend):+ """Ascend hybrid wrapper that routes ``conv_state_metadata`` to the sidecar.++ Short-conv layers are never reached through the full-vs-linear+ ``forward_decode`` / ``forward_extend`` dispatch; the model calls this+ hook directly, exactly as ``ShortConvHybridAttnBackend`` does on CUDA.+ """++ def __init__(+ self,+ full_attn_backend,+ 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/layers/attention/attention_registry.py b/python/sglang/srt/layers/attention/attention_registry.pyindex 9af985d73765d55f812d40af43986ebdeb783619..b42cc8a5b052fb6a704449f01ab6a1bb1c172619 100644--- a/python/sglang/srt/layers/attention/attention_registry.py+++ b/python/sglang/srt/layers/attention/attention_registry.py@@ -436,27 +436,25 @@ 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."+ # The NPU mamba pool stores conv state dim-last, so the+ # sidecar has to hand the model canonical-layout views.+ from sglang.srt.hardware_backend.npu.attention.ascend_short_conv_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/layers/attention/mamba/causal_conv1d.py b/python/sglang/srt/layers/attention/mamba/causal_conv1d.pyindex 4601f1df533b24cfffdc262834ea5478a47e334e..8c02456fa74956f274d5fed99eec070e4508ed7e 100644--- a/python/sglang/srt/layers/attention/mamba/causal_conv1d.py+++ b/python/sglang/srt/layers/attention/mamba/causal_conv1d.py@@ -5,10 +5,16 @@ # Copyright (c) 2024, Tri Dao. # Adapted from https://github.com/Dao-AILab/causal-conv1d/blob/main/causal_conv1d/causal_conv1d_interface.py +import weakref from typing import Optional import torch +# Memoized fp32 conv taps. Keyed on ``id(weight)`` -- tensors are unhashable --+# with a weakref back to the owner so a recycled address can never hit.+_TAPS_CACHE: "dict[int, tuple[weakref.ReferenceType, torch.Tensor]]" = {}+_TAPS_CACHE_MAX = 512+ from sglang.kernels.ops.mamba.causal_conv1d_triton import ( PAD_SLOT_ID, )@@ -18,6 +24,7 @@ from sglang.kernels.ops.mamba.causal_conv1d_triton import ( from sglang.kernels.ops.mamba.causal_conv1d_triton import ( causal_conv1d_update as _causal_conv1d_update_triton, )+from sglang.srt.utils import is_npu try: from sgl_kernel import causal_conv1d_fwd@@ -28,6 +35,8 @@ try: except (ImportError, AttributeError): _HAS_SGL_KERNEL = False +_IS_NPU = is_npu()+ def _get_seq_lens_cpu(query_start_loc, x): if query_start_loc is not None:@@ -35,6 +44,294 @@ def _get_seq_lens_cpu(query_start_loc, x): return [x.shape[-1]] +# ---------------------------------------------------------------------------+# Ascend NPU path.+#+# The NPU mamba pool stores conv state as ``(slots, kernel - 1, dim)`` (dim+# last, see ``_init_npu_conv_state``), and the Ascend short-conv backends hand+# that to the model transposed into the canonical ``(slots, dim, kernel - 1)``+# layout these wrappers speak. Everything below is plain torch: no host sync,+# no per-sequence Python loop, so a chunked prefill step stays launch-bound+# only. Accumulation is fp32 with the taps applied in ascending tap order, the+# same order the CUDA/Triton kernels use.+# ---------------------------------------------------------------------------+++def _weight_taps(weight: torch.Tensor) -> torch.Tensor:+ """``(dim, width)`` weight -> fp32 ``(width, dim)`` tap vectors.++ The taps are per-layer constants, so they are memoized on the weight tensor+ itself: recomputing them cost two small launches per conv layer per step,+ which is pure overhead on the decode path where the whole conv is a handful+ of elementwise kernels.+ """+ cached = _TAPS_CACHE.get(id(weight))+ if cached is not None and cached[0]() is weight:+ return cached[1]+ taps = weight.detach().t().to(torch.float32).contiguous()+ if len(_TAPS_CACHE) >= _TAPS_CACHE_MAX:+ _TAPS_CACHE.clear()+ _TAPS_CACHE[id(weight)] = (weakref.ref(weight), taps)+ return taps+++def causal_conv1d_update_npu(+ x: torch.Tensor,+ conv_state: torch.Tensor,+ weight: torch.Tensor,+ bias: Optional[torch.Tensor] = None,+ activation: Optional[str] = None,+ cache_seqlens: Optional[torch.Tensor] = None,+ conv_state_indices: Optional[torch.Tensor] = None,+ pad_slot_id: int = PAD_SLOT_ID,+) -> torch.Tensor:+ """Depthwise causal conv over a short multi-token (or single-token) block.++ ``x``: ``(batch, dim)`` or ``(batch, dim, seqlen)``.+ ``conv_state``: ``(slots, dim, state_len)`` with ``state_len >= width - 1``.+ """+ del cache_seqlens, pad_slot_id # circular-buffer mode is unused here+ dtype = x.dtype+ squeeze = x.dim() == 2+ if squeeze:+ x = x.unsqueeze(-1)+ batch, _, seqlen = x.shape+ width = weight.shape[1]+ state_len = conv_state.shape[-1]++ indices = conv_state_indices+ if indices is None:+ indices = torch.arange(batch, device=x.device, dtype=torch.int64)+ # Padded rows carry a negative slot id; route them at slot 0 so the gathers+ # stay in bounds. Their scatter is dummy traffic on the reserved slot.+ safe = indices.to(torch.int64).clamp_(min=0)+ taps = _weight_taps(weight)++ # One window, one cast, one fused multiply-add per tap: the whole conv is+ # eight launches, which matters because Ascend elementwise kernels have a+ # ~30us floor and this runs for every conv layer on every decode step.+ window = torch.cat((conv_state[safe], x.to(conv_state.dtype)), dim=-1)+ window_f = window.to(torch.float32)+ offset = state_len - width + 1+ acc = torch.mul(+ window_f[..., offset : offset + seqlen], taps[0].view(1, -1, 1)+ )+ for k in range(1, width):+ acc = torch.addcmul(+ acc,+ window_f[..., offset + k : offset + k + seqlen],+ taps[k].view(1, -1, 1),+ )+ if bias is not None:+ acc = acc + bias.to(torch.float32).view(1, -1, 1)+ if activation in ("silu", "swish"):+ acc = torch.nn.functional.silu(acc)++ conv_state[safe] = window[..., -state_len:]+ out = acc.to(dtype)+ return out.squeeze(-1) if squeeze else out+++def causal_conv1d_fn_npu(+ x: torch.Tensor,+ weight: torch.Tensor,+ bias: Optional[torch.Tensor] = None,+ query_start_loc: Optional[torch.Tensor] = None,+ cache_indices: Optional[torch.Tensor] = None,+ has_initial_state: Optional[torch.Tensor] = None,+ conv_states: Optional[torch.Tensor] = None,+ activation: Optional[str] = None,+ pad_slot_id: int = PAD_SLOT_ID,+ **kwargs,+) -> torch.Tensor:+ """Varlen depthwise causal conv over a ragged ``(dim, total_tokens)`` block.++ ``query_start_loc``/``cache_indices``/``conv_states`` follow the CUDA+ wrapper contract; ``conv_states`` is ``(slots, dim, width - 1)`` and is+ updated in place with each sequence's trailing window.+ """+ del pad_slot_id+ if query_start_loc is None or cache_indices is None or conv_states is None:+ if x.dim() != 3:+ raise ValueError("varlen Ascend causal_conv1d_fn needs query_start_loc")+ return causal_conv1d_update_npu(+ x,+ conv_states,+ weight,+ bias=bias,+ activation=activation,+ conv_state_indices=cache_indices,+ )++ dtype = x.dtype+ dim, total = x.shape+ width = weight.shape[1]+ state_len = conv_states.shape[-1]+ device = x.device+ single_sequence = query_start_loc.shape[0] == 2++ if single_sequence:+ seq_lens = None+ else:+ # Only the multi-sequence path reads the cu-seqlens; deriving them costs+ # a handful of launches per conv layer, which is real time on Ascend.+ starts = query_start_loc[:-1].to(torch.int64)+ ends = query_start_loc[1:].to(torch.int64)+ seq_lens = ends - starts+ has_prefix = (+ has_initial_state.to(dtype)+ if has_initial_state is not None+ else torch.zeros(query_start_loc.shape[0] - 1, dtype=dtype, device=device)+ )++ safe = cache_indices.to(torch.int64).clamp_(min=0)+ taps = _weight_taps(weight)+ xf = x.to(torch.float32)++ # Sequences that resume a cached prefix seed the window from their slot;+ # the rest start from zeros (the pool state is stale for them).+ state = conv_states[safe].to(torch.float32) * has_prefix.view(-1, 1, 1)++ # Causal taps over a zero-padded copy of the flat token stream. The first+ # ``width - 1`` positions of every sequence read across the boundary and are+ # overwritten below.+ padded = torch.cat(+ (+ torch.zeros((dim, width - 1), dtype=torch.float32, device=device),+ xf,+ ),+ dim=1,+ )+ newest = width - 1+ acc = padded[:, newest : newest + total] * taps[newest].view(-1, 1)+ for lag in range(1, width):+ acc = torch.addcmul(+ acc,+ padded[:, newest - lag : newest - lag + total],+ taps[newest - lag].view(-1, 1),+ )+ if bias is not None:+ acc = acc + bias.to(torch.float32).view(-1, 1)++ if single_sequence:+ _apply_single_sequence(+ acc, xf, state, safe, conv_states, taps, width, state_len, total+ )+ else:+ # Boundary fix-ups: output ``start + m`` consumes the window's oldest+ # ``width - 1 - m`` taps from the per-slot state. Write the deeper+ # offsets first so an out-of-range write for a short sequence is+ # overwritten by the always-valid ``m == 0`` fix-up of whichever+ # sequence owns that position.+ for m in range(width - 2, -1, -1):+ pos = (starts + m).clamp_(max=total - 1)+ val = xf[:, pos] * taps[width - 1].view(-1, 1)+ for lag in range(1, width):+ if lag <= m:+ src = xf[:, (pos - lag).clamp_(min=0)]+ else:+ src = state[:, :, state_len + m - lag].t()+ val = torch.addcmul(val, src, taps[width - 1 - lag].view(-1, 1))+ acc[:, pos] = val++ # Roll each slot's window forward: column ``i`` of the new state is+ # ``z[len + i]`` of ``z = [state, seq]``, i.e. the sequence's own token+ # when long enough and otherwise the carried-over state column.+ if state_len:+ conv_states[safe] = _roll_window(+ xf, state, ends, seq_lens, state_len, total, conv_states.dtype+ )++ if activation in ("silu", "swish"):+ acc = torch.nn.functional.silu(acc)++ return acc.to(dtype)+++def _apply_single_sequence(+ acc: torch.Tensor,+ xf: torch.Tensor,+ state: torch.Tensor,+ safe: torch.Tensor,+ conv_states: torch.Tensor,+ taps: torch.Tensor,+ width: int,+ state_len: int,+ total: int,+) -> None:+ """Fix-ups + window roll for a one-sequence ragged block.++ A single sequence starts at offset 0 and ends at ``total`` -- both host+ constants -- so the gather/clamp/select machinery of the multi-sequence+ path collapses to plain slices. That is the shape every chunked-prefill+ step of a long prompt takes, and each Ascend elementwise launch costs+ ~30us, so the op count is what matters here.+ """+ bias_cols = min(width - 1, total)+ for m in range(bias_cols):+ val = xf[:, m] * taps[width - 1]+ for lag in range(1, width):+ if m - lag >= 0:+ src = xf[:, m - lag]+ else:+ src = state[:, :, state_len + m - lag].squeeze(0)+ val = torch.addcmul(val, src, taps[width - 1 - lag])+ acc[:, m] = val++ if not state_len:+ return+ cols = []+ for i in range(state_len):+ own = total - state_len + i+ cols.append(+ xf[:, own]+ if own >= 0+ else state[:, :, total + i].squeeze(0)+ )+ conv_states[safe] = torch.stack(cols, dim=-1).unsqueeze(0).to(+ conv_states.dtype+ )+++def _roll_window(+ xf: torch.Tensor,+ state: torch.Tensor,+ ends: torch.Tensor,+ seq_lens: torch.Tensor,+ state_len: int,+ total: int,+ dtype: torch.dtype,+) -> torch.Tensor:+ """Trailing ``(batch, dim, state_len)`` window of ``[state, sequence]``."""+ if state_len == 1:+ # A single-column window always takes the sequence's last token.+ return xf[:, (ends - 1).clamp_(min=0, max=total - 1)].t().unsqueeze(-1)+ last = state_len - 1+ carried = state[:, :, last]+ own_last = xf[:, (ends - 1).clamp_(min=0, max=total - 1)].t()+ if state_len == 2:+ # The common short-conv window. A one-token sequence carries its oldest+ # column over from ``state[len] == state[1]``; longer ones take their own+ # second-to-last token.+ own_prev = xf[:, (ends - 2).clamp_(min=0, max=total - 1)].t()+ col_prev = torch.where((seq_lens < 2).view(-1, 1), carried, own_prev)+ return torch.stack((col_prev, own_last), dim=-1).to(dtype)+ col_last = own_last+ new_cols = [col_prev, col_last]+ for i in range(state_len - 3, -1, -1):+ resume = seq_lens < (state_len - i)+ carried_i = state.gather(+ 2,+ (seq_lens + i)+ .clamp_(max=state_len - 1)+ .view(-1, 1, 1)+ .expand(-1, state.shape[1], 1),+ ).squeeze(-1)+ own_i = xf[:, (ends - state_len + i).clamp_(min=0, max=total - 1)].t()+ new_cols.insert(0, torch.where(resume.view(-1, 1), carried_i, own_i))+ return torch.stack(new_cols, dim=-1).to(dtype)++ def causal_conv1d_fn( x: torch.Tensor, weight: torch.Tensor,@@ -76,6 +373,19 @@ def causal_conv1d_fn( out: (batch, dim, seqlen) """+ if _IS_NPU:+ return causal_conv1d_fn_npu(+ x,+ weight,+ bias=bias,+ query_start_loc=query_start_loc,+ cache_indices=cache_indices,+ has_initial_state=has_initial_state,+ conv_states=conv_states,+ activation=activation,+ pad_slot_id=pad_slot_id,+ **kwargs,+ ) # Use Triton when: (1) sgl_kernel not available, or (2) input is # non-contiguous and seq_lens_cpu is already pre-computed by caller. # The Triton kernel accepts arbitrary strides, avoiding a .contiguous()@@ -150,6 +460,17 @@ def causal_conv1d_update( indices 0 and 3 out: (batch, dim) or (batch, dim, seqlen) """+ if _IS_NPU:+ return causal_conv1d_update_npu(+ x,+ conv_state,+ weight,+ bias=bias,+ activation=activation,+ cache_seqlens=cache_seqlens,+ conv_state_indices=conv_state_indices,+ pad_slot_id=pad_slot_id,+ ) use_triton = not _HAS_SGL_KERNEL if use_triton: return _causal_conv1d_update_triton(