Skip to content

[Fix] scheduler: Keep the new-token ratio at its floor after a KV-full retraction - #46496

Open
sohom-cs wants to merge 8 commits into
sgl-project:mainfrom
sohom-cs:fix/retract-keeps-new-token-ratio
Open

sohom-cs wants to merge 8 commits into
sgl-project:mainfrom
sohom-cs:fix/retract-keeps-new-token-ratio

Conversation

@sohom-cs

@sohom-cs sohom-cs commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Fixes #46495.

With max_tokens unset (the OpenAI chat default), max_new_tokens is about the context length minus the prompt. After a KV-full retraction the scheduler sets the new-token ratio to retract_decode's estimate, which divides by the survivors' unclipped max_new_tokens (new_token_ratio_tracker.py:41-49). So it lands far below NewTokenRatioTracker.min, which every other writer of the ratio (init, decay_step, reset) keeps. Admission multiplies the ratio by each running request's remainder clipped to 4096 (schedule_policy.py:756-765). So right after the pool ran out it reserves much less decode headroom and admits more prefill work, until the next decode step puts the ratio back at the floor.

The issue has the CPU repro and its output on main: the ratio goes 0.0980 -> 0.0117, the survivors' decode reservation drops from 15254 to 1819 tokens, and two fresh 2000-token requests are admitted with 20000 tokens free (none at the floor).

Modifications

update_running_batch clamps the estimate to the tracker's floor (scheduler.py:4471, one line plus a comment). Above the floor the estimate is used as before: with max_tokens=2048 it is 0.7422, and a later retraction can still lower the ratio toward the floor.

The issue lists two other forms: the estimate in clipped units, or on the clipped remainder. Both change the estimate itself, and add_one_req_ignore_eos (schedule_policy.py:1217-1223) multiplies the ratio by unclipped max_new_tokens: with max_tokens unset either would reserve about 47k tokens per running request there, against about 11k at the floor. The issue also mentions clamping to the current ratio, which would keep a ratio that an earlier retraction raised. I kept to the floor. I'll switch to another form if you prefer it.

The retraction warning now logs the applied ratio, so a clamped retraction logs 0.0980 -> 0.0980.

Accuracy Tests

New file test/registered/unit/managers/test_scheduler_retract_ratio.py, like the other test_scheduler_*.py files there: it needs its own fixture, a bare Scheduler with a real NewTokenRatioTracker and a stubbed batch. It drives the real update_running_batch.

  • max_tokens unset, ratio at 0.5: the retraction sets the floor, not the estimate and not the old ratio.
  • max_tokens=2048: the retraction still raises the ratio to the estimate.

test_scheduler_pause_generation.py gets one line: its stub tracker gains min.

On CPU:

  • main: 1 failed, 1 passed (AssertionError: 0.011686012858255906 != 0.098)
  • this PR: 2 passed; test_retraction_order.py, test_scheduler_pause_generation.py, test_scheduler_flush_cache_after_retract.py and test_schedule_policy.py still pass (47 passed, 10 subtests), as do four more scheduler test files that stub update_running_batch or the tracker (26 passed, 56 subtests)

Not run: a GPU job.

Speed Tests and Profiling

N/A: one max per retraction. Right after a below-floor retraction admission reserves what it reserves at the floor, as on every other step; I have not measured throughput under KV pressure.

Checklist

Developed with AI assistance (Claude); every changed line was reviewed and the tests were run locally by me.


CI States

Latest PR Test (Base): ⊘ Skipped in Run #45698036055 -- its commit has no run-ci approval, or the run predates the labels; a maintainer's /approve-ci approves this commit and reruns it, or /rerun-failed-ci reruns an approved one.
Latest PR Test (Extra): ⊘ Skipped -- add the run-ci-nv-extra label to opt in.
Latest PR Test (AMD ROCm 10): ➖ No AMD PR run found for this commit.

Tip

Base CI only covers the core cases, and its workload may not exercise your change. Use /rerun-test to run the tests your change touches, or copy this prompt for an agent:

Find the registered tests this PR affects and run them with /rerun-test, following https://github.com/sgl-project/sglang/blob/main/.agents/skills/rerun-test/SKILL.md

…l retraction

With max_tokens unset (the OpenAI chat default), max_new_tokens is about
the context length minus the prompt. After a KV-full retraction the
scheduler sets the ratio to retract_decode's estimate, (decoded + 20 * n)
/ (sum of unclipped max_new_tokens + 1) over the survivors, which lands
far below NewTokenRatioTracker.min (0.0117 against 0.098 in the new
test). Admission multiplies the ratio by each running request's
remainder clipped to 4096, so right after the pool ran out it reserves
much less decode headroom and admits more prefill work. Every other
writer of the ratio (init, decay_step, reset) keeps it at or above min.

Clamp the estimate to min. Above the floor the estimate is used as
before, so a retraction can still raise or lower the ratio.

Signed-off-by: Sohom Chakraborty <[email protected]>
detain added a commit to detain/sglang that referenced this pull request Oct 29, 2026
[Fix] scheduler: keep the new-token ratio at its floor after a KV-full
retraction. An unset max_tokens over a long context makes
retract_decode's estimate land under NewTokenRatioTracker.min,
releasing the floor exactly when the pool ran dry -> over-admission
(issue sgl-project#46495). One clamp line + comment.

git apply -3 clean on all 3 files (scheduler region at our :4438).

CPU: test_scheduler_retract_ratio (new, 2P incl. the floor case) +
test_scheduler_pause_generation = 29P/8sub.

(cherry picked from commit 1947555)
(cherry picked from commit 8c9565bac3b167ccb84f8abad57546fc8c53a954)
detain added a commit to detain/sglang that referenced this pull request Oct 29, 2026
…gl-project#45607/sgl-project#45789 (entries 267-270)

Second admission docs commit. Records: sgl-project#46496 DRAFT-upstream status;
sgl-project#46643's BEHAVIOR CHANGE (admission re-runs every round for ALL models --
TTFT/starvation watch at the owed restart, entry-198 precedent; the two
entry-198 arms removed as strict subsets, COW-retry semantics untouched);
sgl-project#45607 page-align composition with entry-177's lcm aligner (both shrink-
only; exact_chunk_fill arm untouched upstream too); sgl-project#45789 default-OFF
fork-split with the guard reconciliation vs sgl-project#46643 (policy-reopening term
proven no-op, test re-pinned), fork cut after sgl-project#45607 align, and the
deliberate no-thread of truncation_align_size into entry-177's aligner.

Battery: every worker number REPRODUCED EXACT AT THEIR OWN TREES (method
identity), then re-measured on the combined tree with full attribution of
every drift; managers dir RE-PINNED 1013P/2F/3S/933sub (base 988). The
worker's stashed-baseline '992P' decomposes only as fresh-base 988 +
their own picks (+5 at sgl-project#46643 EXACT) -- flagged as measurement noise.
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]>
@sohom-cs
sohom-cs marked this pull request as ready for review November 2, 2026 04:47
@sohom-cs
sohom-cs requested a review from merrymercy as a code owner November 2, 2026 04:47

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-02T04:49:36.311300Z 1947555 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Main's KV-full retraction now also removes the retracted requests from
running_reqs, so the test's bare Scheduler needs that field.

Signed-off-by: Sohom Chakraborty <[email protected]>

@BBuf BBuf left a comment

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.

[BBuf Review Agent] LGTM. Please wait for the related CPU and retraction CI.

@BBuf

BBuf commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

/tag-and-rerun-ci

@BBuf

BBuf commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

/rerun-test test/registered/scheduler/test_retract_decode.py

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Nov 3, 2026
@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

🚀 1-gpu-5090 (1 test): ✅ View workflow run

cd test/ && python3 registered/scheduler/test_retract_decode.py

detain added a commit to detain/sglang that referenced this pull request Nov 11, 2026
…r + retract floor -- 11/39 markers consumed

- overlap seam ADOPTED onto sgl-project#47716 (1c0dc02): should_process_last_batch_early
  is now the single pre-schedule pop+flush point, so the fork's entry-220
  publish-before-prepare predicate (_has_pending_mamba_cache_update) RE-PLANTED
  as its first arm (double pop_and_process guard subsumed by the early flag);
  entry-122 grammar-mixed sync rides last_batch.grammar_needs_sync() (schedule
  batch half lands with C2). Opportunistic flush takes upstream's hardened
  propagate form (the fork's try/except predates it; b3-era unified pool audit).
- capacity pair (sgl-project#43527, entry 200): _observed_storage + load_inquirer +
  tp_worker.get_worker_info dropped the consumer-side *kv_shard_widening /
  *page_interleave_shard_size re-widening (the configurator's allocator.size
  branch is logical; test_dcp_logical_capacity is the anti-double-widening
  tripwire); upstream's in-window from_cp_sharded cp-arm KEPT -- matching the
  unmarked init_req-subtraction site.
- COW catcher (entry 198) RE-PLANTED over the cascade's BROKEN union: the
  merge6 take-upstream flattened the try/except and left a DOUBLED staging arm
  with add_one_req nested inside the hicache guard (non-hicache deployments
  would have lost res= assignment; prepare_staged_prefetch double-called).
  MambaCowAllocError import restored.
- retract floor (sgl-project#46496, entry 267) RE-PLANTED post-retract_decode clamp.
- test seam re-adaptations (upstream moves, pins preserved): OverlapHarness ->
  sgl-project#47716 loop entrypoints (pause_state/increment/should_early/invariant),
  grammar-tail scheduler test -> should_process_last_batch_early (C2 completes),
  hybrid_ssm stubs -> IndexedReqList queues + should_defer/
  batch_is_full_after_rejection + tree_sub_pool family kwarg (b3 sgl-project#48013 seam),
  retract stubs -> request_retirer/running_reqs, dcp consumers -> _observed_
  storage helper, running_reqs preemption -> fork get_kvcache fixture (B4-5
  note (2) pattern), running_batch_finished -> request-list properties.

Targeted: 32P/0F/18sub (boundary+retry+latch+retract+dcp+running_reqs+finished).
Gates: ruff repo ruleset + format on touched files; registration trio rc=0.
…-token-ratio

Signed-off-by: Sohom Chakraborty <[email protected]>

# Conflicts:
#	python/sglang/srt/managers/scheduler.py
Main now releases retracted requests through RequestRetirer and dropped
the running_reqs component, so the test's bare Scheduler takes a
request_retirer and uocr_runtime instead.

Signed-off-by: Sohom Chakraborty <[email protected]>
@sohom-cs

Copy link
Copy Markdown
Contributor Author

/rerun-failed-ci

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] KV-full retraction can drop new_token_ratio below its floor and loosen admission

2 participants