Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
sglang · 5 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..211d01a2ee995b6b5d24cdc2091e37e1227c8d28 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@@ -166,14 +166,13 @@ 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()+ # Rebind first, then replay: the recorded graph reads the rebound host+ # binding, so the update must land before the command list is+ # submitted. Doing it inline also avoids spawning (and joining) a+ # Python thread on every decode step.+ self._device_module.set_device(self._device_id)+ graph.update(cpu_update_input=cpu_update_input) graph.replay()- thread.join() return self._outputs[shape_key] def cleanup(self) -> 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..a0eeedc965aa60808300d863028026cbb04ed43b 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@@ -239,7 +239,17 @@ class NPUGraphRunner(DecodeCudaGraphRunner): is_deepseek_dsa(self.model_runner.model_config.hf_config) or is_deepseek_v4(self.model_runner.model_config.hf_config) ):- if forward_batch.forward_mode.is_target_verify():+ # The scheduler keeps a host mirror of seq_lens (and+ # _apply_cuda_graph_metadata already trusts it on replay), so read+ # that instead of draining the device: a blocking D2H here would+ # serialize the next step's host prep with the previous replay.+ seq_lens_cpu = forward_batch.seq_lens_cpu+ if seq_lens_cpu is not None:+ pad = [0] * (self.bs - self.raw_bs)+ if forward_batch.forward_mode.is_target_verify():+ seq_lens_cpu = seq_lens_cpu + self.captured_req_width+ seq_lens = seq_lens_cpu.tolist() + pad+ elif 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) else:diff --git a/python/sglang/srt/managers/scheduler.py b/python/sglang/srt/managers/scheduler.pyindex a9615a14c512345b2d63323ff3ebd2fe3d9a0dca..81db820cb5e922d4c30fcabce2beb429a107449c 100644--- a/python/sglang/srt/managers/scheduler.py+++ b/python/sglang/srt/managers/scheduler.py@@ -322,6 +322,8 @@ else: logger = logging.getLogger(__name__) +from sglang.srt.managers.scheduler_profbean import _pb_rec # PROFBEAN+ def _prewarm_hccl_group(device, group, device_module): warmup_tensor = torch.zeros(1, dtype=torch.int32, device=device)@@ -1728,11 +1730,13 @@ class Scheduler( if self.gracefully_exit: break + _pb_t0 = time.perf_counter() # PROFBEAN # Receive requests recv_reqs = self.request_receiver.recv_requests() self.process_input_requests(recv_reqs) if self._engine_paused: continue+ _pb_t1 = time.perf_counter() # PROFBEAN # Get the next batch to run plan = self.get_next_batch_to_run(@@ -1744,6 +1748,7 @@ class Scheduler( disable_overlap_for_batch = self.is_disable_overlap_for_batch( batch, last_batch=self.last_batch )+ _pb_t2 = time.perf_counter() # PROFBEAN # If we do not need to overlap the current batch with the last batch, # we can process the last batch immediately.@@ -1766,6 +1771,7 @@ class Scheduler( self.result_queue.append((batch.copy(), batch_result)) else: batch_result = None+ _pb_t3 = time.perf_counter() # PROFBEAN # Process the last batch if self.last_batch:@@ -1774,11 +1780,15 @@ class Scheduler( elif batch is None: # When the server is idle, do self-check and re-init some states self.on_idle()+ _pb_t4 = time.perf_counter() # PROFBEAN # Run sample of the current batch # It depends on the result of the last batch (e.g., grammar), so we run it after the last batch is processed. if self.is_generation: self.launch_batch_sample_if_needed(batch_result, batch)+ _pb_t5 = time.perf_counter() # PROFBEAN+ _pb_rec(self, batch, _pb_t0, _pb_t1, _pb_t2, _pb_t3, _pb_t4, _pb_t5,+ disable_overlap_for_batch) # Update last_batch self.last_batch = batchdiff --git a/python/sglang/srt/managers/scheduler_profbean.py b/python/sglang/srt/managers/scheduler_profbean.pynew file mode 100644index 0000000000000000000000000000000000000000..f2979a055a47bc01e745e8fd7be631fc0e6ffdd2--- /dev/null+++ b/python/sglang/srt/managers/scheduler_profbean.py@@ -0,0 +1,110 @@+"""PROFBEAN_TEMP_INSTRUMENTATION — loop-phase timing for the scheduler.++Appended to python/sglang/srt/managers/scheduler.py during the optimization+session; removed before delivery. Loaded only when the env var is set.+"""++import logging+++_PB_STATE = {"n": 0, "rows": []}++_PB_LABELS = ("recv", "plan", "run_batch", "process", "sample", "TOTAL")+++def _pb_pct(vals, q):+ s = sorted(vals)+ i = (len(s) - 1) * q / 100+ lo = int(i)+ f = i - lo+ return s[lo] * (1 - f) + s[min(lo + 1, len(s) - 1)] * f+++def _pb_rec(sch, batch, t0, t1, t2, t3, t4, t5, disable_overlap):+ import time as _t++ st = _PB_STATE+ st["n"] += 1+ mode = "none"+ if batch is not None:+ mode = "extend" if batch.forward_mode.is_extend() else "decode"+ st["rows"].append(+ (+ mode,+ 0 if batch is None else len(batch.reqs),+ (t1 - t0) * 1000,+ (t2 - t1) * 1000,+ (t3 - t2) * 1000,+ (t4 - t3) * 1000,+ (t5 - t4) * 1000,+ (t5 - t0) * 1000,+ _t.perf_counter(),+ )+ )+ if st["n"] % 1500 == 0:+ _pb_dump(sch)+++def _pb_dump(sch):+ import statistics++ rows = _PB_STATE["rows"]+ if not rows:+ return+ out = []+ for name in ("decode", "extend"):+ rs = [r for r in rows if r[0] == name]+ if not rs:+ continue+ for i, label in enumerate(_PB_LABELS, start=2):+ vals = [r[i] for r in rs]+ out.append(+ "%-6s %-9s p50=%7.3f p90=%7.3f p99=%7.3f max=%8.3f"+ % (name, label, statistics.median(vals), _pb_pct(vals, 90), _pb_pct(vals, 99), max(vals))+ )+ # Wall-clock step period measured between consecutive decode launches.+ periods = [+ (rs[i][8] - rs[i - 1][8]) * 1000 for i in range(1, len(rs))+ ] or [0.0]+ out.append(+ "%-6s n=%d bs_p50=%d wall-step-period p50=%.3f p90=%.3f p99=%.3f"+ % (+ name,+ len(rs),+ statistics.median([r[1] for r in rs]),+ statistics.median(periods),+ _pb_pct(periods, 90),+ _pb_pct(periods, 99),+ )+ )+ logging.getLogger(__name__).info("PROFBEAN\n " + "\n ".join(out))+++_PB2 = {"rows": []}+++def _pb2_rec(forward_batch, t_a, t_b, t_c, t_d):+ _PB2["rows"].append(+ (+ "extend" if forward_batch.forward_mode.is_extend() else "decode",+ (t_b - t_a) * 1000,+ (t_c - t_b) * 1000,+ (t_d - t_c) * 1000,+ )+ )+ if len(_PB2["rows"]) % 400 == 0:+ import statistics++ out = []+ for name in ("decode", "extend"):+ rs = [r for r in _PB2["rows"] if r[0] == name]+ if not rs:+ continue+ for i, label in ((1, "init_new"), (2, "forward"), (3, "sample")):+ vals = [r[i] for r in rs]+ out.append(+ "%-6s %-9s p50=%7.3f p90=%7.3f p99=%7.3f"+ % (name, label, statistics.median(vals), _pb_pct(vals, 90), _pb_pct(vals, 99))+ )+ logging.getLogger(__name__).info("PROFBEAN2\n " + "\n ".join(out))+ _PB2["rows"].clear()diff --git a/python/sglang/srt/managers/tp_worker.py b/python/sglang/srt/managers/tp_worker.pyindex 0fdf5b96657f12efcb568724112b85f5d3155155..b579c62c00fa42a223a70afc39cb5fcb6848f1ce 100644--- a/python/sglang/srt/managers/tp_worker.py+++ b/python/sglang/srt/managers/tp_worker.py@@ -16,6 +16,7 @@ from __future__ import annotations import logging+import time from abc import ABC, abstractmethod from typing import TYPE_CHECKING, List, Optional, Tuple @@ -69,6 +70,8 @@ if TYPE_CHECKING: logger = logging.getLogger(__name__) +from sglang.srt.managers.scheduler_profbean import _pb2_rec # PROFBEAN+ class BaseTpWorker(ABC): @abstractmethod@@ -570,12 +573,14 @@ class TpModelWorker(BaseTpWorker): # update the consumer index of hicache to the running batch self.set_hicache_consumer(batch.hicache_consumer_index) + _t_a = time.perf_counter() # PROFBEAN forward_batch = ForwardBatch.init_new( batch, self.model_runner, capture_hidden_mode=capture_hidden_mode, return_hidden_states_before_norm=False, )+ _t_b = time.perf_counter() # PROFBEAN else: # FIXME(lsyin): unify the interface of forward_batch assert forward_batch is not None@@ -594,6 +599,7 @@ class TpModelWorker(BaseTpWorker): forward_batch, pp_proxy_tensors=pp_proxy_tensors, )+ _t_c = time.perf_counter() # PROFBEAN logits_output, can_run_cuda_graph = out.logits_output, out.can_run_graph batch_result = GenerationBatchResult( logits_output=logits_output,@@ -627,6 +633,7 @@ class TpModelWorker(BaseTpWorker): batch_result.next_token_ids = self.model_runner.sample( logits_output, forward_batch )+ _pb2_rec(forward_batch, _t_a, _t_b, _t_c, time.perf_counter()) # PROFBEAN else: # For prefill-only requests, create dummy token IDs on CPU # The size should match the batch size (number of sequences), not total tokens