Skip to content

[Perf] scheduler/hicache: Replace O(B^2) request and page list scans in ScheduleBatch.filter_batch, BatchResultProcessor, and RankMetadata - #46272

Open
deep1blue wants to merge 2 commits into
sgl-project:mainfrom
deep1blue:perf/batch-filter-and-hf3fs-metadata-set
Open

deep1blue wants to merge 2 commits into
sgl-project:mainfrom
deep1blue:perf/batch-filter-and-hf3fs-metadata-set

Conversation

@deep1blue

@deep1blue deep1blue commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

While profiling CPU-side batch bookkeeping and HiCache storage metadata operations in SGLang, we identified three linear list-membership bottlenecks on hot paths:

  1. ScheduleBatch.filter_batch (python/sglang/srt/managers/schedule_batch.py):
    When keep_indices is None, self.reqs[i] not in reqs_to_exclude scanned reqs_to_exclude as a Python list for every request in self.reqs, taking $O(|\text{reqs}| \cdot |\text{reqs_to_exclude}|)$ time during running-batch filtering (finishing_reqs) and disaggregation prefill filtering.
  2. SchedulerBatchResultProcessor.process_batch_result_prefill (python/sglang/srt/managers/scheduler_components/batch_result_processor.py):
    During mixed chunked-prefill batches (batch.decoding_reqs), req in batch.decoding_reqs / req not in batch.decoding_reqs was evaluated up to three times per request in batch.reqs via linear list scans ($O(|\text{reqs}| \cdot |\text{decoding_reqs}|)$), whereas SchedulerMetricsReporter (metrics_reporter.py) already precomputes an $O(1)$ id(req) set.
  3. RankMetadata.confirm_write / delete_keys (python/sglang/srt/mem_cache/storage/hf3fs/mini_3fs_metadata_server.py):
    Checking if page_index not in self.free_pages: scanned the free_pages list linearly on every released or deleted page ($O(P \cdot |\text{free_pages}|)$).

Modifications

  • python/sglang/srt/managers/schedule_batch.py: Precompute reqs_to_exclude_ids as an $O(1)$ set of object IDs before building keep_indices in ScheduleBatch.filter_batch (126.1x speedup at 4,096 requests with 512 excluded: 17.21 ms -> 0.136 ms).
  • python/sglang/srt/managers/scheduler_components/batch_result_processor.py: Lazily materialize decoding_req_ids = {id(r) for r in batch.decoding_reqs} once per batch when processing completed prefill/mixed chunks and reuse is_decoding_req = id(req) in decoding_req_ids across all three checks (184.2x speedup on mixed-batch membership checks at 4,096 decoding requests: 65.40 ms -> 0.355 ms).
  • python/sglang/srt/mem_cache/storage/hf3fs/mini_3fs_metadata_server.py: Maintain a companion free_pages_set: set[int] alongside RankMetadata.free_pages across reserve_and_allocate_page_indices, confirm_write, delete_keys, clear_all, and GlobalMetadataState.load_from_disk (819x speedup releasing 2,000 pages against 50,000 free pages: 737.4 ms -> 0.90 ms).
  • test/registered/unit/managers/test_schedule_batch_req_pool_indices.py: Add unit tests TestFilterBatchReqsToExclude and TestHf3fsRankMetadataSet.

Verification

pytest test/registered/unit/managers/test_schedule_batch_out_of_place.py \
       test/registered/unit/managers/test_batch_result_processor_hidden_states.py \
       test/registered/unit/managers/test_schedule_batch_req_pool_indices.py -v
# 17 passed, 8 subtests passed

Attribution & Acknowledgements

This is a self-discovered performance optimization found by profiling ScheduleBatch, SchedulerBatchResultProcessor, and RankMetadata. Special thanks to the SGLang scheduler, chunked-prefill, and HF3FS HiCache storage authors and maintainers (including @ayw-sirius, @merrymercy, @zhyncs, and @hnyls2002) for designing the batch result processor and HiCache metadata architecture.

Checklist


CI States

Latest PR Test (Base): ❌ Run #44207604854
Latest PR Test (Extra): ❌ Run #44207601682
Latest PR Test (AMD ROCm 10): ⊘ Skipped -- add the run-ci label to run CI tests.

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

@github-actions

This comment has been minimized.

@deep1blue deep1blue changed the title [Perf] Replace O(B^2) request and page list scans in ScheduleBatch.filter_batch, BatchResultProcessor, and RankMetadata [Perf] scheduler/hicache: Replace O(B^2) request and page list scans in ScheduleBatch.filter_batch, BatchResultProcessor, and RankMetadata Oct 24, 2026
detain added a commit to detain/sglang that referenced this pull request Oct 29, 2026
[Perf] scheduler/hicache: Replace O(B^2) request and page list scans in
ScheduleBatch.filter_batch, BatchResultProcessor, and RankMetadata.
id-keyed sets replace 'in list' scans (O(B^2) -> O(B)) in the prefill
result loop and free-page release paths. git apply -3 clean on all
4 files; no stack-local drift in the touched regions.

CPU: test_schedule_batch_req_pool_indices 3P; batch_result_processor
quartet + schedule_batch_mixed_mamba_track 31P/17sub.

(cherry picked from commit 4b57095434504d3b7869083ac920875315c41307)
(cherry picked from commit b1de9ff1009004b2082b7352347f97a33bb0d616)
detain added a commit to detain/sglang that referenced this pull request Oct 29, 2026
…(entries 265-266)

First of TWO admission docs commits (267-270 follow at wave end). Records
the auto-merge semantic audit at the sgl-project#46272 x batch-1 interlock (gate
counts byte-invariant, quartet 24P/17sub) and the four sgl-project#43484 mandated
items: upstream ImportError bug caught, components/mamba.py supersession
by entries 197/198/216 with OUR retry semantics kept, isinstance-not-
hasattr gate (MagicMock ledger, 32 mis-fires), dedicated slot-charge
space + commit-path debit threading.
detain added a commit to detain/sglang that referenced this pull request Oct 30, 2026
…s 94,95,119,122,169,215,262,263,265 (re-plant + verified-absorbed)

3 markers consumed (batch B4 total now 23-1-3=19; briefing's '20' was the
session-1 census -- true tree count is 23, per the B3 census lesson).

RE-PLANTED (batch_result_processor.py, from its fork-hunks patch):
- _logprob_rows_to_host tensor-or-placeholder converter + 3 call sites
  (the mixed-batch per-row mixed-type class; damage: 3F).
- Entry 265 (sgl-project#46272, OPEN port -- VERIFIED NOT MERGED in-range): the
  decoding_req_ids lazy {id(r)} set replacing the three O(B) 'req in
  batch.decoding_reqs' scans in the prefill-result loop. The entry-265
  interlock holds: the re-planted set feeds the SAME branch that
  mamba_untracked_decode_batch_idx gates, and that gate landed byte-
  present upstream via sgl-project#45435 (schedule_batch x3 + brp x1 references
  audited) -- the byte-count invariant of the merge point is preserved.

VERIFIED-ABSORBED (markers consumed, NO edits -- the merged tree already
carries the semantics, hunk-a-hunk against the 309-tip):
- schedule_batch.py (no fork-hunks patch existed; tsv DRIVER class was
  TRIAGE-UNION all-mechanical, so the audit was semantic): sgl-project#45435's
  mamba_lazy_undo_prealloc_at_boundary x2, _mamba_track_for_mixed DELETED
  (0 refs) with upstream's -1 tail padding + freed_rows->-1 guard carried
  VERBATIM (entry 263(a)), sgl-project#45472's _gather_mamba_track_indices x3 +
  pinned async_h2d track tensors + mamba_ping_pong_empty host mirror x4 +
  the collapsed single set_mamba_track_indices_from_reqs, holds_kv x4
  (sgl-project#44401), untracked_decode_batch_idx x3. Entry 119's supersession by the
  sgl-project#45435 upstream form CONFIRMED (32c2678 in-range per git log
  12dc623..2a6c204 -- this is the merge's own absorption of our
  entry-262 pick).
- mm_utils.py: entry 263(b)'s UNION was superseded IN-RANGE by upstream
  landing the plural padding_values() (pad_values or (pad_value,) --
  exactly the fork's scalar source degenerate case) with the sorted
  invariant; _get_multimodal_mask (mm_schedule.py:655) is the sgl-project#45472
  searchsorted no-sync form fed by that sortedness contract.
- brp's _mamba_can_cache_finished_req gate + mamba_ping_pong_empty mirror
  consumption x2 + the two rich FINISH_ABORT sites + the
  untracked_decode_batch_idx advance gate: PRESENT upstream.

TEST RE-ANCHORS (mixed_mamba_track, contract-driven, per entry 198's
fixture-adaptation precedent; NOT production):
- CacheInitParams tree_components kwarg -> tree_slots_of((FULL, MAMBA))
  (#46970x: slots drive components),
- allocator.state = req_to_token_pool.state -- production's equivalent is
  the configurator's runner_state() bind (kv_cache_configurator:553); a
  manual classic build must bind too or ensure_mamba_capacity (#46970x
  seam) reads state=None (diagnosed: NOT a fork-delta loss, NOT
  upstream-own -- upstream binds in prod; fixture bypass),
- backend._state_ids identity IdSpace stub (runner_ids seam; classic
  pools index slots directly -- matches production for this config).

ACTUALS (damage -> after, CVD=9, prod venv, per-file):
  test_schedule_batch_mixed_mamba_track 7F -> ** 7P EXACT (262 pin) **
  test_batch_result_processor_mixed_token_ids_logprob 3F -> ** 3P **
  brp family (mamba_boundary, spec_grammar) + mix_with_running: 33P/17sub
  GREEN incl. the entry-265 quartet proof.
  DIR: unit/managers 1025P/83F/9S/427sub -> ** 1048P/48F/9S/439sub **
  (remaining 48F = prefill_adder 39F + dcp_logical 7F [both B4-3's pricing
  reconciliation] + the two known order-dependent test_mm_process_config
  F's [env class, reproduce at base]).
Lint: ruff format + F821/E9 clean; 3 EOF-marker artifacts the merge left
(schedule_batch/mm_utils/brp trailing comments) resolved by the marker
removals. No GPU; no push.

Co-Authored-By: OpenCode <[email protected]>
@deep1blue
deep1blue force-pushed the perf/batch-filter-and-hf3fs-metadata-set branch from 4b57095 to c5d71f7 Compare November 4, 2026 16:16
…Processor, and RankMetadata

Signed-off-by: Parth Vadera <[email protected]>
Co-authored-by: Copilot <[email protected]>
Signed-off-by: Parth Vadera <[email protected]>
@deep1blue
deep1blue force-pushed the perf/batch-filter-and-hf3fs-metadata-set branch from c5d71f7 to 1b2ba90 Compare November 7, 2026 16:32
detain added a commit to detain/sglang that referenced this pull request Nov 11, 2026
…arkers consumed; both named classes dead

- brp sgl-project#46272 id-set RE-PLANTED at the two sites the take-upstream reverted to
  O(B) req-in-list scans: the finish-side _prepare_kv_cache_release predicate
  and the checkpoint elif now consume the per-row is_decoding_req id-set (the
  sgl-project#49253 deferred kv_ops shape kept -- fork predicate onto upstream structure;
  entry-265 interlock re-verified: mamba_untracked_decode_batch_idx + its brp
  arm were DELETED upstream by sgl-project#48328 (02db123) together with the
  next==last hazard they guarded -> ADOPTED, mixed_track tests re-pinned).
- detokenizer: ADOPTED sgl-project#47338 (add6f6d) state-machine move; the fork's
  sent_offset anti-retreat max() clamp RE-PLANTED at its new home
  (DetokenizeState.step) -- test_detokenizer_stream_offsets.py 6F -> 7P/3sub,
  driving _update_detokenize_states + the header-seeded state table.
- io_struct: ADOPTED upstream's env-bounded validate_n gate (sgl-project#44047
  b2616ca subsumes the entry-157 static-128 loop; both validator helpers
  stay unit-tested in test_sampling_params) -- the dossier's
  'entry-265 brp track field' label on region@551 is a misattribution
  (the field never lived in io_struct; verified by fork-delta audit).
  4 fork-era normalization tests re-pinned to the new contract
  (above-max bound, null-n, beam message, per-element bound).
- tokenizer_manager: DEDUPE candidate resolved as the union -- upstream's
  return_logprob gate (the mask-validation tests prove the disabled-row
  design) + the fork's shared validate_top_logprobs_num delegation; the
  fork-era io_struct top_logprobs test re-pinned to return_logprob=True.
- brp mixed_token_ids_logprob ctor seam: enable_overlap fields retired by
  sgl-project#49019 (d1d317c); harness follows the merged class (still_in_batch,
  kv_weight_version_tracker, request_retirer, forward_iter,
  still_in_batch_rows, real LogprobResultProcessor). 3P.
- test_sampling_params test_beam_n_below_one_raises message regex re-pinned
  (validate_n now fires before the beam branch); its sibling
  test_n_bounds vs test_n_above_max_raises double-gate tension in
  sampling_params.verify is PRE-EXISTING cascade damage (union of both
  gates), outside every battery dir -- handed to B6 (env registration).

Targeted: 158P + 128sub (io_struct+mask+rid+brp+detok) + sampling sweep.
Gates: ruff repo ruleset + format; registration trio rc=0.

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

hicache Hierarchical Caching for SGLang

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant