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/attention/ascend_backend.py b/python/sglang/srt/hardware_backend/npu/attention/ascend_backend.pyindex 89e9de06db1cb0350cb55b83dbaffc15c100fff9..8f8cc18e05cfd0d7d5d6557213fdbdd464d05dd1 100644--- a/python/sglang/srt/hardware_backend/npu/attention/ascend_backend.py+++ b/python/sglang/srt/hardware_backend/npu/attention/ascend_backend.py@@ -333,6 +333,8 @@ class AscendAttnBackend(AttentionBackend): self.token_to_kv_pool = model_runner.token_to_kv_pool self.req_to_token = model_runner.req_to_token_pool.req_to_token self.graph_mode = False+ # Lazily-grown int32 arange backing `_decode_actual_seq_lengths_q`.+ self._actual_seq_q_buffer: Optional[torch.Tensor] = None self.use_fa = get_bool_env_var("ASCEND_USE_FA", "False") self.use_fia = get_bool_env_var("ASCEND_USE_FIA", "False") self.enable_torch_compile = get_flags().capture.enable_torch_compile@@ -427,10 +429,23 @@ class AscendAttnBackend(AttentionBackend): out_cache_loc=forward_batch.out_cache_loc, ) - def init_forward_metadata(self, forward_batch: ForwardBatch):- """Init the metadata for a forward pass."""- self.forward_metadata = ForwardMetadata()- seq_lens_max = forward_batch.seq_lens.max()+ def _seq_lens_max(self, forward_batch: ForwardBatch) -> int:+ """Max sequence length as a host int.++ Read off ``seq_lens_cpu`` (which this backend already feeds to the+ attention kernels as ``context_lens``/``actual_seq_lengths_kv``) so the+ slice bound below stays on the host. ``seq_lens.max()`` is an NPU+ reduction whose conversion to a Python int stalls the host on every+ eager step.+ """+ seq_lens_cpu = forward_batch.seq_lens_cpu+ if (+ seq_lens_cpu is not None+ and seq_lens_cpu.numel() == forward_batch.seq_lens.shape[0]+ ):+ seq_lens_max = int(seq_lens_cpu.max())+ else:+ seq_lens_max = int(forward_batch.seq_lens.max()) if forward_batch.forward_mode.is_target_verify(): seq_lens_max += self.speculative_num_draft_tokens elif (@@ -438,6 +453,27 @@ class AscendAttnBackend(AttentionBackend): and forward_batch.spec_info is not None ): seq_lens_max += self.speculative_step_id + 1+ return seq_lens_max++ def _decode_actual_seq_lengths_q(self, batch_size: int) -> torch.Tensor:+ """``[1, 2, ..., batch_size]`` as an int32 NPU tensor.++ Rebuilt from a cached arange buffer: materializing a Python list of+ ``batch_size`` ints and shipping it to the device was a per-step cost+ on every eager decode.+ """+ buffer = self._actual_seq_q_buffer+ if buffer is None or buffer.shape[0] < batch_size:+ buffer = torch.arange(+ 1, batch_size + 1, dtype=torch.int32, device=self.device+ )+ self._actual_seq_q_buffer = buffer+ return buffer[:batch_size]++ def init_forward_metadata(self, forward_batch: ForwardBatch):+ """Init the metadata for a forward pass."""+ self.forward_metadata = ForwardMetadata()+ seq_lens_max = self._seq_lens_max(forward_batch) self.forward_metadata.block_tables = ( self.req_to_token_pool.req_to_token[ forward_batch.req_pool_indices, :seq_lens_max@@ -506,10 +542,8 @@ class AscendAttnBackend(AttentionBackend): device=self.device, ) elif forward_batch.forward_mode.is_decode_or_idle():- self.forward_metadata.actual_seq_lengths_q = torch.tensor(- [1 + i for i in range(forward_batch.seq_lens.shape[0])],- dtype=torch.int32,- device=self.device,+ self.forward_metadata.actual_seq_lengths_q = (+ self._decode_actual_seq_lengths_q(forward_batch.seq_lens.shape[0]) ) if (diff --git a/python/sglang/srt/hardware_backend/npu/graph_runner/npu_cudagraph_backend.py b/python/sglang/srt/hardware_backend/npu/graph_runner/npu_cudagraph_backend.pyindex 105034c03c0fb36d35254f822b63908f5bd0a2a0..4106a9bb67c8faab55cc1334f0af7af697869a76 100644--- a/python/sglang/srt/hardware_backend/npu/graph_runner/npu_cudagraph_backend.py+++ b/python/sglang/srt/hardware_backend/npu/graph_runner/npu_cudagraph_backend.py@@ -145,7 +145,7 @@ class NPUCudaGraphBackend(BaseCudaGraphBackend): def replay_with_input_update( self, shape_key: ShapeKey,- seq_lens: Any,+ seq_lens: Any = None, attr_name: str = None, attr_type: Any = None, cpu_update_input: list = None,diff --git a/python/sglang/srt/hardware_backend/npu/graph_runner/npu_graph_runner.py b/python/sglang/srt/hardware_backend/npu/graph_runner/npu_graph_runner.pyindex b82c973bc340c072ea79877ef4a0d183bd6af32d..48c83a6476d9c694fde62872978444c33956e307 100644--- a/python/sglang/srt/hardware_backend/npu/graph_runner/npu_graph_runner.py+++ b/python/sglang/srt/hardware_backend/npu/graph_runner/npu_graph_runner.py@@ -108,6 +108,10 @@ class NPUGraphRunner(DecodeCudaGraphRunner): ) self.update_attr_name = None self.update_attr_type = None+ # Live batch the kv-length rebinding reads from; set at the top of+ # execute() so the helpers below stay parameter-light.+ self._forward_batch: Optional[ForwardBatch] = None+ self._forward_batch_seq_lens_cpu: Optional[torch.Tensor] = None self.model_runner = model_runner self._init_arch_map() self.use_fia = get_bool_env_var("ASCEND_USE_FIA", "False")@@ -175,6 +179,38 @@ class NPUGraphRunner(DecodeCudaGraphRunner): cpu_update_input=[{self.update_attr_name: seq_lens}] ) + def _padded_seq_lens_update_input(self, raw_bs: int, padded_bs: int):+ """``cpu_update_input`` payload rebinding per-request kv lengths.++ The recorded graph reads the kv lengths as host values, so every replay+ has to hand it a padded per-request vector. Building it from the+ scheduler-maintained ``seq_lens_cpu`` keeps that on the host: going+ through ``seq_lens.cpu().tolist()`` forced a device sync and three+ intermediate copies (list concat -> numpy -> tensor) per decode step.+ """+ attr_name = self._get_update_attr_name()+ seq_lens_cpu = self._current_seq_lens_cpu(raw_bs)+ if isinstance(self._get_update_attr_type(), torch.Tensor):+ if seq_lens_cpu is not None:+ padded = torch.zeros(padded_bs, dtype=torch.int32)+ padded[:raw_bs] = seq_lens_cpu+ return [{attr_name: padded}]+ seq_lens = self._padded_seq_lens_list(raw_bs, padded_bs)+ as_int32 = torch.from_numpy(np.array(seq_lens).astype(np.int32))+ return [{attr_name: as_int32}]+ return [{attr_name: self._padded_seq_lens_list(raw_bs, padded_bs)}]++ def _current_seq_lens_cpu(self, raw_bs: int):+ """Host copy of the live kv lengths, or None when only the device+ tensor is authoritative for this batch."""+ seq_lens_cpu = self._forward_batch_seq_lens_cpu+ if seq_lens_cpu is None or seq_lens_cpu.numel() != raw_bs:+ return None+ return seq_lens_cpu.to(torch.int32)++ def _padded_seq_lens_list(self, raw_bs: int, padded_bs: int):+ return self._forward_batch.seq_lens.cpu().tolist() + [0] * (padded_bs - raw_bs)+ def _cache_loc_dtype(self): return torch.int32 @@ -242,16 +278,21 @@ class NPUGraphRunner(DecodeCudaGraphRunner): if forward_batch.forward_mode.is_target_verify(): seq_lens_cpu = forward_batch.seq_lens.cpu() + self.captured_req_width seq_lens = seq_lens_cpu.tolist() + [0] * (self.bs - self.raw_bs)+ output = self.backend.replay_with_input_update(+ graph_key,+ seq_lens=seq_lens,+ attr_name=self._get_update_attr_name(),+ attr_type=self._get_update_attr_type(),+ ) else:- seq_lens = forward_batch.seq_lens.cpu().tolist() + [0] * (- self.bs - self.raw_bs+ self._forward_batch = forward_batch+ self._forward_batch_seq_lens_cpu = forward_batch.seq_lens_cpu+ output = self.backend.replay_with_input_update(+ graph_key,+ cpu_update_input=self._padded_seq_lens_update_input(+ self.raw_bs, self.bs+ ), )- output = self.backend.replay_with_input_update(- graph_key,- seq_lens=seq_lens,- attr_name=self._get_update_attr_name(),- attr_type=self._get_update_attr_type(),- ) else: output = self.backend.replay(graph_key, forward_batch) diff --git a/python/sglang/srt/models/qwen3.py b/python/sglang/srt/models/qwen3.pyindex 9fbd046709e6d2d557b005f22d8b8586727fcec4..5cfe4e21d6c0e3816be30304380cf65ae6882732 100644--- a/python/sglang/srt/models/qwen3.py+++ b/python/sglang/srt/models/qwen3.py@@ -42,6 +42,19 @@ logger = logging.getLogger(__name__) _is_cuda = is_cuda() _is_hip = is_hip() _is_npu = is_npu()+++def _exec_graph_config_published() -> bool:+ """True once the runtime exec context (and its graph config) is live.++ ``Qwen3DecoderLayer`` caches its CMO prefetch decision on the first forward+ that can actually consult the published config; this predicate is what+ makes "not yet published" distinguishable from "published and disabled".+ """+ try:+ return get_exec().graph.cuda_graph_config is not None+ except ValueError:+ return False _use_aiter = get_bool_env_var("SGLANG_USE_AITER") and _is_hip _has_fused_qk_norm_mrope = False@@ -384,6 +397,27 @@ class Qwen3DecoderLayer(nn.Module): input_layernorm=self.input_layernorm, post_attention_layernorm=self.post_attention_layernorm, )+ # Per-layer MLP weight pair handed to the CMO prefetcher. Resolved on+ # the first forward (the graph config is published by then) and cached:+ # re-deriving it queried the runtime config twice per layer per step.+ self._npu_mlp_prefetch_cache: Optional[+ List[torch.Tensor]+ ] = None+ self._npu_mlp_prefetch_cache_resolved = False++ def _resolve_npu_mlp_prefetch_cache(self) -> Optional[List[torch.Tensor]]:+ """MLP weight pair for the NPU CMO prefetcher, or None when the+ prefetcher is off (no prefill piecewise graph / missing weights)."""+ if not _is_npu:+ return None+ if not (+ hasattr(self.mlp.gate_up_proj, "weight")+ and hasattr(self.mlp.down_proj, "weight")+ ):+ return None+ if not check_cuda_graph_backend(Phase.PREFILL, Backend.TC_PIECEWISE):+ return None+ return [self.mlp.gate_up_proj.weight, self.mlp.down_proj.weight] def forward( self,@@ -408,20 +442,16 @@ class Qwen3DecoderLayer(nn.Module): ) # Fully Connected+ if not self._npu_mlp_prefetch_cache_resolved:+ self._npu_mlp_prefetch_cache = self._resolve_npu_mlp_prefetch_cache()+ # Keep re-resolving until the runtime config is published, so an+ # early warmup forward cannot pin the answer to "unpublished".+ self._npu_mlp_prefetch_cache_resolved = _exec_graph_config_published() hidden_states, residual = self.layer_communicator.prepare_mlp( hidden_states, residual, forward_batch,- cache=(- [self.mlp.gate_up_proj.weight, self.mlp.down_proj.weight]- if _is_npu- and check_cuda_graph_backend(Phase.PREFILL, Backend.TC_PIECEWISE)- and (- hasattr(self.mlp.gate_up_proj, "weight")- and hasattr(self.mlp.down_proj, "weight")- )- else None- ),+ cache=self._npu_mlp_prefetch_cache, ) hidden_states = self.mlp(hidden_states, forward_batch=forward_batch) if _is_npu and get_cmo_stream():