Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
sglang · 9 changed files
Base commit: 340db9201005fc64635bb25db1d2538f955761c3
diff --git a/python/sglang/srt/environ.py b/python/sglang/srt/environ.pyindex 81cbfc18ddf28f9cf3d458c4f141f9ec1c9ac66a..049f59c90fff0997c235178e8855e91043deb59a 100644--- a/python/sglang/srt/environ.py+++ b/python/sglang/srt/environ.py@@ -631,6 +631,8 @@ class Envs: SGLANG_MLX_CLEAR_CACHE_STEPS = EnvInt(256) # NPU+ # Seconds to coalesce singleton eager prefills while decode is busy; 0 disables.+ SGLANG_NPU_PREFILL_COALESCE_MAX_DELAY = EnvFloat(0.08) SGLANG_NPU_DISABLE_ACL_FORMAT_WEIGHT = EnvBool(False) SGLANG_NPU_USE_MULTI_STREAM = EnvBool(False) SGLANG_NPU_USE_MLAPO = EnvBool(False)diff --git a/python/sglang/srt/hardware_backend/npu/allocator_npu.py b/python/sglang/srt/hardware_backend/npu/allocator_npu.pyindex 1a6ce9e6e4f73d1f004ed8ba6f109f9b19bb5dbf..c570cc819656a7676fb1804a4ad59691eed9b4da 100644--- a/python/sglang/srt/hardware_backend/npu/allocator_npu.py+++ b/python/sglang/srt/hardware_backend/npu/allocator_npu.py@@ -120,12 +120,12 @@ class NPUPagedTokenToKVPoolAllocator(PagedTokenToKVPoolAllocator): if num_new_pages > len(self.free_pages): return None - need_new_pages = (seq_lens % self.page_size == 1).int()- end_new_pages = torch.cumsum(need_new_pages, 0)- start_new_pages = end_new_pages - need_new_pages if num_new_pages == 0: out_indices = last_loc + 1 else:+ need_new_pages = (seq_lens % self.page_size == 1).int()+ end_new_pages = torch.cumsum(need_new_pages, 0)+ start_new_pages = end_new_pages - need_new_pages out_indices = (last_loc + 1) * (1 - need_new_pages) + self.free_pages[ start_new_pages ] * self.page_size * need_new_pagesdiff --git a/python/sglang/srt/hardware_backend/npu/attention/ascend_backend.py b/python/sglang/srt/hardware_backend/npu/attention/ascend_backend.pyindex 89e9de06db1cb0350cb55b83dbaffc15c100fff9..39ff13c4e6a5e782fd0106bba1a222578e109071 100644--- a/python/sglang/srt/hardware_backend/npu/attention/ascend_backend.py+++ b/python/sglang/srt/hardware_backend/npu/attention/ascend_backend.py@@ -430,7 +430,11 @@ class AscendAttnBackend(AttentionBackend): 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()+ seq_lens_max = (+ forward_batch.seq_lens_cpu.max().item()+ if forward_batch.seq_lens_cpu is not None and forward_batch.spec_info is None+ else forward_batch.seq_lens.max().item()+ ) if forward_batch.forward_mode.is_target_verify(): seq_lens_max += self.speculative_num_draft_tokens elif (@@ -459,8 +463,19 @@ class AscendAttnBackend(AttentionBackend): ) if forward_batch.extend_seq_lens is not None: self.forward_metadata.extend_seq_lens = forward_batch.extend_seq_lens+ # DP padding and speculative workers can change the device lengths+ # independently of the scheduler's original CPU list. self.forward_metadata.extend_seq_lens_cpu_int = (- forward_batch.extend_seq_lens.cpu().int()+ torch.tensor(+ forward_batch.extend_seq_lens_cpu,+ dtype=torch.int32,+ device="cpu",+ )+ if forward_batch.extend_seq_lens_cpu is not None+ and forward_batch.spec_info is None+ and len(forward_batch.extend_seq_lens_cpu)+ == forward_batch.extend_seq_lens.numel()+ else forward_batch.extend_seq_lens.cpu().int() ) if forward_batch.seq_lens is not None: self.forward_metadata.seq_lens = forward_batch.seq_lens.int()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..ea05cbd11ae6295e455b6c84461dc1eb23e16444 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@@ -12,7 +12,7 @@ non-NPU hosts. from __future__ import annotations -import threading+from concurrent.futures import ThreadPoolExecutor from contextlib import AbstractContextManager, contextmanager from functools import partial from typing import TYPE_CHECKING, Any, Callable, Dict, Optional@@ -63,6 +63,7 @@ class NPUCudaGraphBackend(BaseCudaGraphBackend): self._enable_torch_compile = getattr( cuda_graph_runner, "enable_torch_compile", False )+ self._update_executor: Optional[ThreadPoolExecutor] = None @contextmanager def capture_session(self, stream):@@ -150,8 +151,8 @@ class NPUCudaGraphBackend(BaseCudaGraphBackend): attr_type: Any = None, cpu_update_input: list = None, ) -> Any:- """Rebind seq_lens on the recorded NPU graph in a background- thread, then replay. Used when the model is not deepseek-nsa.+ """Rebind seq_lens on the recorded NPU graph in a persistent+ worker while replaying. Used when the model is not deepseek-nsa. Two calling conventions: 1. (legacy) seq_lens + attr_name + attr_type:@@ -166,17 +167,31 @@ class NPUCudaGraphBackend(BaseCudaGraphBackend): graph = self._graphs[shape_key] - def _update():- self._device_module.set_device(self._device_id)- graph.update(cpu_update_input=cpu_update_input)-- thread = threading.Thread(target=_update)- thread.start()- graph.replay()- thread.join()+ # update and replay must overlap: captured attention waits on external+ # events recorded by update. Reuse one worker (and its device context)+ # instead of creating a thread on every generated token.+ if self._update_executor is None:+ self._update_executor = ThreadPoolExecutor(+ max_workers=1,+ thread_name_prefix="npu-graph-update",+ initializer=self._device_module.set_device,+ initargs=(self._device_id,),+ )+ update = self._update_executor.submit(+ graph.update, cpu_update_input=cpu_update_input+ )+ try:+ graph.replay()+ finally:+ # Finish the update before any captured buffers can be reused, and+ # propagate worker failures to the scheduler.+ update.result() return self._outputs[shape_key] def cleanup(self) -> None:+ if self._update_executor is not None:+ self._update_executor.shutdown(wait=True)+ self._update_executor = None self._graphs.clear() self._outputs.clear() self._pool = Nonediff --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..1c12a1f09cea8debe286dfd979c49be53ea16d34 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@@ -243,9 +243,19 @@ class NPUGraphRunner(DecodeCudaGraphRunner): seq_lens_cpu = forward_batch.seq_lens.cpu() + self.captured_req_width seq_lens = seq_lens_cpu.tolist() + [0] * (self.bs - self.raw_bs) else:- seq_lens = forward_batch.seq_lens.cpu().tolist() + [0] * (- self.bs - self.raw_bs- )+ # Ordinary decode maintains an immutable CPU mirror for each+ # scheduled batch. Reading it avoids synchronizing the forward+ # stream just to recover lengths already known by the scheduler.+ # Speculative workers may advance device lengths independently.+ if (+ forward_batch.forward_mode.is_decode_or_idle()+ and forward_batch.spec_info is None+ and forward_batch.seq_lens_cpu is not None+ ):+ seq_lens_cpu = forward_batch.seq_lens_cpu+ else:+ seq_lens_cpu = forward_batch.seq_lens.cpu()+ 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,diff --git a/python/sglang/srt/hardware_backend/npu/prefill_coalescer.py b/python/sglang/srt/hardware_backend/npu/prefill_coalescer.pynew file mode 100644index 0000000000000000000000000000000000000000..e7768e04c7fcd14e5814c618e5abfa8eace7a12b--- /dev/null+++ b/python/sglang/srt/hardware_backend/npu/prefill_coalescer.py@@ -0,0 +1,93 @@+"""Bounded coalescing of eager prefills while an NPU decode graph is busy."""++import math+import time+from typing import TYPE_CHECKING, Optional++if TYPE_CHECKING:+ from sglang.srt.managers.scheduler import Scheduler+++class NPUPrefillCoalescer:+ """Amortize eager launch overhead without waiting on an idle device.++ A singleton prefill can interrupt every active decoder for many operator+ launches. Allow another arrival to join it while useful decode work runs.+ The wait is at most twice the observed prefill launch time, subject to a+ fixed wall-clock ceiling. A ready batch of two is dispatched immediately.+ """++ def __init__(self, max_delay_s: float):+ if not math.isfinite(max_delay_s) or max_delay_s < 0:+ raise ValueError(+ "NPU prefill coalescing delay must be finite and nonnegative"+ )+ self.max_delay_s = max_delay_s+ self._prefill_cost: Optional[float] = None+ self._waiting_req = None+ self._deadline = 0.0++ @classmethod+ def from_scheduler(cls, scheduler: "Scheduler") -> Optional["NPUPrefillCoalescer"]:+ from sglang.srt.environ import envs+ from sglang.srt.model_executor.cuda_graph_config import Backend++ args = scheduler.server_args+ max_delay_s = envs.SGLANG_NPU_PREFILL_COALESCE_MAX_DELAY.get()+ # Distributed ranks need a negotiated decision. Explicit delayers,+ # mixed chunks and speculative workers already own their scheduling.+ if (+ max_delay_s == 0+ or not scheduler.enable_overlap+ or not scheduler.is_generation+ or scheduler.dllm_config is not None+ or scheduler.ps.tp_size != 1+ or scheduler.ps.dp_size != 1+ or scheduler.ps.pp_size != 1+ or not scheduler.spec_algorithm.is_none()+ or scheduler.is_mixed_chunk+ or scheduler.prefill_delayer is not None+ or scheduler.min_free_slots_delayer is not None+ or args.enable_priority_scheduling+ or args.schedule_policy != "fcfs"+ or args.disaggregation_mode != "null"+ or args.cuda_graph_config.decode.backend != Backend.FULL+ or args.cuda_graph_config.prefill.backend != Backend.DISABLED+ ):+ return None+ return cls(max_delay_s)++ def observe_prefill(self, duration_s: float) -> None:+ if not math.isfinite(duration_s) or duration_s < 0:+ return+ # Clip cold-start compilation outliers before updating the estimate.+ duration_s = min(duration_s, self.max_delay_s)+ if self._prefill_cost is None:+ self._prefill_cost = duration_s+ else:+ self._prefill_cost += 0.125 * (duration_s - self._prefill_cost)++ def should_delay(+ self,+ *,+ running_bs: int,+ waiting_queue: list,+ has_chunked_req: bool,+ ) -> bool:+ if (+ running_bs < 2+ or len(waiting_queue) != 1+ or has_chunked_req+ or self._prefill_cost is None+ ):+ self._waiting_req = None+ return False++ now = time.perf_counter()+ req = waiting_queue[0]+ if req is not self._waiting_req:+ self._waiting_req = req+ self._deadline = now + min(self.max_delay_s, 2 * self._prefill_cost)+ # Keep an expired deadline until this request is admitted or leaves the+ # queue. Memory pressure must not restart its wait on every attempt.+ return now < self._deadlinediff --git a/python/sglang/srt/managers/scheduler.py b/python/sglang/srt/managers/scheduler.pyindex a9615a14c512345b2d63323ff3ebd2fe3d9a0dca..dd776252b28740edbf44a857b48daa2cbf0566c5 100644--- a/python/sglang/srt/managers/scheduler.py+++ b/python/sglang/srt/managers/scheduler.py@@ -1228,6 +1228,19 @@ class Scheduler( self.server_args ) + self.npu_prefill_coalescer = None+ if _is_npu:+ from sglang.srt.hardware_backend.npu.prefill_coalescer import (+ NPUPrefillCoalescer,+ )++ self.npu_prefill_coalescer = NPUPrefillCoalescer.from_scheduler(self)+ if self.npu_prefill_coalescer is not None:+ logger.info(+ "NPU eager prefill coalescing enabled (maximum delay %.0f ms).",+ self.npu_prefill_coalescer.max_delay_s * 1000,+ )+ def init_soft_watchdog(self, server_args: ServerArgs): if (x := server_args.soft_watchdog_timeout) is not None: self.soft_watchdog = create_scheduler_watchdog(@@ -1760,7 +1773,15 @@ class Scheduler( # Launch the current batch if batch:+ coalescer = self.npu_prefill_coalescer+ prefill_start = (+ time.perf_counter()+ if coalescer is not None and batch.forward_mode.is_extend()+ else None+ ) batch_result = self.run_batch(batch)+ if prefill_start is not None:+ coalescer.observe_prefill(time.perf_counter() - prefill_start) # Fence result processing behind this forward's shared reads. self._apply_war_barrier() self.result_queue.append((batch.copy(), batch_result))@@ -3065,6 +3086,18 @@ class Scheduler( return res def get_new_batch_prefill(self, running_batch: ScheduleBatch) -> NextBatchPlan:+ if (+ self.npu_prefill_coalescer is not None+ and self.npu_prefill_coalescer.should_delay(+ running_bs=(+ 0 if running_batch.is_prefill_only else len(running_batch.reqs)+ ),+ waiting_queue=self.waiting_queue,+ has_chunked_req=self.chunked_req is not None,+ )+ ):+ return NextBatchPlan(batch_to_run=None, running_batch=running_batch)+ prefill_delayer_single_pass = None if self.prefill_delayer: # Decay the max-prefill-bs high-watermark once per pass so onediff --git a/python/sglang/test/ascend/test_npu_decode_metadata.py b/python/sglang/test/ascend/test_npu_decode_metadata.pynew file mode 100644index 0000000000000000000000000000000000000000..94e6e4d7feb9a518cddc4f743d36963f1ced2e0e--- /dev/null+++ b/python/sglang/test/ascend/test_npu_decode_metadata.py@@ -0,0 +1,220 @@+"""CPU tests for NPU decode metadata and graph-update coordination."""++import threading+import unittest+from types import SimpleNamespace+from unittest.mock import Mock, patch++import torch++from sglang.srt.hardware_backend.npu.allocator_npu import (+ NPUPagedTokenToKVPoolAllocator,+)+from sglang.srt.hardware_backend.npu.attention.ascend_backend import AscendAttnBackend+from sglang.srt.hardware_backend.npu.graph_runner.npu_cudagraph_backend import (+ NPUCudaGraphBackend,+)+from sglang.srt.hardware_backend.npu.graph_runner.npu_graph_runner import NPUGraphRunner+from sglang.srt.layers.logits_processor import LogitsProcessorOutput+from sglang.srt.model_executor.forward_batch_info import ForwardMode+++class TestNPUDecodeLengths(unittest.TestCase):+ def setUp(self):+ self.runner = object.__new__(NPUGraphRunner)+ self.runner.model_runner = SimpleNamespace(+ model_config=SimpleNamespace(+ hf_config=SimpleNamespace(architectures=["Qwen3ForCausalLM"])+ )+ )+ self.runner.bs = 4+ self.runner.raw_bs = self.runner.raw_num_token = 3+ self.runner.captured_req_width = 1+ self.runner.is_dllm = False+ self.runner.load_batch = Mock()+ self.runner._make_graph_key = Mock(return_value=4)+ self.runner._get_update_attr_name = Mock(return_value="actual_seq_lengths_kv")+ self.runner._get_update_attr_type = Mock(return_value=[])+ self.runner.backend = Mock()+ self.runner.backend.replay_with_input_update.return_value = (+ LogitsProcessorOutput(next_token_logits=torch.zeros(4, 8))+ )+ self.batch = SimpleNamespace(+ needs_forward_metadata_init=lambda: True,+ forward_mode=ForwardMode.DECODE,+ seq_lens_cpu=torch.tensor([17, 129, 257]),+ seq_lens=Mock(),+ spec_info=None,+ )+ self.batch.seq_lens.cpu.side_effect = AssertionError("unexpected device copy")++ def test_decode_uses_cpu_mirror_and_pads_inactive_requests(self):+ out = self.runner.execute(self.batch)+ self.assertEqual(out.next_token_logits.shape, (3, 8))+ self.assertEqual(+ self.runner.backend.replay_with_input_update.call_args.kwargs["seq_lens"],+ [17, 129, 257, 0],+ )+ self.batch.seq_lens.cpu.assert_not_called()++ def test_missing_mirror_uses_device_lengths(self):+ self.batch.seq_lens_cpu = None+ self.batch.seq_lens.cpu.side_effect = None+ self.batch.seq_lens.cpu.return_value = torch.tensor([18, 130, 258])+ self.runner.execute(self.batch)+ self.assertEqual(+ self.runner.backend.replay_with_input_update.call_args.kwargs["seq_lens"],+ [18, 130, 258, 0],+ )++ def test_speculative_decode_keeps_device_length_authority(self):+ self.batch.spec_info = object()+ self.batch.seq_lens.cpu.side_effect = None+ self.batch.seq_lens.cpu.return_value = torch.tensor([20, 132, 260])+ self.runner.execute(self.batch)+ self.assertEqual(+ self.runner.backend.replay_with_input_update.call_args.kwargs["seq_lens"],+ [20, 132, 260, 0],+ )+++class TestNPUPageAllocation(unittest.TestCase):+ def setUp(self):+ self.allocator = object.__new__(NPUPagedTokenToKVPoolAllocator)+ self.allocator.debug_mode = False+ self.allocator.page_size = 128+ self.allocator.free_pages = torch.tensor([8, 11, 13, 17])++ def test_decode_within_pages_does_not_build_a_page_scan(self):+ seq_lens = torch.tensor([2, 128, 130, 256])+ last_loc = torch.tensor([128, 382, 512, 766])+ with patch.object(torch, "cumsum", side_effect=AssertionError("unused scan")):+ out = self.allocator.alloc_decode(seq_lens, seq_lens, last_loc)+ self.assertEqual(out.tolist(), [129, 383, 513, 767])+ self.assertEqual(out.dtype, torch.int32)+ self.assertEqual(self.allocator.free_pages.tolist(), [8, 11, 13, 17])++ def test_decode_across_pages_consumes_pages_in_request_order(self):+ seq_lens = torch.tensor([129, 130, 257, 258])+ last_loc = torch.tensor([255, 512, 767, 896])+ out = self.allocator.alloc_decode(seq_lens, seq_lens, last_loc)+ self.assertEqual(out.tolist(), [8 * 128, 513, 11 * 128, 897])+ self.assertEqual(self.allocator.free_pages.tolist(), [13, 17])+++class TestNPUEagerMetadata(unittest.TestCase):+ def setUp(self):+ self.backend = object.__new__(AscendAttnBackend)+ self.backend.req_to_token_pool = SimpleNamespace(+ req_to_token=torch.arange(4096, dtype=torch.int32).reshape(4, 1024)+ )+ self.backend.page_size = 128+ self.backend.is_hybrid_swa = False+ self.backend.use_mla = False+ self.backend.use_sliding_window_kv_pool = False+ self.batch = SimpleNamespace(+ forward_mode=ForwardMode.EXTEND,+ seq_lens=torch.tensor([130, 180]),+ seq_lens_cpu=torch.tensor([130, 180]),+ req_pool_indices=torch.tensor([1, 2]),+ extend_seq_lens=torch.tensor([2, 3]),+ extend_seq_lens_cpu=[2, 3],+ spec_info=None,+ )++ def test_prefill_metadata_needs_no_device_readback(self):+ with patch.object(torch.Tensor, "cpu", side_effect=AssertionError("readback")):+ self.backend.init_forward_metadata(self.batch)+ metadata = self.backend.forward_metadata+ self.assertEqual(metadata.block_tables.tolist(), [[8, 9], [16, 17]])+ self.assertEqual(metadata.extend_seq_lens_cpu_int.tolist(), [2, 3])+ self.assertEqual(metadata.extend_seq_lens_cpu_int.dtype, torch.int32)++ def test_speculative_lengths_can_advance_independently(self):+ self.batch.spec_info = object()+ self.batch.seq_lens = torch.tensor([130, 300])+ self.batch.extend_seq_lens = torch.tensor([4, 5])+ self.backend.init_forward_metadata(self.batch)+ metadata = self.backend.forward_metadata+ self.assertEqual(metadata.block_tables.shape, (2, 3))+ self.assertEqual(metadata.extend_seq_lens_cpu_int.tolist(), [4, 5])++ def test_padded_device_lengths_keep_the_device_shape(self):+ self.batch.extend_seq_lens = torch.tensor([2, 3, 0])+ self.backend.init_forward_metadata(self.batch)+ metadata = self.backend.forward_metadata+ self.assertEqual(metadata.extend_seq_lens_cpu_int.tolist(), [2, 3, 0])+++class TestNPUGraphUpdateWorker(unittest.TestCase):+ def setUp(self):+ self.device = Mock()+ self.device.current_device.return_value = 0+ self.backend = NPUCudaGraphBackend(+ SimpleNamespace(+ device_module=self.device,+ model_runner=SimpleNamespace(tp_group=None),+ )+ )+ self.addCleanup(self.backend.cleanup)++ def test_updates_overlap_replay_and_reuse_the_worker(self):+ worker_ids = []+ for index in range(3):+ update_started = threading.Event()+ replay_started = threading.Event()+ update_finished = threading.Event()+ metadata = [{"actual_seq_lengths_kv": [index + 1, 0]}]++ def update(*, cpu_update_input):+ self.assertEqual(cpu_update_input, metadata)+ worker_ids.append(threading.get_ident())+ update_started.set()+ self.assertTrue(replay_started.wait(5))+ update_finished.set()++ def replay():+ self.assertTrue(update_started.wait(5))+ replay_started.set()+ self.assertTrue(update_finished.wait(5))++ self.backend._graphs[index] = SimpleNamespace(update=update, replay=replay)+ output = object()+ self.backend._outputs[index] = output+ self.assertIs(+ self.backend.replay_with_input_update(+ index, seq_lens=None, cpu_update_input=metadata+ ),+ output,+ )+ self.assertEqual(len(set(worker_ids)), 1)+ self.assertNotEqual(worker_ids[0], threading.get_ident())+ self.device.set_device.assert_called_once_with(0)+ self.backend.cleanup()+ self.assertIsNone(self.backend._update_executor)+ self.assertFalse(self.backend._graphs)++ def test_update_errors_reach_the_caller(self):+ self.backend._graphs[1] = Mock()+ self.backend._graphs[1].update.side_effect = RuntimeError("update failed")+ self.backend._outputs[1] = object()+ with self.assertRaisesRegex(RuntimeError, "update failed"):+ self.backend.replay_with_input_update(+ 1, seq_lens=[1], attr_name="actual_seq_lengths_kv"+ )++ def test_tensor_metadata_conversion(self):+ graph = Mock()+ self.backend._graphs[1] = graph+ self.backend._outputs[1] = object()+ self.backend.replay_with_input_update(+ 1, seq_lens=[7, 0], attr_name="context_lens", attr_type=torch.empty(0)+ )+ lengths = graph.update.call_args.kwargs["cpu_update_input"][0]["context_lens"]+ self.assertEqual(lengths.tolist(), [7, 0])+ self.assertEqual(lengths.dtype, torch.int32)+ self.assertEqual(lengths.device.type, "cpu")+++if __name__ == "__main__":+ unittest.main()diff --git a/python/sglang/test/ascend/test_npu_prefill_coalescer.py b/python/sglang/test/ascend/test_npu_prefill_coalescer.pynew file mode 100644index 0000000000000000000000000000000000000000..b556b624824af0679c8d54c360963a3ccd64d348--- /dev/null+++ b/python/sglang/test/ascend/test_npu_prefill_coalescer.py@@ -0,0 +1,133 @@+import unittest+from types import SimpleNamespace+from unittest.mock import Mock, patch++from sglang.srt.environ import envs+from sglang.srt.hardware_backend.npu.prefill_coalescer import NPUPrefillCoalescer+from sglang.srt.model_executor.cuda_graph_config import Backend, CudaGraphConfig+++class TestNPUPrefillCoalescer(unittest.TestCase):+ def setUp(self):+ self.coalescer = NPUPrefillCoalescer(max_delay_s=0.08)+ self.coalescer.observe_prefill(0.02)+ self.clock = patch(+ "sglang.srt.hardware_backend.npu.prefill_coalescer.time.perf_counter",+ return_value=100.0,+ ).start()+ self.addCleanup(patch.stopall)+ self.request = object()++ def delay(self, **overrides):+ kwargs = dict(+ running_bs=8, waiting_queue=[self.request], has_chunked_req=False+ )+ kwargs.update(overrides)+ return self.coalescer.should_delay(**kwargs)++ def test_wait_expires_and_does_not_restart_under_memory_pressure(self):+ self.assertTrue(self.delay())+ self.clock.return_value += 0.039+ self.assertTrue(self.delay())+ self.clock.return_value += 0.002+ self.assertFalse(self.delay())+ self.clock.return_value += 1+ self.assertFalse(self.delay())++ def test_second_arrival_is_dispatched_immediately(self):+ self.assertTrue(self.delay())+ self.assertFalse(self.delay(waiting_queue=[self.request, object()]))++ def test_idle_small_decode_and_chunked_prefills_are_not_delayed(self):+ for overrides in (+ dict(running_bs=0),+ dict(running_bs=1),+ dict(has_chunked_req=True),+ dict(waiting_queue=[]),+ ):+ with self.subTest(overrides=overrides):+ self.assertFalse(self.delay(**overrides))++ def test_new_request_gets_its_own_deadline(self):+ self.assertTrue(self.delay())+ self.clock.return_value += 0.05+ self.assertFalse(self.delay())+ self.request = object()+ self.assertTrue(self.delay())+ self.clock.return_value += 0.05+ self.assertFalse(self.delay())++ def test_cold_start_outlier_cannot_exceed_the_ceiling(self):+ self.coalescer.observe_prefill(1000)+ self.assertTrue(self.delay())+ self.clock.return_value += 0.081+ self.assertFalse(self.delay())++ def test_no_observation_and_zero_budget_do_not_wait(self):+ self.coalescer = NPUPrefillCoalescer(0.08)+ self.assertFalse(self.delay())+ self.coalescer = NPUPrefillCoalescer(0)+ self.coalescer.observe_prefill(0.1)+ self.assertFalse(self.delay())++ def test_invalid_timings_cannot_create_an_unbounded_wait(self):+ for duration in (float("nan"), float("inf"), -1):+ self.coalescer.observe_prefill(duration)+ self.assertTrue(self.delay())+ self.clock.return_value += 0.041+ self.assertFalse(self.delay())+ for delay in (float("nan"), float("inf"), -1):+ with self.assertRaises(ValueError):+ NPUPrefillCoalescer(delay)+++class TestNPUPrefillCoalescerEligibility(unittest.TestCase):+ def setUp(self):+ config = CudaGraphConfig.from_dict(+ {"decode": {"backend": "full"}, "prefill": {"backend": "disabled"}}+ )+ self.scheduler = SimpleNamespace(+ enable_overlap=True,+ is_generation=True,+ dllm_config=None,+ ps=SimpleNamespace(tp_size=1, dp_size=1, pp_size=1),+ spec_algorithm=Mock(is_none=lambda: True),+ is_mixed_chunk=False,+ prefill_delayer=None,+ min_free_slots_delayer=None,+ server_args=SimpleNamespace(+ enable_priority_scheduling=False,+ schedule_policy="fcfs",+ disaggregation_mode="null",+ cuda_graph_config=config,+ ),+ )++ def test_single_device_eager_prefill_can_coalesce(self):+ self.assertIsNotNone(NPUPrefillCoalescer.from_scheduler(self.scheduler))++ def test_explicit_scheduling_controls_take_precedence(self):+ for field, value in (+ ("prefill_delayer", object()),+ ("min_free_slots_delayer", object()),+ ("is_mixed_chunk", True),+ ("enable_overlap", False),+ ("dllm_config", object()),+ ):+ with self.subTest(field=field), patch.object(self.scheduler, field, value):+ self.assertIsNone(NPUPrefillCoalescer.from_scheduler(self.scheduler))++ def test_distributed_engines_do_not_make_local_wait_decisions(self):+ for field in ("tp_size", "dp_size", "pp_size"):+ with self.subTest(field=field), patch.object(self.scheduler.ps, field, 2):+ self.assertIsNone(NPUPrefillCoalescer.from_scheduler(self.scheduler))++ def test_graph_prefill_and_env_opt_out(self):+ with envs.SGLANG_NPU_PREFILL_COALESCE_MAX_DELAY.override(0):+ self.assertIsNone(NPUPrefillCoalescer.from_scheduler(self.scheduler))+ self.scheduler.server_args.cuda_graph_config.prefill.backend = Backend.FULL+ self.assertIsNone(NPUPrefillCoalescer.from_scheduler(self.scheduler))+++if __name__ == "__main__":+ unittest.main()