Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
sglang · 2 changed files
Base commit: 340db9201005fc64635bb25db1d2538f955761c3
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..e7d4b07d745b080b965750a93bc0ccda8d7e1bde 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@@ -15,7 +15,7 @@ from __future__ import annotations import threading from contextlib import AbstractContextManager, contextmanager from functools import partial-from typing import TYPE_CHECKING, Any, Callable, Dict, Optional+from typing import TYPE_CHECKING, Any, Callable, Dict, KeysView, Optional import numpy as np import torch@@ -129,6 +129,11 @@ class NPUCudaGraphBackend(BaseCudaGraphBackend): def can_run(self, forward_batch: ForwardBatch, shape_key: ShapeKey) -> bool: return shape_key in self._graphs + @property+ def graph_keys(self) -> KeysView[Any]:+ """Captured shape keys, for callers that plan replays ahead of time."""+ return self._graphs.keys()+ @contextmanager def replay_session(self): yielddiff --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..cd25a06bda98544cad7cdbe2fb2ffefa2e485d59 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@@ -22,15 +22,19 @@ capture/replay mechanics live in the backend. This class adds: - Replay override that issues an async NPUGraph.update for seq_lens before replay (skipped for deepseek-nsa). - Smaller cache_loc dtype (int32 instead of int64).+ - Oversized-batch chunked replay: a decode batch wider than the+ largest captured bucket is served by several graph replays+ instead of falling back to a much slower eager forward. """ from __future__ import annotations +import copy import logging import os from contextlib import contextmanager from pathlib import Path-from typing import TYPE_CHECKING, Dict, Optional, Union+from typing import TYPE_CHECKING, Dict, Optional, Sequence, Tuple, Union import numpy as np import torch@@ -109,6 +113,7 @@ class NPUGraphRunner(DecodeCudaGraphRunner): self.update_attr_name = None self.update_attr_type = None self.model_runner = model_runner+ self._chunked_logits: Optional[torch.Tensor] = None self._init_arch_map() self.use_fia = get_bool_env_var("ASCEND_USE_FIA", "False") self.if_use_v2 = any(@@ -178,6 +183,139 @@ class NPUGraphRunner(DecodeCudaGraphRunner): def _cache_loc_dtype(self): return torch.int32 + # ------------------------------------------------------------------+ # Oversized-batch chunked decode replay+ # ------------------------------------------------------------------+ # A decode batch wider than the largest captured bucket normally falls+ # back to the eager runner, which on NPU costs an order of magnitude+ # more host time per step than a graph replay. Serving such a batch as+ # several bucket-sized replays keeps every request advancing one token+ # per step while staying on the captured graphs. This is a pure graph+ # *execution* strategy: capture, bucket selection and the configured+ # decode max_bs are all left exactly as the user asked for them.++ def _chunked_decode_supported(self) -> bool:+ """Chunked replay is only wired for the plain single-width decode+ path; every feature that keys graphs by something other than the+ request count (speculation, TBO, PDMux, LoRA variants, DP gather)+ opts out."""+ return (+ not self.disable_padding+ and not self.enable_two_batch_overlap+ and not self.is_encoder_decoder+ and not self.is_dllm+ and not self.ragged_verify_mode+ and not self.enable_pdmux+ and not self.require_mlp_sync+ and not self.require_gathered_buffer+ and not self.model_runner.server_args.enable_lora+ and self.model_runner.spec_algorithm.is_none()+ )++ def decode_chunk_plan(+ self, forward_batch: ForwardBatch+ ) -> Optional[Sequence[Tuple[int, int]]]:+ """Row ranges [start, end) of the bucket-sized replays, or None when+ the batch is not an oversized plain decode batch."""+ if not self._chunked_decode_supported():+ return None+ if not forward_batch.forward_mode.is_decode():+ return None+ if forward_batch.replace_embeds is not None:+ return None+ if forward_batch.spec_info is not None:+ return None+ if forward_batch.capture_hidden_mode.need_capture():+ # The chunked path returns logits only; it would silently drop+ # the hidden states the caller asked for.+ return None+ bs = forward_batch.batch_size+ if bs <= self.max_bs:+ # Within the captured range: the ordinary single-replay path+ # already owns it, and anything it rejected was rejected for a+ # reason that applies to the chunks too.+ return None+ if self._make_graph_key(self.max_bs) not in self.backend.graph_keys:+ return None+ step = self.max_bs+ return [(start, min(start + step, bs)) for start in range(0, bs, step)]++ def can_run_graph(self, forward_batch: ForwardBatch):+ return super().can_run_graph(forward_batch) or (+ self.decode_chunk_plan(forward_batch) is not None+ )++ def _chunk_view(+ self, forward_batch: ForwardBatch, start: int, end: int, seq_lens_sum: int+ ) -> ForwardBatch:+ """A row-sliced view of `forward_batch` covering requests+ [start, end); `load_batch` reads only the per-row fields below."""+ chunk = copy.copy(forward_batch)+ chunk.batch_size = end - start+ chunk.seq_lens_sum = seq_lens_sum+ # Each chunk needs its own attention-metadata plan at its own width;+ # a plan recorded for the whole batch must not be reused.+ chunk.forward_metadata_ready = False+ for name in (+ "input_ids",+ "positions",+ "out_cache_loc",+ "req_pool_indices",+ "seq_lens",+ "seq_lens_cpu",+ "rids_int",+ "bootstrap_room_ids_int",+ ):+ value = getattr(forward_batch, name)+ if value is not None:+ setattr(chunk, name, value[start:end])+ chunk.encoder_lens = None+ chunk.mrope_positions = None+ chunk.input_embeds = None+ chunk.spec_info = None+ return chunk++ def _chunked_logits_buffer(self, bs: int) -> torch.Tensor:+ """One grow-only buffer, sliced to the live batch. Keying it by batch+ size instead would hold a separate [bs, vocab] tensor for every width+ the decode batch drains through."""+ buffer = self._chunked_logits+ if buffer is None or buffer.shape[0] < bs:+ buffer = torch.empty(+ (bs, self.model_runner.model_config.vocab_size),+ dtype=self.model_runner.model_config.dtype,+ device=self.device,+ )+ self._chunked_logits = buffer+ return buffer[:bs]++ def _execute_chunked(+ self,+ forward_batch: ForwardBatch,+ plan: Sequence[Tuple[int, int]],+ ) -> LogitsProcessorOutput:+ seq_lens = forward_batch.seq_lens.cpu().tolist()+ logits = self._chunked_logits_buffer(forward_batch.batch_size)+ for start, end in plan:+ width = end - start+ chunk = self._chunk_view(+ forward_batch, start, end, sum(seq_lens[start:end])+ )+ self.load_batch(chunk)+ padded = seq_lens[start:end] + [0] * (self.bs - width)+ output = self.backend.replay_with_input_update(+ self._make_graph_key(self.bs),+ seq_lens=padded,+ attr_name=self._get_update_attr_name(),+ attr_type=self._get_update_attr_type(),+ )+ # Copy out before the next replay overwrites the shared+ # per-graph logits buffer.+ logits[start:end].copy_(+ output.next_token_logits[:width].to(logits.dtype)+ )+ return LogitsProcessorOutput(next_token_logits=logits)+ def _init_profile_context_and_memory_record(self): output_dir = os.path.join( os.getenv("SGLANG_TORCH_PROFILER_DIR", "/tmp"), "graph_capture_profile"@@ -211,6 +349,9 @@ class NPUGraphRunner(DecodeCudaGraphRunner): forward_batch: ForwardBatch, pp_proxy_tensors: Optional[PPProxyTensors] = None, ) -> Union[LogitsProcessorOutput, PPProxyTensors]:+ plan = self.decode_chunk_plan(forward_batch)+ if plan is not None:+ return self._execute_chunked(forward_batch, plan) if forward_batch.needs_forward_metadata_init(): self.load_batch(forward_batch, pp_proxy_tensors) else: