Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
sglang · 1 changed files
Base commit: 340db9201005fc64635bb25db1d2538f955761c3
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..5dc7ff1febea2038453288b8d17d268ab3257333 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@@ -21,6 +21,8 @@ capture/replay mechanics live in the backend. This class adds: - Profile context override (NPU profiler emits to disk, not in-mem). - Replay override that issues an async NPUGraph.update for seq_lens before replay (skipped for deepseek-nsa).+ - Chunked replay for feature-free decode batches larger than the+ configured maximum graph shape. - Smaller cache_loc dtype (int32 instead of int64). """ @@ -29,6 +31,7 @@ from __future__ import annotations import logging import os from contextlib import contextmanager+from dataclasses import replace from pathlib import Path from typing import TYPE_CHECKING, Dict, Optional, Union @@ -58,6 +61,8 @@ if is_npu: logger = logging.getLogger(__name__) +_MAX_CHUNKED_DECODE_GRAPH_REPLAYS = 4+ if TYPE_CHECKING: from sglang.srt.model_executor.model_runner import ModelRunner @@ -116,6 +121,7 @@ class NPUGraphRunner(DecodeCudaGraphRunner): in ("MiMoV2ForCausalLM", "MiMoV2FlashForCausalLM", "Step3p5ForCausalLM") for arch in (model_runner.model_config.hf_config.architectures or []) )+ self._chunked_logits_buffer = None def _init_arch_map(self): if self.is_dllm:@@ -206,10 +212,195 @@ class NPUGraphRunner(DecodeCudaGraphRunner): # for NPU, profile data will be saved to disk for further analysis. pass + def can_run_graph(self, forward_batch: ForwardBatch):+ if super().can_run_graph(forward_batch):+ return True+ return self._can_run_chunked_decode_graph(forward_batch)++ def _can_run_chunked_decode_graph(self, forward_batch: ForwardBatch) -> bool:+ """Whether a large plain-decode batch can use several graph replays.++ NPU graph capture is comparatively expensive, so deployments commonly+ capture a conservative maximum batch size. A larger decode batch used+ to fall back to eager execution even though requests in a plain decode+ step are independent. Keep the configured capture limit intact and+ replay the captured graph over request chunks instead.++ Start with the deliberately narrow, feature-free case. More involved+ modes carry cross-request metadata whose slicing needs a mode-specific+ implementation and must continue to use the eager fallback.+ """+ return (+ forward_batch.batch_size > self.max_bs+ and forward_batch.batch_size+ <= self.max_bs * _MAX_CHUNKED_DECODE_GRAPH_REPLAYS+ and forward_batch.forward_mode.is_decode()+ and self.captured_req_width == 1+ and self.model_runner.spec_algorithm.is_none()+ and self.dp_size == 1+ and self.pp_size == 1+ and not self.require_mlp_sync+ and not self.enable_two_batch_overlap+ and not self.enable_pdmux+ and not self.is_encoder_decoder+ and not self.is_dllm+ and not self.model_runner.server_args.enable_lora+ and not self.use_ngram_embedding+ and not forward_batch.return_logprob+ and not forward_batch.return_hidden_states_before_norm+ and (+ forward_batch.capture_hidden_mode is None+ or not forward_batch.capture_hidden_mode.need_capture()+ )+ and forward_batch.input_ids is not None+ and forward_batch.input_ids.numel() == forward_batch.batch_size+ and forward_batch.req_pool_indices is not None+ and forward_batch.req_pool_indices.numel() == forward_batch.batch_size+ and forward_batch.seq_lens is not None+ and forward_batch.seq_lens.numel() == forward_batch.batch_size+ and forward_batch.out_cache_loc is not None+ and forward_batch.out_cache_loc.numel() == forward_batch.batch_size+ and forward_batch.positions is not None+ and forward_batch.positions.numel() == forward_batch.batch_size+ and forward_batch.seq_lens_cpu is not None+ and len(forward_batch.seq_lens_cpu) == forward_batch.batch_size+ and forward_batch.out_cache_loc_dsv4 is None+ and forward_batch.input_embeds is None+ and forward_batch.replace_embeds is None+ and forward_batch.replace_positions is None+ and forward_batch.token_type_ids is None+ and (+ not forward_batch.mm_inputs+ or all(item is None for item in forward_batch.mm_inputs)+ )+ and forward_batch.mm_input_embeds is None+ and forward_batch.mrope_positions is None+ and forward_batch.mamba_track_indices is None+ and forward_batch.mamba_track_mask is None+ and forward_batch.mamba_track_seqlens is None+ and forward_batch.mamba_cow_src_indices is None+ and forward_batch.mamba_cow_dst_indices is None+ and forward_batch.mamba_clear_indices is None+ and forward_batch.attn_cp_metadata is None+ and forward_batch.attn_dcp_metadata is None+ and forward_batch.dcp_kv_mask is None+ and forward_batch.req_all_ids_flat is None+ and forward_batch.req_all_ids_lens is None+ and forward_batch.rids_int is None+ and forward_batch.bootstrap_room_ids_int is None+ and forward_batch.cross_attention_custom_mask is None+ and forward_batch.minimax_m3_precached_sparse_layers is None+ and (+ forward_batch.sampling_info is None+ or getattr(forward_batch.sampling_info, "grammars", None) is None+ )+ and not forward_batch.forward_metadata_ready+ )++ @staticmethod+ def _slice_optional_tensor(value, start: int, end: int):+ return None if value is None else value[start:end]++ @staticmethod+ def _slice_optional_list(value, start: int, end: int):+ return None if value is None else value[start:end]++ def _slice_plain_decode_batch(+ self, forward_batch: ForwardBatch, start: int, end: int+ ) -> ForwardBatch:+ seq_lens_cpu = forward_batch.seq_lens_cpu[start:end]+ return replace(+ forward_batch,+ batch_size=end - start,+ input_ids=forward_batch.input_ids[start:end],+ req_pool_indices=forward_batch.req_pool_indices[start:end],+ seq_lens=forward_batch.seq_lens[start:end],+ out_cache_loc=forward_batch.out_cache_loc[start:end],+ seq_lens_sum=int(seq_lens_cpu.sum()),+ seq_lens_cpu=seq_lens_cpu,+ orig_seq_lens=self._slice_optional_tensor(+ forward_batch.orig_seq_lens, start, end+ ),+ positions=forward_batch.positions[start:end],+ mm_inputs=self._slice_optional_list(forward_batch.mm_inputs, start, end),+ lora_ids=self._slice_optional_list(forward_batch.lora_ids, start, end),+ rids=self._slice_optional_list(forward_batch.rids, start, end),+ )++ def _copy_chunk_output(+ self,+ buffer_name: str,+ source: Optional[torch.Tensor],+ start: int,+ end: int,+ total: int,+ ) -> Optional[torch.Tensor]:+ if source is None:+ return None++ buffer = getattr(self, buffer_name)+ required_shape = (total, *source.shape[1:])+ if (+ buffer is None+ or buffer.shape[0] < total+ or buffer.shape[1:] != source.shape[1:]+ or buffer.dtype != source.dtype+ or buffer.device != source.device+ ):+ buffer = torch.empty(+ required_shape, dtype=source.dtype, device=source.device+ )+ setattr(self, buffer_name, buffer)+ buffer[start:end].copy_(source)+ return buffer[:total]++ def _execute_chunked_decode(+ self, forward_batch: ForwardBatch+ ) -> LogitsProcessorOutput:+ total = forward_batch.batch_size+ combined_logits = None++ for start in range(0, total, self.max_bs):+ end = min(start + self.max_bs, total)+ chunk = self._slice_plain_decode_batch(forward_batch, start, end)+ output = self._execute_one(chunk)+ if not isinstance(output, LogitsProcessorOutput):+ raise RuntimeError(+ "Plain decode graph replay unexpectedly returned pipeline tensors"+ )+ combined_logits = self._copy_chunk_output(+ "_chunked_logits_buffer",+ output.next_token_logits,+ start,+ end,+ total,+ )+ if output.hidden_states is not None:+ raise RuntimeError(+ "Plain decode graph replay unexpectedly returned hidden states"+ )++ return LogitsProcessorOutput(next_token_logits=combined_logits)+ def execute( self, forward_batch: ForwardBatch, pp_proxy_tensors: Optional[PPProxyTensors] = None,+ ) -> Union[LogitsProcessorOutput, PPProxyTensors]:+ if forward_batch.batch_size > self.max_bs:+ if pp_proxy_tensors is not None or not self._can_run_chunked_decode_graph(+ forward_batch+ ):+ raise RuntimeError(+ "An unsupported oversized batch reached the NPU graph runner"+ )+ return self._execute_chunked_decode(forward_batch)+ return self._execute_one(forward_batch, pp_proxy_tensors)++ def _execute_one(+ self,+ forward_batch: ForwardBatch,+ pp_proxy_tensors: Optional[PPProxyTensors] = None, ) -> Union[LogitsProcessorOutput, PPProxyTensors]: if forward_batch.needs_forward_metadata_init(): self.load_batch(forward_batch, pp_proxy_tensors)