Skip to content

[None][fix] Support chunked prefill and KV cache reuse for Gemma 3 and Llama 4 images and keep Gemma 4 images whole - #22886

Draft
yechank-nvidia wants to merge 6 commits into
NVIDIA:mainfrom
yechank-nvidia:yechank/legacy-mm-feature-guards
Draft

yechank-nvidia wants to merge 6 commits into
NVIDIA:mainfrom
yechank-nvidia:yechank/legacy-mm-feature-guards

Conversation

@yechank-nvidia

@yechank-nvidia yechank-nvidia commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Why

On main, Gemma 3 and Llama 4 fail in fusion when a cache hit or chunk boundary leaves fewer image tokens in the current prefill than the image embeddings they supply. A Gemma 3 cache hit that ends before the image passes fusion and then fails the mask code's assertion that the cached prefix is empty. On Gemma 3 and bidirectional Gemma 4 models, splitting an image also prevents earlier tokens from attending to the whole image.

Changes

  • Select the active image embeddings on Gemma 3 and Llama 4. Gemma 3 includes the cached prefix in its masks. Llama 4 can resume inside an image and uses the processor’s patch counts to key each tiled image.
  • V2 clips cache hits and picks chunk ends outside declared bidirectional spans. An image-only rematch preserves the mixed-precision back-off. A late connector offer can advance only the left edge of the scheduled chunk for every flagged request. Image KV reuse requires content-aware connector keys. [TRTLLM-12407][fix] Pass mRoPE state and image hashes from prefill to decode in disaggregated serving #20949 tracks prefill-to-decode identity.
  • Closely spaced Gemma 3 images with no aligned cut between them form one interval under the 256-token sliding-window chunk unit. A pass must have room for that interval after decode.

Behavior changes for other models

  • Gemma 4 26B, 31B and Unified use the same V2 boundary rule. Unified’s causal audio still shares the vision span declaration. [None][feat] Add a multimodal model protocol and CPU checks for required runtime features #20906 tracks separate declarations.
  • Admission reports the minimum token budget for an indivisible interval and checks resident encoder-output capacity. V1 rejects bidirectional multimodal requests that run prefill locally with chunking enabled. Use the V2 KV cache manager, removing any setting that forces a fallback to V1 (such as sleep_config), or set enable_chunked_prefill=False. Text-only and generation-only requests remain eligible.
  • Shared hashing skips empty and None media buckets. A text request with an empty bucket preserves hashing for the next request. Gemma 3 and Llama 4 require hashing on supported media inputs and surface errors. A single unframed modality can now use matching processor-supplied embedding lengths as its per-item token counts.

Merge order

Known limits

On main, a first Gemma 4 26B request with tuple-image input can disable hashing for later requests. In a CPU check, two different images then produced identical V2 keys. Multimodal KV reuse stays No for Gemma 4 26B and 31B.

Test Coverage

1,583 distinct CPU cases passed. The PyExecutor admission test rejects an image request that needs chunked prefill on V1 and accepts a generation-only request with the same image spans. The incomplete-window regression rematched from 1,152 to 1,024 and then to 512. The Gemma 4 31B encoder-budget fixture still exercises eight images across multiple encoder steps with its original budgets.

In correctness screening on one shared GB200, Gemma 3’s 320-token hit inside [66, 322) resumed at 66 with partial reuse and 64 with whole blocks. Decoder inputs and masks matched exactly. Gemma 3 FlashInfer suffix logits matched at three prefix depths with atol=rtol=0.01. Llama 4 matched at hits of 32, 96 and 128, and both local and attached CUDA tests passed. The forward cases use the existing H100 model suites and the Llama 4 B200 suite.

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.

@yechank-nvidia

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #87161 [ run ] triggered by Bot. Commit: a13f34e Link to invocation

@yechank-nvidia

Copy link
Copy Markdown
Collaborator Author

/bot kill

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #87194 [ kill ] triggered by Bot. Commit: a13f34e Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #87161 [ run ] completed with state ABORTED. Commit: a13f34e

Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #87194 [ kill ] completed with state SUCCESS. Commit: a13f34e
Successfully killed previous jobs for commit a13f34e

Link to invocation

@yechank-nvidia

Copy link
Copy Markdown
Collaborator Author

@trtllm-agent-review please help review it

@trtllm-agent-review

Copy link
Copy Markdown
Collaborator

Thanks, @yechank-nvidia. @trtllm-agent-review starts its reviews at fixed times, every day at 02:00, 08:00, 14:00 and 20:00 Beijing time (04:00, 10:00, 16:00 and 22:00 Pacific time). It will pick up this request at the next one, 02:00 Beijing time on Dec 1 (10:00 Pacific time on Nov 30), and start its review then.

@trtllm-agent-review trtllm-agent-review 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.

Thanks for the PR. Turns chunked prefill and KV block reuse off by default for Gemma 3 VLM and Llama 4 checkpoints, rejects an explicit opt-in to either at startup, and stops trtllm-eval from forcing block reuse on.

Reviewed at commit a13f34e053 (6 files, +107/−19).

Request changes: 4 Blockers need fixing before merge.

Blockers (4)

  • (B4: API or compatibility break) Default trtllm-bench throughput on any Gemma 3 VLM or Llama 4 checkpoint now fails at startup: the bench passes enable_chunked_prefill=True on every run, text-only runs included. (modeling_multimodal_utils.py:649)
  • (B4: API or compatibility break) Every Llama 4 deployment, text-only ones included, now fails at startup when it enables chunked prefill or block reuse, which supported-models.md lists as supported for Llama 4 language-only requests. (modeling_llama.py:1553)
  • (B5: User-visible switch behavior) KV block reuse is now off by default for every Llama 4 and Gemma 3 VLM deployment, text-only serving included, so the documented Llama 4 Scout recipe silently loses prefix caching. (modeling_multimodal_utils.py:663)
  • (B4: API or compatibility break) The default quickstart_multimodal.py / quickstart_advanced.py run on Gemma 3 VLM or Llama 4 now fails at startup: setup_llm still sets enable_block_reuse=True explicitly. (eval.py:190)
Nice to have (5): 5 inline, 0 below
  • (R4: Bypassing framework mechanisms) The guard disables two features model-wide instead of using the multimodal slicing path the other VLMs use (get_multimodal_embeddings + find_input_mm_embeds, and mm_bidirectional_blocks for Gemma 3). (modeling_multimodal_utils.py:646)
  • (N7: Robustness hardening) Block-reuse sub-options set without enable_block_reuse fail with an error that tells the user to set enable_block_reuse=True, which this helper then rejects. (modeling_multimodal_utils.py:655)
  • (N3: Missing or ineffective tests) Tests: the trtllm-eval change is untested, the rejection tests accept any ValueError, and test_config_database.py's shallow update drops nested defaults. (eval.py:190)
  • (R6: Required documentation) supported-models.md still lists Chunked Prefill and KV Cache Reuse as Yes for Llama 4 language-only requests, and no doc states the new restriction. (modeling_gemma3vl.py:3)
  • (N5: Code tidiness) Tidiness in full_image_prefill_defaults: a no-op chunked-prefill check and default, and a docstring that does not state the helper's contract. (modeling_multimodal_utils.py:648)
What this review checked
  • Explicit opt-outs and partial KV configs keep their values: apply_model_defaults_to_llm_args merges model defaults under user-set fields (tensorrt_llm/llmapi/llm_utils.py:537-566), which the new free_gpu_memory_fraction case of test_legacy_multimodal_prefill_defaults asserts.
  • trtllm-eval --disable_kv_cache_reuse still wins over a YAML enable_block_reuse: true: the attribute assignment marks the field as set and update_llm_args_with_extra_dict keeps explicit CLI values (tensorrt_llm/llmapi/llm_args.py:10543-10552); without the flag, eval now resolves block reuse as trtllm-serve does.
  • The new tests would fail on the base revision and run pre-merge: TestModelDefaults is cpu_only and tests/integration/test_lists/test-db/l0_cpu.yml lists unittest/llmapi/test_llm_args.py.
  • Not covered: No GPU run: the startup rejections and the split-image failure were traced in code, not reproduced.
  • Not covered: No local test run: the review environment has no built tensorrt_llm bindings.
  • Not covered: Other open PRs were searched by keyword only.

Automated review by trtllm-agent-review. If a point is wrong, reply in its thread. Once you have pushed code changes and replied in every Blocker thread, the bot re-checks the Blockers within a few hours. A Blocker you think should not be fixed needs no code change: reply in its thread with the reason and the evidence.

Comment thread tensorrt_llm/commands/eval.py Resolved
Comment thread tensorrt_llm/commands/eval.py Resolved
@trtllm-agent-review

Copy link
Copy Markdown
Collaborator

What this PR changes, by code owner

For each code owner (a team or a person) of files this PR changes: what it changes there. The review above has the findings.

trt-llm-models-devs · 3 files
Gemma3VLM and Llama4ForConditionalGeneration default chunked prefill and KV block reuse to off and raise UnsupportedError at load when either is explicitly enabled, through a new shared multimodal helper. Both models fuse each image's full encoder output, which fails when a prefill chunk or KV cache hit splits an image.

Files
  • tensorrt_llm/_torch/models/modeling_gemma3vl.py
  • tensorrt_llm/_torch/models/modeling_llama.py
  • tensorrt_llm/_torch/models/modeling_multimodal_utils.py

trt-llm-devs · 1 file
trtllm-eval no longer sets kv_cache_config.enable_block_reuse=True when --disable_kv_cache_reuse is omitted, so a model's own block-reuse default applies as it does under trtllm-serve; the flag still turns reuse off.

Files
  • tensorrt_llm/commands/eval.py

trt-llm-runtime-devs · 2 files
New model-defaults tests load Gemma 3 and Llama 4 configs through ModelLoader and check the new defaults and startup rejections; the Gemma scratch-reuse test now expects Gemma3VLM to reject explicit block reuse. The config-database helper passes the args object, not its dump, to get_model_defaults, since the new hook reads model_fields_set.

Files
  • tests/unittest/llmapi/test_config_database.py
  • tests/unittest/llmapi/test_llm_args.py

@trtllm-agent-review

Copy link
Copy Markdown
Collaborator

Re-review status. @trtllm-agent-review re-reviews this PR once all three of these hold since its last review:

  1. new code is pushed (a commit that changes the code);
  2. every open Blocker thread has a reply;
  3. the PR has no merge conflicts with main.

Not met yet:

  • (1) The code has not changed since the bot's last review.
  • (2) 4 of 4 open Blockers have no reply since the bot's last review: A1, A2, A3, A5.

A Blocker you think should not be fixed needs no new code: reply in its thread with the reason (its premise does not hold, this PR does not introduce it, the PR rejects that configuration on purpose, the PR or the docs declare the limit, or it is resolved elsewhere) and the evidence. To fix one later, say so in its thread, ideally with a link to the NVBug, JIRA ticket or PR that tracks the fix; a crash, hang, wrong result or CI break needs that link. Once every open Blocker thread has a reply and there are no merge conflicts, the bot checks those replies, and approves when they hold.

The bot checks again in its next round.

Problem
A 64-token prefill with 24 image tokens received all 64 image embeddings.
A prefix hit inside an image also supplied embeddings for cached tokens.
Content keys need to cover the actual number of patch tokens emitted for
each tiled image.

Solution
Collect local or attached embeddings through the shared helpers and
select the part consumed by the current prefill. Record patch counts
from the processor's emitted image markers. Use the per-item counts for
a single modality with an unframed embedding mask, and require hashing
for Llama 4 image input. Skip empty media buckets when choosing whether
to hash so a text request leaves the next image request eligible.

Performance
Kernel latency, request latency, throughput and peak memory were
unmeasured. The measurements below check correctness.

Validation
In shared-node screening on one GB200 at TP1, both chunks of a 113-token
prompt and native KV hits at 32, 96 and 128 matched the full decoder
input exactly. The local and attached CUDA cases checked the embeddings
and the number of encoder calls. The Scout processor emitted 144 and 432
patch tokens for two images. Replacing the second changed only its key.

Run the Llama 4 cases in tests/unittest/_torch/modeling/test_modeling_llama.py
and the empty-image-bucket regression in tests/unittest/inputs/test_multimodal.py.
The forward checks use component weights. Trained end-to-end generation
and distributed serving were unmeasured.

Signed-off-by: Yechan Kim <161688079+yechank-nvidia@users.noreply.github.com>
…ill and KV reuse

Problem
An image token attends to later tokens in its image. A cache hit or a
budget cut inside the image leaves some of those keys unavailable. With
closely spaced images, rounding one boundary can split the next image.
Gemma 3 asserted that the cached prefix was empty when building its
image attention mask, and supplied full-prefill embeddings for a suffix.

The legacy scheduler can split a bidirectional image without an error.
In V2, a complete mixed-precision KV hit can rematch at an image start
where its high-precision window is incomplete. Consuming the back-off
during that first image clip can leave part of the later window unwritten.

Solution
Declare Gemma 3 image spans through the existing Gemma 4 mechanism,
select the embeddings for the active tokens, and include the cached
prefix in attention masks. V2 rematches local KV up to a legal prefix
and consumes the mixed-precision back-off only for a window limit.
Clip connector reservations before acceptance. A late offer can shorten
the already scheduled chunk from its left edge.

Use aligned boundaries outside every declared span, or the prompt end.
Budget for aligned intervals even when they contain several images, and
report an impossible token or encoder-output budget at admission. Check
the active scheduler before local prefill. For bidirectional input,
reject chunking on V1 and explain how to remove a V1 fallback or
disable chunking. Apply the V2 chunk budget to local prefill.
Generation-only requests do not prefill on either scheduler.
Gemma 4 26B, 31B and Unified use the same boundary rules. Separate
the images in the 31B encoder-budget fixture with text so it still
exercises several encoder steps under its original token limits.

Performance
Kernel and end-to-end latency, throughput and peak memory were unmeasured.
A shorter prefix can require recomputing part of an image. Unified's
current span declaration also covers causal audio.

Validation
CPU regressions cover V1 with generation-only image, text, and
chunking-off controls, V2 admission by request type, connector and
scheduler boundaries, and a native-status mixed-precision rematch.
With 128-token blocks and a 512-token window that rematch went from
1152 to 1024 and then to 512.
The previous code stopped at 1024. The extended V1 admission test
reproduced the generation-only rejection before the fix. All 1583 CPU
cases passed after the fix. Run the PyExecutor and KV scheduler unit
suites to reproduce. With the 31B processor the largest interval
in the eight-image QA prompt fell from 8736 to 1120 tokens against a
2048-token budget. This was a CPU admission and residency check.

In shared-node screening on one GB200 at TP1, a hit at 320 inside a
Gemma 3 image at [66,322) rematched to 66 with partial reuse and to 64
with whole blocks. Decoder inputs and masks matched exactly. On the
same model code, a two-layer BF16 FlashInfer decoder matched full-prefill
logits at three prefix depths with absolute and relative tolerance 0.01.
See tests/unittest/_torch/modeling/test_modeling_gemma3.py. Trained
end-to-end generation, live connectors and multiple ranks were unmeasured.

Signed-off-by: Yechan Kim <161688079+yechank-nvidia@users.noreply.github.com>
yechank-nvidia added a commit to yechank-nvidia/TensorRT-LLM that referenced this pull request Dec 2, 2026
…ontent keys land

Problem

Llama 4 raw image placeholders do not carry per-image content keys.
Selecting image embeddings for a prefill chunk can therefore mask a
KV prefix match that ends inside a different image. Whole-image fusion
on main reports a token-count mismatch in that case.

Solution

Pass the local vision encoder's full output to fusion. On workers
without a local encoder, pass each request's full attached embedding
tensor as on main. Keep the worker-role checks and support_mm_disagg.
Remove the test that expects partial-image selection. That behavior and
the corresponding raw-image content keys belong together in NVIDIA#22886.

Performance

Latency, throughput and GPU memory were unmeasured.

Validation

All 18 focused CPU tests passed, covering external embeddings and worker
admission. Four additional CPU checks exercised the Llama 4 forward
with synthetic features. Both worker roles fused two complete contexts
in order and raised ValueError before decoding when one image token
had two embeddings. Changed-file pre-commit and git diff --check passed.
End-to-end GPU generation was untested.

Signed-off-by: Yechan Kim <161688079+yechank-nvidia@users.noreply.github.com>
@yechank-nvidia yechank-nvidia changed the title [None][fix] Disable chunked prefill and KV block reuse for Gemma3 and Llama 4 multimodal models [None][fix] Support chunked prefill and KV cache reuse for Gemma 3 and Llama 4 images and keep Gemma 4 images whole Dec 2, 2026
@yechank-nvidia
yechank-nvidia force-pushed the yechank/legacy-mm-feature-guards branch from a13f34e to e7272dc Compare December 2, 2026 00:45
@moraxu

moraxu commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

We hit the same gap while validating KV cache reuse for Gemma 4 (TRTLLM-18392) and had prepared an equivalent clip in prepare_context_cache's re-claim loop. We are dropping it in favor of this PR. Some GB300 results that may help, from the L0_PostMerge 3090 wheel (50251c2) plus the equivalent clip. Each probe is compared with the same prompt run cold under its own cache salt:

  • LLM API reproducer. Gemma 4 26B with dummy weights, a 128-token sliding window and enable_partial_reuse=False. A request shares an image with an earlier one and diverges right after it. Without the clip it claims 256 tokens, inside the run [8, 264); with the clip it claims 0. I can contribute this check (an extension of test_gemma4_e2e_dummy.py::test_e2e_multimodal_26b_dummy) after this PR lands.
  • Real weights: a claim inside a long run. 31B BF16 is deterministic here (cold vs. cold matches bit for bit). Claims inside a 1089-token image run (max_soft_tokens=1120, sliding window 1024) left greedy outputs identical over 48 tokens. The first-token logprob deltas were 0.04–0.11, the same as for correct reuse that ends after the run (0.06–0.11). These claims left only about 9 tokens of the run to recompute; the error grows with that tail.
  • Real weights: a claim inside a run that fits the window. Claims inside a 256-token run behaved like correct reuse, apart from one near-tie flip (top-2 margin 0.08).
  • Cost with partial reuse off. The clipped claim floors to a block boundary, so for prompts that start with an image it drops to 0: an exact repeat of a 1120-token image prompt reused nothing. With partial reuse on (the default), repeats and "same image, different question" end after the run and lose nothing. A variant that clips only runs longer than the sliding window would keep the within-window resumes, which the data above suggests are exact.
  • E4B (causal over media): reuse matched cold runs exactly for image, video, audio, multi-turn and long-text prompts, with and without chunked prefill.

Problem
Pyrefly sees a generic ModuleList element at the compact mask
capability check. It infers Tensor for the dynamic self_attn access
and reports a missing attn attribute on the PR merge.

Solution
Cast the iterable to the Gemma3DecoderLayer element type populated
by Gemma3TextModel. Each layer still checks its attention backend
against the current attention metadata.

Performance
Unmeasured. The cast returns the same ModuleList.

Validation
Pyrefly 1.4.0 reproduced the reported diagnostic on the original
merge and found zero new diagnostics on the fixed Gemma 3 file.
The CPU suite passed 1,584 tests and the Gemma 3 mask routing checks.
Pre-commit and git diff --check passed. CUDA cases remain for CI.

Signed-off-by: Yechan Kim <161688079+yechank-nvidia@users.noreply.github.com>

@trtllm-agent-review trtllm-agent-review 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.

Thanks for the PR. Lets Gemma 3 and Llama 4 image requests use chunked prefill and KV cache reuse, and replaces the V2 scheduler's image-chunk alignment with a rule that keeps bidirectional image spans whole for Gemma 3 and Gemma 4.

Reviewed at commit e7272dc44c (26 files, +806/−561). The PR moved to 7a118483f2 while the review ran; those later changes are not covered here.

This re-review covers the two commits pushed since the previous review (778e078, e7272dc). They replace that review's startup guard, so the whole current diff is new code. As a re-review, it posts only Blockers and possible blockers.

Re-review: request changes: 4 Blockers need fixing before merge.

Blockers (4)

  • (B3: CI breakage) The new Llama 4 span check fails the existing pre-merge cpu_only test test_llama4_rescales_decoded_png, whose Mock processor has no image markers, so the CPU-Generic stages break. (modeling_llama.py:1524)
  • (B2: Crash, hang, race or leak) A Gemma 3/Gemma 4 image request whose merged image interval exceeds the budget left after decode is skipped every pass while younger requests run, so under steady load it waits without bound. (scheduler_v2.py:2004)
  • (B4: API or compatibility break) Forced hashing makes Gemma 3 VLM and Llama 4 requests that pass their images as a tuple fail in preprocessing; on main they fell back to the plain processor and were served. (modeling_gemma3vl.py:61)
  • (B1: Correctness) A KV connector that keys on tokens and cache_salt, as the connector guide and examples do, now silently serves another image's KV to Gemma 3 and Llama 4 requests; the image-identity rule is enforced nowhere. (multimodal.md:82)

Possible blockers (3)

  • (P1: Performance regression or cost) With an FP8 KV cache, Gemma 3 VLM image chunks after a long cached prefix build about 2 GiB of dense masks per forward that KV-cache sizing does not reserve, and sliding layers attend to every prefix key. (modeling_gemma3.py:584)
  • (P1: Performance regression or cost) Under FORCE_CHUNK the new snapshot-point filter drops branch-snapshot forks that are not multiples of the chunk unit, even far from any image, so image requests sharing a prefix lose its reuse. (scheduler_v2.py:1961)
  • (P2: Stated as intended) Back-to-back Gemma 4 images now merge into one interval that must fit max_num_tokens, so multi-image prompts that ran on main are refused at admission; the QA prompt was reshaped to avoid it. (scheduler_v2.py:2225)
What this review checked
  • The previous review's four Blockers are fixed: full_image_prefill_defaults and both model hooks are gone, block reuse keeps its default, and text-only requests (trtllm-bench with disable_mm_encoder=True) never reach the new admission check, which needs declared image spans (tensorrt_llm/_torch/pyexecutor/py_executor.py:9358-9373).
  • With chunked prefill off, no new call can divide by the V2 scheduler's zero chunk unit: legal_chunk_end, indivisible_mm_chunks and hold_chunk run only on chunking paths (scheduler_v2.py:1676-1687, 2219-2220; ctx_decoder_batch.py:146-156), and the connector paths use tokens_per_block.
  • The find_mm_token_lengths shortcut (tensorrt_llm/inputs/multimodal.py:1587-1595) is reached only by Llama 4's processor at this revision, since other processors attach item metadata after hashing (tensorrt_llm/inputs/registry.py:1854-1876), and Llama 4's patch counts match its embedding mask and its encoder rows.
  • Not covered: No GPU run: the scheduling, mask-memory and connector scenarios were traced in code.
  • Not covered: No unit-test run: the review environment has no torch or built bindings.
  • Not covered: Open PRs #23060, #23036 and #23118 were read from their GitHub pages only.

Automated review by trtllm-agent-review. If a point is wrong, reply in its thread. Once you have pushed code changes and replied in every Blocker thread, the bot re-checks the Blockers within a few hours. A Blocker you think should not be fixed needs no code change: reply in its thread with the reason and the evidence.

chunk_size = pregrown
elif mm_runs:
lo = req.context_current_position
end = legal_chunk_end(req, lo, lo + chunk_size, self.chunk_unit_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.

[Blocker] (B2: Crash, hang, race or leak) A Gemma 3 or Gemma 4 26B/31B image request can wait here without bound. When lo + chunk_size ends inside its next indivisible interval, legal_chunk_end rounds down to 0 and the request returns SKIP (lines 2007-2008), and the FCFS loop continues past it (lines 1174-1175), so younger context requests take the budget left after decode and then decode themselves. Phase 1 commits generation tokens first (lines 826-952), the starvation shares apply only with shortest_uncached_first plus context_starvation_iterations, and the deadlock detector never fires because decode keeps progressing. With the default V2 manager and enable_chunked_prefill, which supported-models.md now lists for Gemma 3 and Gemma 4, a request whose merged image interval needs more than max_num_tokens minus the per-pass decode tokens (several back-to-back images at max_num_tokens=8192 while about 1,000 requests decode with 3 draft tokens each) is not scheduled while that load lasts, and a mid-prefill request keeps its KV pages. The description says "A pass must have room for that interval after decode", and docs/source/developer-guide/multimodal.md says the interval "must also fit in the budget left after decode", but nothing bounds the wait. On main only one Gemma 4 image had to fit; now adjacent images merge, and Gemma 3 joins.

Suggested fix: bound the wait with a reservation that the request actually reaches.

  • Keep a scheduler-side dict of consecutive passes in which a flagged context request was pending and its chunk did not run: the SKIPs at lines 1999-2000 and 2007-2008, and chunks that MultimodalScheduler or attention-DP balancing dropped after scheduling. Count by the chunk running, not by context_current_position, which prepare_context moves on admission.
  • Once one request reaches a small bound, budget.hold the tokens of the interval it waits for plus one request slot before phase 1. Put that request first in phase 2 even when the phase-1 scan stopped before reaching it (phase 1 breaks at the first generation request that no longer fits, lines 944-945), release the hold just before it is tried, and schedule it with token_cap at the interval's end.
  • Keep it out of that pass's generation eviction and recompute-pause candidates, keep the reservation until the chunk runs, reserve for one request at a time, and guard the bookkeeping so text-only passes pay nothing.
  • In the multi-pass schedule_request test, let the text requests it admits join decode on each pass; with a fixed decode set, the test cannot fail without the fix.

For every request with declared spans, a connector offer received after the
chunk is scheduled can advance its start only. The end stays fixed so encoder
inputs and the token budget still cover that chunk. A connector that reuses
image KV must include the image content identity in its cache keys.

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.

[Blocker] (B1: Correctness) This rule is enforced nowhere, and the connector docs and examples break it.

  • KVCacheManagerV2._connector_may_serve (tensorrt_llm/_torch/pyexecutor/kv_cache/kv_cache_manager_v2.py:8158-8173) accepts offers for image requests. The new code only clips them to legal chunk ends (8105-8106, 8253-8258).
  • On V2, RequestData.block_hashes is [], and PrefixLoad carries only request.get_tokens(0) and cache_salt (connectors/kv_cache_connector.py:612-613, 1003-1004).
  • docs/source/features/kv-cache-connector.md (lines 215 and 495) describes connectors that hash the token prefix with cache_salt, and the example connectors key on tokens (examples/llm-api/llm_kv_cache_connector.py:260, and llm_kv_cache_connector_vswa.py:185-187, which is written for Gemma 3).

Gemma 3 and Llama 4 image placeholders are identical token ids. A request whose image differs from a stored request's but whose tokens match therefore loads the other image's KV and answers about that image, possibly another user's, with no error. On main these hits failed loudly (the Gemma 3 cached-prefix assert, the Llama 4 token-count mismatch), and this PR removes both. mooncake-store keys on multimodal digests and is not affected.

Suggested fix: clip what a connector may serve, for a request with multimodal content, at its first multimodal position floored to a block, unless the connector declares that its keys include multimodal content.

  • Clip in KVCacheManagerV2 at the reservation clip (8105-8106) and at the late-offer clip (8253-8258). At the late-offer clip, also cap at floor_block(chunk_end - 1), so a causal request's offer cannot take the shifted-window arm onto the image.
  • Clip on V1 too, in KvCacheConnectorManager.get_num_new_matched_tokens, which Llama 4 reaches.
  • Skip the connector query when the clip leaves no block, so an async connector does not start a transfer that is then discarded.
  • Read multimodal_positions with getattr and an isinstance(list) check, so the test fakes and Mock requests keep working.
  • Resolve the declaration on every rank from the connector scheduler class, as supports_attention_dp is (py_executor_creator.py:1388-1413), and set it for mooncake-store.
  • Add the first multimodal position to RequestData, so leaders can stop saving there.
  • State the rule in kv-cache-connector.md next to the cache_salt rule, and make the example connectors follow it.

variable_window_token_ends = None
if image_token_mask is not None:
context_lens = self._get_image_context_lengths(attn_metadata)
context_lens, cached_token_lens = self._get_image_context_lengths(

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.

[Possible blocker] (P1: Performance regression or cost) With an FP8 KV cache, these prefix lengths now make the dense image masks grow with the cached prefix.

  • Gemma3VLM's text model always uses FlashInfer (modeling_gemma3vl.py:267), and FlashInfer's supports_variable_window is False with FP8 KV (tensorrt_llm/_torch/attention/backends/flashinfer.py:2658-2671). Every batch with an image chunk therefore takes the dense branch at lines 609-618.
  • build_gemma_attention_mask allocates sum(q*(p+q)) bools per mask, once for global and once for local layers (lines 106-112).
  • For an 8K-token chunk after a ~120K-token prefix (chunked prefill of a long image prompt, or a block-reuse hit, which is on by default), that is about 2 GiB per forward, against 128 MiB with no prefix. KV-cache sizing is profiled without a prefix, so it does not reserve this memory.
  • FlashInfer also runs the sliding-window layers over all p+q keys, because custom masks plan with window_left=-1 (flashinfer.py:2502-2507).

On main this path asserted (the prefix had to be 0). With a BF16 KV cache, the compact path bounds the masks.

What decides it: Gemma 3 27B VLM with an FP8 KV cache on one H100 80GB, chunked prefill, max_num_tokens=8192 and max_seq_len=131072. Run a 128K-token prompt with an image in the last chunk, and a 120K-token cached prefix followed by an image. Compare peak memory and that chunk's prefill time with the image in the first chunk. An OOM, or a peak above the headroom left after KV-cache allocation, makes it a blocker.

Suggested fix, if it does: a per-request admission cap does not bound it, because once any context in the batch has image tokens, every context gets a q*(p+q) mask (lines 520-532, 608-618). Do one of these:

  • (a) Let the compact variable-window path take FP8 KV on FlashInfer for fa2/fa3 on SM89 and newer (Triton's fp8e4nv needs SM89). Pass the K/V from before the FP8 cast only on that branch, because trtllm-gen casts q to FP8 (flashinfer.py:3093-3095). Add a test on a real FP8 KV cache against the dense path, and keep the FP8 rejection below SM89.
  • (b) Reserve about 2.25 × max_num_tokens × max_seq_len bytes (both masks plus FlashInfer's packed copies) in KV-cache sizing, only for Gemma3VLM with an FP8 KV cache on FlashInfer.

Either way, state the FP8 KV cost next to footnote [^32].

# Even a text-only stretch preceding the first image needs one aligned chunk.
chunks.append((0, min(self.chunk_unit_size, req.prompt_len)))
start, end = max(chunks, key=lambda span: span[1] - span[0])
if end - start > self.max_num_tokens:

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.

[Possible blocker] (P2: Stated as intended) Is this refusal meant to reach Gemma 4 prompts that ran on main, and where will users read about it? Adjacent bidirectional images merge into one interval (llm_request.py:2187-2191), and this check refuses the request when the interval exceeds max_num_tokens.

  • TestGemma4_31B's original prompt now fails here: eight back-to-back images at max_soft_tokens=1120 (1,089 tokens each) with max_num_tokens=2048.
  • At the default max_num_tokens=8192, the same eight images fail whenever no 32-token boundary falls in the few framing tokens between them.
  • On main these requests produced output, with an image split across chunks.

multimodal.md:72-76 states the rule. But the PR changed the QA prompt to put 256 text tokens before each image (tests/integration/defs/accuracy/test_llm_api_pytorch_multimodal.py:228-233), while the description says the fixture "still exercises eight images ... with its original budgets".

Suggested fix: state the rule by its trigger in footnote [^32] and in the multimodal guide.

  • Say that each media span is widened to chunk-unit boundaries, and that spans whose widened intervals overlap must fit max_num_tokens together.
  • Say that the unit is tokens_per_block (32 by default), or max(256, tokens_per_block) only when kv_cache_config.max_attention_window is set below max_seq_len (py_executor_creator.py:1269-1275), and qualify the guide's "256-token sliding-window chunk unit" example to match.
  • Give the fixture's case as the example, and correct the description's sentence about the QA fixture.
  • Keep the original back-to-back layout as a second case inside the existing LLM block of TestGemma4_31B. Assert the admission error ("Increase max_num_tokens"), and that the following text request still completes.

@trtllm-agent-review

Copy link
Copy Markdown
Collaborator

Re-review status. @trtllm-agent-review re-reviews this PR once all three of these hold since its last review:

  1. new code is pushed (a commit that changes the code);
  2. every open Blocker thread has a reply;
  3. the PR has no merge conflicts with main.

Not met yet:

  • (2) 4 of 4 open Blockers have no reply since the bot's last review: A10, A11, A12, A15.

A Blocker you think should not be fixed needs no new code: reply in its thread with the reason (its premise does not hold, this PR does not introduce it, the PR rejects that configuration on purpose, the PR or the docs declare the limit, the PR or the docs say who must be trusted, or it is resolved elsewhere) and the evidence. To fix one later, say so in its thread, ideally with a link to the NVBug, JIRA ticket or PR that tracks the fix; a crash, hang, wrong result or CI break needs that link. Once every open Blocker thread has a reply and there are no merge conflicts, the bot checks those replies, and approves when they hold.

The bot checks again in its next round.

Problem
The Llama 4 decoded PNG test used a Mock for the image token ids and
a one-token prompt. The processor now counts the patch tokens between
the start and end markers of each image, so this CPU test failed with
an AttributeError.

Solution
Give the test double real token ids and one complete marker span per
image. The test still checks do_rescale and now also checks the patch
count recorded for each image.

Performance
Not applicable. Only the test changes.

Validation
The test failed at the previous head and passes with this change. All
three tests in its file pass on CPU in the main-defaults image.

Signed-off-by: Yechan Kim <161688079+yechank-nvidia@users.noreply.github.com>
Problem
Gemma 3 and Llama 4 require multimodal hashing. When a request passed
two images as a tuple, the hashing helpers treated the tuple as one
image while the processor read two. Preprocessing then failed on the
token count. A tuple of UUIDs failed the same way.

Solution
Treat tuple buckets and tuple UUID entries as item lists when hashing,
counting tokens and counting items, as request validation already
does. The processor still receives the original input.

Performance
Unmeasured. The helpers do the same work per item.

Validation
A new CPU test passes two images with UUIDs as a list and as a tuple
and expects the same hashes, UUIDs and token counts. It failed before
the change. Without UUIDs, the tuple bucket failed the token count
check before the change and now matches the list.

Signed-off-by: Yechan Kim <161688079+yechank-nvidia@users.noreply.github.com>
Problem
For a request with bidirectional image spans, the scheduler kept a
branch snapshot point only if it was a legal aligned chunk end. With a
256-token sliding-window chunk unit and 32-token blocks, it dropped
block-aligned points outside every image. Later requests that shared
the prompt up to such a point then recomputed it.

Solution
Drop only the points inside a span. A kept point ends the chunk without
unit rounding, as it does for a text request. The guide and the
interval docstring list it as a legal boundary.

Performance
Unmeasured. A chunk can now end at a kept snapshot point.

Validation
A new CPU scheduler test uses 32-token blocks, a 256-token unit and
points at 192 and 352 around two images. It drops 192, which lies
inside an image, keeps 352 and ends the chunk there. Before the change
it dropped both points.

Signed-off-by: Yechan Kim <161688079+yechank-nvidia@users.noreply.github.com>

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants