Skip to content

[bugfix] chunked prefill req counted as a new waiting req in calculating batch_is_full - #40940

Closed
MatsueYu wants to merge 1 commit into
sgl-project:mainfrom
MatsueYu:batch-add
Closed

MatsueYu wants to merge 1 commit into
sgl-project:mainfrom
MatsueYu:batch-add

Conversation

@MatsueYu

@MatsueYu MatsueYu commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

In Prefill procedure, chunked reqs,

Under the combination of chunked prefill + DP attention, when max_running_requests > 1 and chunked_prefill_size is internally divided by dp_size along the dp-attention path, the per-rank running batch gets stuck at max_running_requests - 1 in steady state:

  • Each DP rank is expected to admit up to max_running_requests // dp_size requests in flight (e.g., 16).
  • In practice, each DP rank holds at most 15 (or max - 1) consistently.
  • The under-utilization persists through the entire steady state; it only briefly recovers when a request finishes and triggers a batch shrink.
  • Reducing chunked_prefill_size or disabling chunked prefill avoids the bug.
  • Increasing concurrency or shortening output_len does not help — as long as "a chunked_req is in flight" AND "the waiting queue is non-empty" both hold, the bug fires.

The admission check len(adder.can_run_list) >= get_num_allocatable_reqs(...) compares two quantities with mismatched scopes. adder.can_run_list includes the in-flight chunked request that add_chunked_req just appended for its next chunk — that request already holds a req_to_token_pool row from its initial prefill, so appending it here is bookkeeping, not a new admission. get_num_allocatable_reqs() counts how many new requests can fit; it uses pp_max_micro_batch_size - running_bs and req_to_token_pool.available_size(), both of which have already subtracted the chunked request's row.

When bs = max - 1 with a chunked request in flight, both sides evaluate to 1, so 1 >= 1 flips batch_is_full to True and breaks out of the admission loop before any waiting request is examined. Since batch_is_full only resets when a request finishes, the running batch is pinned at max - 1 for the rest of steady state.

As an example, in Ascend 910 NPU environment, TP8+DP8+DP Attention+EP8, Qwen3.5 122B A10B, chunked-refill-size 32768, adjust men-fraction-static and schedule-conservativeness to ensure max-request 16 per rank. Sending 128 reqs of (2k to 32k) by bench serving will trigger this problem.

Modifications

Admission gate in _get_new_batch_prefill_raw: track whether add_chunked_req appended to can_run_list (via length diff) and subtract that count from the left side of the gate.

Before
Pasted image 20260924110858

After
Pasted image 20260924141602

Accuracy Tests

Speed Tests and Profiling

Checklist

Review and Merge Process

  1. Ping Merge Oncalls to start the process. See the PR Merge Process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests with comments or contact authorized users to do so.
    • Common commands include /tag-and-rerun-ci, /tag-run-ci-label, /rerun-failed-ci
  4. After green CI and required approvals, ask Merge Oncalls or people with Write permission to merge the PR.

CI States

Latest PR Test (Base): ❌ Run #37900816258
Latest PR Test (Extra): ❌ Run #37900815823
Latest PR Test (AMD ROCm 10): ❌ Run #37900816027

Comment thread python/sglang/srt/managers/scheduler.py Outdated
@@ -3927,6 +3925,7 @@ def _get_new_batch_prefill_raw(
self.page_size,
)
self.chunked_req = adder.add_chunked_req(self.chunked_req)
has_chunked = 1 if len(adder.can_run_list) > pre_can_run_list_len else 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

has_chunked is assigned only when self.chunked_req is not None, but the waiting-queue loop uses it unconditionally. On the first ordinary request, self.chunked_req is None, so the admission check raises UnboundLocalError. This also affects configurations with chunked prefill disabled. Initialize has_chunked = 0 before the branch.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, has_chunked is now out of the branch

Comment thread python/sglang/srt/managers/scheduler.py Outdated
@@ -3954,7 +3953,8 @@ def _get_new_batch_prefill_raw(
candidate_beam_width = (
req.beam_group.beam_width if req.beam_group is not None else None
)
if len(adder.can_run_list) >= self.get_num_allocatable_reqs(
# chunked req is loaded in a previous prefill step and should not be counted for occupying a free slot in this step.
if len(adder.can_run_list) - has_chunked >= self.get_num_allocatable_reqs(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

get_num_allocatable_reqs() returns the minimum of the remaining PP microbatch capacity and the available request-pool slots. A continuing chunked request reuses its pool slot, but still occupies microbatch capacity. Subtracting it from the count used against both limits can therefore admit an extra waiting request. For example, with a microbatch limit of 2, 1 running request, 1 chunked request completing its final prefill chunk, and sufficient free pool slots, the new condition evaluates to 1 - 1 >= 1, which is false. Another request is admitted, bringing the total to 3. Check total microbatch occupancy separately from requests requiring new pool slots.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Modification on get_num_allocatable_reqs will handle this problem

@sglang-npu-bot

Copy link
Copy Markdown
Collaborator

/tag-and-rerun-ci

@@ -3911,6 +3926,7 @@ def _get_new_batch_prefill_raw(
self.page_size,
)
self.chunked_req = adder.add_chunked_req(self.chunked_req)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

try to correct running_bs, if chunked req is added, running_bs+=1

Comment thread python/sglang/srt/managers/scheduler.py Outdated
@@ -3911,6 +3926,7 @@ def _get_new_batch_prefill_raw(
self.page_size,
)
self.chunked_req = adder.add_chunked_req(self.chunked_req)
has_chunked = 1 if len(adder.can_run_list) > pre_can_run_list_len else 0

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move this counter to PrefillAdder class

Comment thread python/sglang/srt/managers/scheduler.py Outdated
Comment on lines 3783 to 3784
pp_budget = get_parallel().pp_max_micro_batch_size - running_bs - has_chunked
available = self.req_to_token_pool.available_size()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pp_budget controls available request slots for prefill which contain both chunk_reqs and new_reqs,
meanwhile available controls available kvpool capacity although chunk_reqs has already allocated,
this is a sufficient comparison from two different perspective, we don't need to subtract chunk_reqs here

@hnyls2002

Copy link
Copy Markdown
Collaborator

Thanks @MatsueYu! The same double count is fixed on main by #44401, which gives back the rows that admitted requests already hold on the pool side only. Subtracting the chunked request from can_run_list here also removes it from pp_budget, which lets a PP microbatch go one past pp_max_micro_batch_size. Closing as superseded; please reopen if the plateau still shows on main.

@hnyls2002 hnyls2002 closed this Oct 15, 2026
detain added a commit to detain/sglang that referenced this pull request Oct 30, 2026
…entries 122,198,200,211,215,220,267,268,305

Re-plants the scheduler.py fork-hunks (replant/...managers__scheduler.py.fork-hunks.patch)
onto the post-sgl-project#46977 admission structure. tp_worker marker consumed (15/23 B4 markers
still on the tree; per-file counts, damage-state from entry 310's map).

PER-HUNK DECISIONS (all VERIFIED against the merged tree, not taken on faith):
- entry 122 (sgl-project#40458): grammar-sync overlap disable RE-PLANTED for mixed mode
  (is_decode() OR is_mixed()) + the fork's trimmed comments; upstream's
  host-draft-only arm was the pre-sgl-project#40458 form (origin/main verified: absent).
- entry 220 (sgl-project#39765, OPEN port): _has_pending_mamba_cache_update + the early
  pop_and_process/short-circuited disable-overlap RE-PLANTED into
  event_loop_overlap; the require_mlp_sync/disable/extra-buffer gate verbatim.
- entry 198 (sgl-project#37612): THE CATCHER — B3-5 landed the raiser; the
  try/except MambaCowAllocError around init_next_round_input (res=NO_TOKEN,
  request stays queued; the revert block + unconditional alloc_group_end were
  already in the merged tree = the no-leak halves VERIFIED PRESENT) RE-PLANTED
  with the import. COW component test re-anchored to the #46970x kv_storage
  seam the B3-5 replant moved _state() behind (stub was the pre-split
  mamba_allocator shape).
- entry 268 (sgl-project#46643, OPEN port -- VERIFIED NEVER MERGED: git log
  12dc623..2a6c204 --grep 46643 = ZERO; only sgl-project#45491/sgl-project#45435/sgl-project#45472/sgl-project#45670
  of the briefed merged-list arrived in-range): the UNCONDITIONAL batch_is_full
  clear RE-PLANTED on the scheduler side, subsuming the entry-198 hybrid-SSM
  arm and the priority-preemption/is_empty arms (policy side lands in B4-3).
- entry 267 (sgl-project#46496): retract_decode new_token_ratio FLOOR clamp RE-PLANTED.
- entry 211: triton_load_watch.prewarm_device_loads(self.model_worker) line
  RE-PLANTED between install() and mark_serving_started (the utils-side
  function survived the merge; only the call site was dropped).
- entry 200 (sgl-project#43527) CAPACITY PAIR RE-PLANTED: model_runner
  .logical_max_total_num_tokens passes allocator= again (the configurator's
  PageInterleavePoolAllocator -> allocator.size branch SURVIVED the merge
  byte-identical, so the merged tree had the fork predicate with upstream's
  consumer-side multiplications = DOUBLE-COUNT); the three scheduler
  * kv_shard_widening multipliers back to the fork form (pool-stats shape,
  load_inquirer, and the init_req one-page-per-shard subtraction);
  tp_worker drops page_interleave_shard_size x + import. Upstream's
  invariant-checker hunk: OBSOLETE (the constructor no longer takes
  max_total_num_tokens -- absorbed by refactor).
- entry 215 (sgl-project#44351/sgl-project#44401/sgl-project#44420): VERIFIED ALREADY PRESENT at the merge
  (filter_batch-every-step + reset ride, num_held_rows, budget_state FIRST
  statement, PD-gate deletion all byte-compare to the fork form) -- DEDUPED,
  no edit. Entry 107's local early-revision of sgl-project#40940 stays superseded
  (entry 215 rule), and its re-plant here would double-count.
- entry 220's/305's pause-window busy accounting + write_fence_stream +
  is_empty arm: VERIFIED PRESENT (entry 305 landed patch-identical via
  sgl-project#46127; the fence assignment is the B3-2 controller half) -- DEDUPED.

TEST FIXTURE RE-ANCHORS (not B2's: no markers, pure new-upstream-contract
drift, per the entry-198 fixture-adaptation precedent): the two hybrid-ssm
admission stubs gain disagg_prefill_bootstrap_queue=None (upstream's
routing-key bootstrap_queue arg in calc_priority arrived in-range).

PRUNE vs BREAKAGE (managers −523sub audit): the three managers test files
vanished in-range (test_schedule_policy_dfs_weight, test_scheduler_batch_is
_full_latch, test_uno_token_accounting) were ALL deleted by upstream's OWN
sgl-project#45672 prune (3438ed6). Two are byte-identical upstream copies = zero
fork delta. The third carried a 3-line fork comment/stub delta whose
SEMANTICS the re-planted unconditional clear pins: its case was the
is_empty-arm mirror of test_scheduler_hybrid_ssm_admission_latch (present,
green, hybrid_swa/non-hybrid arms included) -- NOT re-homed, recorded.

ACTUALS (damage -> after, CVD=9, prod venv, PYTHONPATH=python, per-file):
  test_scheduler_hybrid_ssm_admission_retry   4F -> ** 4P **
  test_scheduler_hybrid_ssm_admission_latch   3F -> ** 4P **
  test_mamba_prefill_cache_boundary  2F/12subF -> ** 5P/12sub EXACT (220 pin) **
  test_scheduler_retract_ratio                1F -> ** 2P EXACT (267 pin) **
  test_scheduler_init_req_max_new_tokens      1F -> ** 10P/6sub **
  test_scheduler_grammar_mixed_tail_sync      1F -> ** 4P **
  adjacent scheduler-stub files (held_row, running_batch_finished,
  pause_generation, disagg_idle, dp_converted, hicache_events) 56P/64sub
  UNMOVED -- no regression from the clear/catcher/capacity edits.
Lint: ruff format + F821/E9 clean on all five files; imports OK (no GPU
execution, no push).

Co-Authored-By: OpenCode <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bypass-fail-fast CI: a failing job no longer aborts its siblings (lint still gates) run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants