Skip to content

Commit f9bdb74

Browse files
authored
[Fix] scheduler: Count a request's held req_to_token row once at admission (#44401)
1 parent 93842f5 commit f9bdb74

3 files changed

Lines changed: 154 additions & 7 deletions

File tree

‎python/sglang/srt/dllm/mixin/scheduler.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -376,7 +376,10 @@ def process_dllm_incoming_reqs(
376376
for req in reqs:
377377
# Check if batch is full
378378
running_bs = len(running_batch.reqs)
379-
if len(adder.can_run_list) >= self.get_num_allocatable_reqs(running_bs):
379+
num_held_rows = sum(r.kv.holds_kv for r in adder.can_run_list)
380+
if len(adder.can_run_list) >= self.get_num_allocatable_reqs(
381+
running_bs, num_held_rows=num_held_rows
382+
):
380383
running_batch.batch_is_full = True
381384

382385
# Try preemption if batch is full

‎python/sglang/srt/managers/scheduler.py‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3928,9 +3928,12 @@ def get_num_allocatable_reqs(
39283928
running_bs: int,
39293929
beam_width: Optional[int] = None,
39303930
running_batch: Optional[ScheduleBatch] = None,
3931+
num_held_rows: int = 0,
39313932
) -> int:
39323933
pp_budget = get_parallel().pp_max_micro_batch_size - running_bs
3933-
available = self.req_to_token_pool.available_size()
3934+
# Requests the caller counts that already hold a row (a continuing
3935+
# chunk, a session borrow) need no free one; give their rows back.
3936+
available = self.req_to_token_pool.available_size() + num_held_rows
39343937

39353938
active_batch = running_batch or self.running_batch
39363939
available = max(
@@ -3985,8 +3988,8 @@ def _get_new_batch_prefill_raw(
39853988
# Reset batch_is_full to try preemption with a prefill adder.
39863989
running_batch.batch_is_full = False
39873990
if running_batch.is_empty():
3988-
# An empty batch never reaches update_running_batch, the only
3989-
# other place that clears the flag, so admission would stay shut.
3991+
# An empty batch has no request left to leave, and only a leaving
3992+
# request clears the flag elsewhere, so admission would stay shut.
39903993
running_batch.batch_is_full = False
39913994

39923995
if (
@@ -4009,8 +4012,8 @@ def _get_new_batch_prefill_raw(
40094012
return None, running_batch
40104013

40114014
# Ignore the check if self.chunked_req is not None.
4012-
# In the non-PP case, when self.chunked_req is not None, num_allocatable_reqs should always be greater than 0,
4013-
# as the space for the chunked requests has just been released.
4015+
# In the non-PP case, a chunked request keeps its req_to_token row across chunks,
4016+
# so continuing it needs no free row.
40144017
# In PP case, chunked requests (or dllm requests) can start in one microbatch and end in another microbatch, so the max_running_requests per microbatch should not be strict.
40154018
# Instead, we should always allow chunked requests to be added, otherwise, there will be a memory leak.
40164019
if (
@@ -4114,16 +4117,21 @@ def _get_new_batch_prefill_raw(
41144117
candidate_beam_width = (
41154118
req.beam_group.beam_width if req.beam_group is not None else None
41164119
)
4120+
num_held_rows = sum(r.kv.holds_kv for r in adder.can_run_list)
41174121
if len(adder.can_run_list) >= self.get_num_allocatable_reqs(
41184122
running_bs,
41194123
candidate_beam_width,
41204124
running_batch=running_batch,
4125+
num_held_rows=num_held_rows,
41214126
):
41224127
running_batch.batch_is_full = True
41234128
if self.disaggregation_mode == DisaggregationMode.PREFILL:
41244129
# In prefill mode, prealloc queue and transfer queue can also take memory,
41254130
# so we need to check if the available size for the actual available size.
4126-
if len(adder.can_run_list) >= self.req_to_token_pool.available_size():
4131+
if (
4132+
len(adder.can_run_list) - num_held_rows
4133+
>= self.req_to_token_pool.available_size()
4134+
):
41274135
running_batch.batch_is_full = True
41284136

41294137
if running_batch.batch_is_full:
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
"""A request that already holds a req_to_token row is not counted twice at admission (#38118, #35537)."""
2+
3+
import unittest
4+
from types import SimpleNamespace
5+
from unittest.mock import Mock, patch
6+
7+
from sglang.test.ci.ci_register import register_cpu_ci
8+
from sglang.test.test_utils import CustomTestCase, maybe_stub_sgl_kernel
9+
10+
maybe_stub_sgl_kernel()
11+
12+
from sglang.srt.disaggregation.utils import DisaggregationMode
13+
from sglang.srt.managers.schedule_batch import ScheduleBatch
14+
from sglang.srt.managers.schedule_policy import AddReqResult
15+
from sglang.srt.managers.scheduler import Scheduler
16+
from sglang.srt.runtime_context import get_context
17+
18+
register_cpu_ci(est_time=3, suite="base-a-test-cpu")
19+
20+
NUM_ROWS = 4
21+
22+
23+
class _Req:
24+
def __init__(self, holds_row):
25+
self.kv = SimpleNamespace(holds_kv=holds_row)
26+
self.beam_group = None
27+
self.token_indices_to_pool = None
28+
self.inflight_middle_chunks = 0
29+
30+
def init_next_round_input(self, tree_cache=None):
31+
pass
32+
33+
34+
class _Adder:
35+
"""Admits whatever the gate lets through; the final chunk joins first."""
36+
37+
def __init__(self, *args, **kwargs):
38+
self.can_run_list = []
39+
self.preempt_list = []
40+
self.new_chunked_req = None
41+
self.rem_chunk_tokens = 0
42+
43+
def add_chunked_req(self, req):
44+
self.can_run_list.append(req)
45+
return None
46+
47+
def add_one_req(self, req, has_chunked_req, truncation_align_size):
48+
self.can_run_list.append(req)
49+
return AddReqResult.CONTINUE
50+
51+
52+
class _BatchBuilt(Exception):
53+
pass
54+
55+
56+
class TestHeldRowAdmission(CustomTestCase):
57+
def _scheduler(self, disaggregation_mode, running, final_chunk, waiting):
58+
s = Scheduler.__new__(Scheduler)
59+
s.grammar_manager = SimpleNamespace(has_waiting_grammars=lambda: False)
60+
s.enable_priority_preemption = False
61+
s.is_hybrid_swa = False
62+
s.waiting_queue = waiting
63+
s.chunked_req = final_chunk
64+
s.min_free_slots_delayer = None
65+
s.policy = Mock()
66+
s.policy.shortest_prefill_chunk_limit.return_value = None
67+
s.processed_tokens_counter = 0
68+
s.chunked_prefill_size = 8192
69+
s.dynamic_chunk_sizer = None
70+
s.tp_worker = SimpleNamespace(
71+
model_runner=SimpleNamespace(attn_backend=SimpleNamespace())
72+
)
73+
s.get_prefill_adder_class = lambda: _Adder
74+
s.page_size = 1
75+
s.tree_cache = SimpleNamespace(
76+
buffer_pipeline=None, storage_prefetch_retries=None
77+
)
78+
s.token_to_kv_pool_allocator = None
79+
s.new_token_ratio_tracker = SimpleNamespace(current=0.0)
80+
s.max_prefill_tokens = 1 << 20
81+
s.is_mixed_chunk = False
82+
s.priority_scheduling_preemption_threshold = 0
83+
s.max_prefill_bs = 0
84+
s.max_running_requests = NUM_ROWS
85+
s.dllm_config = None
86+
s.enable_lora = False
87+
s.disaggregation_mode = disaggregation_mode
88+
s.enable_hicache_storage = False
89+
s.enable_lmcache = False
90+
s.truncation_align_size = None
91+
s.model_config = None
92+
s.enable_overlap = False
93+
s.spec_algorithm = None
94+
# The final chunk and the running requests hold rows; one row is free.
95+
s.req_to_token_pool = SimpleNamespace(
96+
available_size=lambda: NUM_ROWS - len(running) - 1
97+
)
98+
s.beam_coordinator = SimpleNamespace(pending_member_rows=lambda batch: 0)
99+
return s
100+
101+
def _admitted(self, disaggregation_mode):
102+
running = [_Req(holds_row=True), _Req(holds_row=True)]
103+
final_chunk = _Req(holds_row=True)
104+
waiting = _Req(holds_row=False)
105+
running_batch = ScheduleBatch(reqs=running)
106+
s = self._scheduler(disaggregation_mode, running, final_chunk, [waiting])
107+
108+
def capture(can_run_list, *args, **kwargs):
109+
raise _BatchBuilt(list(can_run_list))
110+
111+
with (
112+
get_context().override_server_args(pp_max_micro_batch_size=NUM_ROWS),
113+
patch.object(ScheduleBatch, "init_new", side_effect=capture),
114+
patch("sglang.srt.managers.scheduler.set_time_batch"),
115+
):
116+
with self.assertRaises(_BatchBuilt) as built:
117+
s._get_new_batch_prefill_raw(
118+
prefill_delayer_single_pass=None, running_batch=running_batch
119+
)
120+
return (
121+
built.exception.args[0],
122+
running_batch.batch_is_full,
123+
final_chunk,
124+
waiting,
125+
)
126+
127+
def test_final_chunk_leaves_the_free_row_to_a_waiting_request(self):
128+
for mode in (DisaggregationMode.NULL, DisaggregationMode.PREFILL):
129+
with self.subTest(mode=mode):
130+
can_run_list, batch_is_full, final_chunk, waiting = self._admitted(mode)
131+
self.assertEqual(can_run_list, [final_chunk, waiting])
132+
self.assertFalse(batch_is_full)
133+
134+
135+
if __name__ == "__main__":
136+
unittest.main()

0 commit comments

Comments
 (0)