Skip to content

[None][fix] prevent multimodal scheduling stalls on the KV cache V2 scheduler - #19801

Merged
yechank-nvidia merged 1 commit into
NVIDIA:mainfrom
yechank-nvidia:fix/multimodal-v2-scheduler-stall
Oct 8, 2026
Merged

yechank-nvidia merged 1 commit into
NVIDIA:mainfrom
yechank-nvidia:fix/multimodal-v2-scheduler-stall

Conversation

@yechank-nvidia

@yechank-nvidia yechank-nvidia commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Dev Engineer Review

MultimodalScheduler now prioritizes resident-output holders when an unstarted request cannot fit within the output-byte budget. It spends encoder budgets in admission order while preserving the combined scheduler’s LLM batch order. When output capacity blocks a context, it releases that context’s KV-cache admission; contexts blocked only by encoder slots or tokens keep their admission.

KVCacheV2Scheduler.release_context_admission frees the request’s allocations from configured KV-cache managers and rewinds its context cursor. RequestScheduler provides a default no-op hook for schedulers that do not allocate KV cache during scheduling. Verify that custom schedulers using this path implement the hook if they allocate resources. The current changes target the item-scheduled multimodal path with KV cache V2.

QA Engineer Review

The changes add four unit tests in tests/unittest/_torch/executor/test_multimodal_scheduler.py. They cover encoder-budget ordering, starvation of partially encoded work, progress by newer requests while output capacity is blocked, and retaining KV cache when only an encoder slot blocks a request. The helper updates in multimodal_utils.py support configurable prompt and embedding lengths.

No reference to test_multimodal_scheduler appears in the inspected tests/integration/test_lists/ files. These are unit tests, and no integration-list change is included. The provided context reports that the changed test file passes, but no test execution result was supplied in this inspection. Coverage verdict: sufficient for the reported stall scenarios; it does not establish that broader test suites pass.

Per-File QA Perspective

  • tensorrt_llm/_torch/pyexecutor/scheduler/scheduler.py: Verify holder-first ordering, admission-order encoder selection, preserved LLM batch ordering, and KV-cache release only for contexts blocked by output capacity.
  • tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py: Verify that releasing admission frees resources across target, draft, and cross-KV managers and rewinds the context cursor. Failed first-chunk admissions now use the same method.
  • tests/unittest/_torch/executor/multimodal_utils.py: Verify that prompt_len and embedding_lengths generate consistent token inputs and multimodal metadata. These helpers have new optional parameters and defaults.
  • tests/unittest/_torch/executor/test_multimodal_scheduler.py: Four new tests cover the combined V2 scheduler’s ordering, output-budget waits, and encoder-slot waits. No matching integration test-list reference was found.

Description

Problem. For multimodal models on KV cache manager V2, MultimodalScheduler wraps KVCacheV2Scheduler. V2 has no separate capacity stage, so the wrapper takes its combined path: V2 schedules the batch, then the wrapper selects MM encoder items among V2's context requests and withholds contexts that would still lack embeddings. By then V2 has already admitted each of those contexts: it charged the token budget and a request slot, and grew the context's KV cache. This allows two permanent stalls on main. Neither reports an error: the executor keeps scheduling empty batches, V2's deadlock check only looks at generation requests, and the hang detector stays quiet because the loop keeps iterating.

  1. A newer request takes the encoder budget, and a withheld older context pins KV cache. This is the first new test: FCFS chunked prefill, max_num_tokens=60, an 80-token KV pool, 2 encoder slots and a 12 B output budget (3 embedding rows).
    • Requests: A (10-token prompt, one 1-row image), B (40 tokens, images of 2 and 1 rows, the whole output budget), C (80 tokens, two 1-row images).
    • Pass 1: V2 admits all three and returns them as [C, A, B], because it puts non-last chunks first. The wrapper visits C first, and C's images take both encoder slots. A and B are withheld, but they keep the 50 KV tokens V2 grew for them.
    • A runs in pass 2. B never fits beside C's outputs, yet V2 re-admits it every pass, so it keeps its 40 tokens.
    • From pass 4, C's next chunk cannot grow: C holds 40 tokens, B holds 40, and the pool is full. Nothing in V2 frees B's KV cache for C's chunk, so B and C never finish.
  2. An older context that cannot start encoding starves a newer, partially encoded request. This is the second new test: FCFS chunked prefill, max_num_tokens=50, a 100-token KV pool, 1 encoder slot and a 32 B output budget (8 rows). Running decodes hold 60 KV tokens in pass 1 only.
    • Requests: A (80 tokens, one 1-row image), B (20 tokens, two 4-row images, the whole budget), T (70-token text request).
    • Pass 1: A's 50-token chunk does not fit beside the decodes, so V2 skips it. B is admitted and its first image is encoded, so B now holds the whole output budget.
    • From pass 2, V2 admits A's 50-token chunk first, and that uses the entire token budget. B is never scheduled again, so it never gets its second image, and A cannot start encoding while B's outputs fill the budget. Nothing finishes.
    • Without chunked prefill the same deadlock happens through V2's token-budget STOP.

Both examples admit every request in the first pass. That happens under attention DP, which skips the executor's MM admission gate (_apply_mm_encoder_admission). With the gate, these exact inputs finish on main, because the gate defers the newer requests. The stalls then need staggered arrivals: 7 of 3000 fuzz cases and 6 of 600 stress cases in check 1 below.

Root cause.

  • The wrapper selects items in the order V2 returns, which puts non-last chunks first. _select_items assumes FCFS order.
  • A withheld context keeps the KV cache V2 grew for it. V2 never preempts one context for another: eviction and recompute-pause run only for generation requests.
  • V2 charges the token budget and KV cache to a context before the wrapper can tell that the context cannot start encoding.

Fix. The change is confined to the combined branch of MultimodalScheduler.schedule_request, plus a behavior-preserving extraction in V2:

  • Holders first. Find the oldest request whose outputs cannot fit beside the outputs that live requests already hold. The requests holding outputs behind it are passed to V2 ahead of it (_holders_first), so it cannot take the token budget they need to drain. Everything else keeps FCFS order, and no request is removed from V2's input.
  • Admission order. _select_items visits V2's admitted contexts in active_requests order. The LLM batch keeps V2's order.
  • Release. A withheld context that holds no encoder outputs, and whose whole embedding cannot fit beside the bytes held after this pass, releases its KV cache through KVCacheV2Scheduler.release_context_admission. That method is V2's existing cleanup for failed first-chunk admissions, moved into a method unchanged. A context withheld only for encoder slots or tokens keeps its admission, as on main; FCFS serves it next.
  • RequestScheduler.release_context_admission is a no-op by default, so the wrapper needs no type checks.

Hiding the blocked request from V2 also fixes stall 2. But newer requests can then start ahead of it and deadlock with it in V2's KV cache, unless they are hidden too, which holds back text requests. Passing the holders first keeps every other request where it is.

Why it is safe.

  • Only the combined path changes. That path is taken only when the wrapped scheduler has no separate capacity and microbatch stages, which today means KVCacheV2Scheduler. The separate-stage path, MultimodalEagerEncoderScheduler, the executor and the LLM args are untouched.
  • V2's own admission behaves exactly as before. Its diff is the extracted cleanup.
  • The reorder only moves requests that hold encoder outputs ahead of a request that cannot start encoding until they drain. Newer requests that hold nothing stay behind it in V2's order.
  • A released context holds no encoder outputs and has not run a chunk, because a context runs only once its embeddings are ready. V2 already frees contexts in this state after a failed first-chunk admission, and the next pass re-admits it from a fresh prefix match. With a KV connector, free_resources releases its unstarted prefix reservation, as release_unused_connector_reservations already does for contexts excluded from the batch.
  • Two randomized checks (scratch scripts, not part of this PR) compared this change with unmodified main. Both drive the real KVCacheV2Scheduler, MultimodalScheduler, request admission and admission gate over a toy KV pool.
    • Check 1 has staggered arrivals and models decodes as fixed KV holds: 3000 fuzz and 600 stress cases (including FORCE_CHUNK), each with and without the gate. Multimodal stalls went from 7 and 37 (fuzz) and from 6 and 27 (stress) to 0. 15 stress cases deadlock in V2's KV cache on main and with this change; with the gate they are the same 15. Without the gate, one main multimodal stall (seed 104) ends in a V2 KV deadlock instead, and one main V2 KV deadlock (seed 321) now finishes. No case that finishes on main stalls.
    • Check 2 adds decode growth with V2's evict, recompute-pause and self-evict paths, an optional host tier, cancellations, small LLM batch limits and streaming arrivals, with the gate on or off at random. Over 2400 burst and 1000 streaming cases, 44 cases stall on main and finish with this change, and 4 go the other way. Those 4 are V2 KV deadlocks that main avoids only by timing: in 2, two decodes outgrow a pool with no host tier and V2 cannot recompute-pause the multimodal one; the other 2 are the partially encoded holder pattern in Limitations. Any change to admission timing moves V2 KV deadlocks between cases in both directions.

Behavior changes.

  • On V2, the encoder budget is spent in FCFS order, and the keys of scheduled_mm_encoder_items follow that order.
  • While the output budget blocks a request, the requests holding outputs behind it get V2's token budget and KV cache before it. V2 looks for eviction and recompute-pause victims from the end of its request list, so those holders are also picked as victims later than on main.
  • A context that the output budget blocks is admitted by V2 and released again in each pass until it can start encoding. Each cycle is a KV cache create, prefix match and free: 31-52 us per context per pass on a real KVCacheManagerV2, against 2-3 us for main's re-admission of a context that kept its KV cache. Contexts withheld for encoder slots or tokens are not affected.
  • The combined branch costs more host time per pass. I measured it over a V2 scheduler with a near-free KV stub, so V2's own cost is a lower bound; the numbers are medians of 5 runs on a shared host. At 1024 active text-only requests the extra time is +38 us (+3.3%), and +75 us (+6.4%) with MM outputs resident. At 4096 requests it is +3.5% and +7.9%.

Scope.

  • The change affects item-scheduled multimodal models on KV cache manager V2. By default that is Qwen3.5-VL and Qwen4Exp-VL: both prefer V2, inherit supports_mm_encoder_item_scheduling from Qwen3VLModelBase, and default to the DEFAULT encoder scheduling policy. It also covers any item-scheduled model run with use_kv_cache_manager_v2=True.
  • For these hybrid models, block reuse (on by default) switches context chunking to FORCE_CHUNK (py_executor_creator.py). V2 therefore returns multi-chunk contexts even without enable_chunked_prefill.

Limitations (unchanged by this PR).

  • V2 never preempts one context for another, and its deadlock check covers only generation requests. Two started contexts can therefore still deadlock in V2's KV cache under pressure, with or without images. These are the 15 stress cases above.
  • A partially encoded context keeps the first-chunk KV cache V2 grew for it. If an older decode then cannot grow and has no other victim, it self-evicts and stops V2's generation phase in every pass. The holder is then never reached, never finishes encoding, and the decode never fits. V2's deadlock check does not fire, because a request is evicted in each pass. This happens on main as well. A V2 follow-up could let the generation eviction path suspend such contexts.
  • A blocked or partially encoded context still takes V2's token budget for its chunk in each pass, as on main.

Relation to #17876. I found this while reviewing #17876 (multimodal encoder cache unification), but the bug exists on main. #17876 does not touch scheduler_v2.py and keeps the same combined branch, so the port there is a small follow-up: "holds encoder outputs" becomes "holds encoder-cache entries", and the byte check becomes a read-only capacity query on its TensorLRUCache.

Test Coverage

New tests in tests/unittest/_torch/executor/test_multimodal_scheduler.py. They are CPU-only and drive a real KVCacheV2Scheduler with a mock KV pool. They run in the unittest/_torch/executor entries of the GPU stages, like the rest of the module. Results are the finish pass per request id.

  • test_v2_chunked_prefill_spends_encoder_budget_in_admission_order (stall 1): {1: 2} on main, where B and C never finish; {1: 1, 3: 3, 2: 4} with this PR.
  • test_v2_partially_encoded_request_is_not_starved_by_older_context (stall 2): {} on main; {2: 2, 1: 4, 3: 5} with this PR.
  • test_v2_output_budget_wait_does_not_hold_back_newer_requests: a text request that arrives while an MM request waits for output bytes finishes in pass 2, as on main.
  • test_v2_context_that_lost_the_encoder_slot_keeps_its_kv_cache: a request that waits only for the encoder slot keeps its KV cache while decodes grow, and finishes in pass 3, as on main.
  • The last two tests pass on main too. They pin the two properties that the alternatives above would break: hiding the newer requests delays the text request to pass 5, and releasing every withheld context delays the second request to pass 5.
  • Disabling one part at a time in a scratch script: without the holders-first order, both stall tests stall; without the release, the stall-1 test stalls; without the admission-order visit, the stall-1 test fails because the oldest request finishes a pass late.
  • tests/unittest/_torch/executor/multimodal_utils.py: make_llm_request and make_mm_request take an optional prompt length and embedding lengths, so the new tests reuse them. Existing callers are unchanged.

Commands, run in the dev container on the PostMerge build that matches 95cb50c358:

  • pytest tests/unittest/_torch/executor/test_multimodal_scheduler.py with scheduler.py and scheduler_v2.py from main: the two stall tests fail as above; the other 40 tests pass. With this PR all 42 pass.
  • pytest tests/unittest/_torch/executor/test_multimodal_scheduler.py tests/unittest/_torch/executor/kv_cache/test_kv_cache_v2_scheduler.py tests/unittest/_torch/executor/engine/test_multimodal.py tests/unittest/_torch/executor/test_scheduler_serializable_output.py tests/unittest/_torch/executor/test_recompute_pause.py tests/unittest/_torch/executor/test_py_scheduler.py tests/unittest/_torch/executor/kv_cache/test_dual_pool_kv_cache.py tests/unittest/_torch/executor/test_kv_connector_v2_prefix_real_manager.py: 498 passed.
  • The GPU V2 suites under tests/unittest/_torch/executor/ (kv_cache/test_kv_cache_manager_v2_helix_superblock.py, kv_cache/test_kv_cache_v2_{capacity_only,extra_buffers,first_new_block_probe,multimodal_runs,vocab_size}.py, kv_cache/test_kvv2_host_tier_sizing.py, test_kv_connector_v2_prefix.py, test_token_budget_fallback.py): 196 passed. The 11 failures in test_kv_cache_v2_vocab_size.py are pre-existing and waived under nvbugs/6818710.
  • Real-model checks (scratch scripts) with Qwen3.5-0.8B on 1x H200: V2 by default, block reuse on (so FORCE_CHUNK), enable_chunked_prefill=True, max_num_tokens=256, encoder_max_batch_size=1.
    • Default path, 6 image and 2 text requests: all 57 passes went through MultimodalScheduler over KVCacheV2Scheduler; 22 had multi-chunk contexts, and in 5 V2's context order differed from FCFS. All requests completed, token-identical to main.
    • Contention, with the admission gate bypassed as under attention DP and the output budget shrunk to two requests' outputs; 12 small color-image and 2 text requests. All 14 completed and all 12 colors were correct. The wrapper released 19 withheld contexts through release_context_admission on the real MambaHybridCacheManagerV2. main also completed; 13 of 14 outputs match, and one text answer reads "two" instead of "2", consistent with a different batch composition. With the gate on, the outputs match main exactly.
    • The holders-first order did not trigger in these runs, because the holders were always older than the blocked requests. The stall-2 test and the randomized checks cover it.
  • pre-commit run --files <changed files>: all hooks pass.

PR Checklist

Please review the following before submitting your PR:

  • PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.

  • PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.

  • Test cases are provided for new code paths (see test instructions)

  • If PR introduces API changes, an appropriate PR label is added - either api-compatible or api-breaking. For api-breaking, include BREAKING in the PR title.

  • Any new dependencies have been scanned for license and vulnerabilities

  • CODEOWNERS updated if ownership changes

  • Documentation updated as needed

  • Update tava architecture diagram if there is a significant design change in PR.

  • The reviewers assigned automatically/manually are appropriate for the PR.

  • Please check this after reviewing the above items as appropriate for this PR.

GitHub Bot Help

To see a list of available CI bot commands, please comment /bot help.

🤖 Generated with Claude Code

…cheduler

KVCacheV2Scheduler has no separate capacity stage, so MultimodalScheduler
schedules the V2 batch first and then selects MM encoder items among the
contexts V2 returned. By then V2 has charged each context to its token
budget and grown its KV cache, which allows two permanent stalls:

- V2 returns non-last chunks first. With chunked prefill, a newer
  multi-chunk request therefore takes the encoder budget ahead of older
  requests. A withheld older context whose outputs cannot fit beside the
  newer request's keeps the KV cache V2 grew for it, which the newer
  request needs to finish its prefill.
- A context that cannot start encoding while live outputs fill the
  output budget still takes V2's token budget every pass. A newer,
  partially encoded request that holds those outputs is then never
  offered its remaining items.

On this combined path MultimodalScheduler now:

- passes the requests that hold encoder outputs to V2 ahead of the
  oldest request the output budget blocks, so that request cannot take
  the token budget they need to drain. Everything else keeps FCFS order.
- selects items over V2's contexts in admission order, and keeps V2's
  order for the LLM batch.
- releases the KV cache of a withheld context that the output budget
  blocks. This reuses V2's failed-admission cleanup, extracted as
  KVCacheV2Scheduler.release_context_admission. A context that only lost
  the race for encoder slots or tokens keeps its KV cache, as before.

Add CPU tests over a real KVCacheV2Scheduler: one per stall, one showing
that a request waiting for output bytes does not hold back newer ready
requests, and one showing that a context that lost the encoder slot
keeps its KV cache. The shared MM request fixtures take a prompt length
and embedding lengths so the tests can reuse them.

Signed-off-by: yechank <[email protected]>
@yechank-nvidia
yechank-nvidia marked this pull request as ready for review October 6, 2026 05:06
@yechank-nvidia
yechank-nvidia requested a review from a team as a code owner October 6, 2026 05:06
@coderabbitai

coderabbitai Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: NVIDIA/TensorRT-LLM/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Enterprise
  • Run ID: d0ccdc9f-1628-4748-a02a-f74bcfba0fe7
📥 Commits

Reviewing files that changed from the base of the PR and between 8a3c903 and 62e8275.

📒 Files selected for processing (4)
  • tensorrt_llm/_torch/pyexecutor/scheduler/scheduler.py
  • tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py
  • tests/unittest/_torch/executor/multimodal_utils.py
  • tests/unittest/_torch/executor/test_multimodal_scheduler.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.


Walkthrough

Changes

Multimodal scheduler budget control

Layer / File(s) Summary
Context admission cleanup
tensorrt_llm/_torch/pyexecutor/scheduler/scheduler.py, tensorrt_llm/_torch/pyexecutor/scheduler/scheduler_v2.py
Schedulers now expose release_context_admission. KVCacheV2Scheduler uses it to release resources and rewind the context cursor when first-chunk admission fails.
Output-budget ordering
tensorrt_llm/_torch/pyexecutor/scheduler/scheduler.py
MultimodalScheduler accounts for resident encoder-output bytes, reorders blocked requests, reuses computed byte totals, and releases context admissions that remain blocked after selection.
Combined scheduler validation
tests/unittest/_torch/executor/multimodal_utils.py, tests/unittest/_torch/executor/test_multimodal_scheduler.py
Tests add configurable prompt and embedding lengths, shared KV-capacity simulation, context progression, and output-budget ordering scenarios.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant KVCacheV2Scheduler
  participant MultimodalScheduler
  participant KVCacheManagerV2
  KVCacheV2Scheduler->>MultimodalScheduler: Provide active contexts
  MultimodalScheduler->>KVCacheManagerV2: Read resident KV allocations
  MultimodalScheduler->>MultimodalScheduler: Reorder requests by output budget
  MultimodalScheduler->>KVCacheV2Scheduler: Release blocked context admission
  MultimodalScheduler->>KVCacheManagerV2: Record selected encoder allocations
Loading

Suggested reviewers: bowenfu

Merge Risk: ⚪ Minimal · up to 62e82

The new tests cover the reported scheduling stalls and admission cleanup. No demonstrated issue currently blocks merging after normal checks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 51.85% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 27 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title follows the repository format and clearly summarizes the main change: preventing multimodal scheduling stalls with KV cache V2.
Description check ✅ Passed The description includes the required Description and Test Coverage sections. It explains the problem, fix, scope, limitations, and tests, and includes the PR checklist.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@yechank-nvidia

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #76316 [ run ] triggered by Bot. Commit: 62e8275 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #76316 [ run ] completed with state SUCCESS. Commit: 62e8275
/LLM/main/L0_MergeRequest_PR pipeline #62921 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

CI Agent Failure Analysis

Link to invocation

@yechank-nvidia

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #76391 [ run ] triggered by Bot. Commit: 62e8275 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #76391 [ run ] completed with state SUCCESS. Commit: 62e8275
/LLM/main/L0_MergeRequest_PR pipeline #62986 completed with status: 'SUCCESS'

CI Report

Link to invocation

@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown

Automatically added "ci: full pre-merge approved" because this PR has satisfied the required GitHub review approvals. Unresolved review conversations and other required checks remain independent merge requirements.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants