Skip to content

[None][fix] Latch cached_tokens from the prefix reuse decision, not the decode position - #19743

Merged
Tabrizian merged 3 commits into
NVIDIA:mainfrom
Tabrizian:fix/gen-only-cached-tokens-root-cause
Oct 2, 2026
Merged

Tabrizian merged 3 commits into
NVIDIA:mainfrom
Tabrizian:fix/gen-only-cached-tokens-root-cause

Conversation

@Tabrizian

@Tabrizian Tabrizian commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

Dev Engineer Review

The change latches cached_tokens from prefix reuse for generation-only requests. _prepare_tp_inputs no longer sets the field from decode positions, except for promoted final-context rows. _prepare_disagg_gen_resources initializes it from prepopulated_prompt_len. This corrects the reported cold-request overcount while preserving the set-once behavior. No current review findings were supplied; finding counts are unavailable. Test results are also unavailable.

QA Engineer Review

The change adds tests/unittest/_torch/executor/test_gen_only_cached_tokens.py, which checks zero and nonzero prefix reuse and verifies that cached_tokens remains latched. It also modifies the request factory, the KV-connector generation-only test, and the disaggregated receive-ordering helper. The reported receive-ordering failure caused by missing prepopulated_prompt_len was addressed by adding that attribute to the test fake. No test-list files changed. The reported integration checks are not confirmed as passing. Coverage verdict: needs follow-up.

Per-File QA Perspective

  • tensorrt_llm/_torch/pyexecutor/model_engine.py: Verify that decode paths do not overwrite cached_tokens and that promoted final-context rows still report reused-prefix tokens.
  • tensorrt_llm/_torch/pyexecutor/py_executor.py: Verify that generation-only requests set cached_tokens from prepopulated_prompt_len before connector reporting.
  • tests/unittest/_torch/executor/test_gen_only_cached_tokens.py: Covers zero and nonzero reuse and the set-once behavior. This unit test is not listed in CI or manual-QA integration lists.
  • tests/unittest/_torch/executor/llm_request_factory.py: Adds a shared helper to build LlmRequest objects, including generation-only context parameters. Check that tests using the helper preserve their intended request setup.
  • tests/unittest/_torch/executor/test_kv_connector_generation_only.py: Reuses the shared request helper while retaining context-request and generation-only guard checks. This unit test is not listed in CI or manual-QA integration lists.
  • tests/unittest/_torch/executor/test_disagg_receive_ordering.py: Adds prepopulated_prompt_len to mocked requests to match the resource-preparation input. This unit test is not listed in CI or manual-QA integration lists.

Description

Result.cached_tokens for a disaggregated generation-only request equals the prompt length, even on a cold cache. The KV arrived by transfer; nothing was served from a prefix cache.

LlmRequest.cached_tokens is a set-once field that reports the prompt prefix served from the KV cache. The generation (decode) branch of _prepare_tp_inputs also wrote it, from the decode position max_beam_num_tokens - 1. For every request whose context phase ran on this worker that write is a silent no-op, because the context branch already latched the real prefix. A generation-only request never runs the context branch on the generation worker, so the decode write was its first write and the sequence length was latched as a cache hit. Every consumer of the field then saw it: the five response-copy sites, LlmRequest.create_response, the ADP router's active-token load, the Prometheus prompt_cache_cached_tokens metric, the gRPC servicers and RequestOutput.cached_tokens.

This fixes the writer instead of the readers (alternative to #19708, which patches three of the response sites):

  • _prepare_tp_inputs: the decode branches no longer write cached_tokens. The one exception is a promoted one-token final context chunk, for which the decode branch is the request's context-phase forward; it latches context_current_position exactly as the context branch does. num_cached_tokens_per_seq (attention metadata) is untouched.
  • _prepare_disagg_gen_resources: generation-only requests latch cached_tokens from prepopulated_prompt_len right after the allocation decides how much of the prompt this worker's cache lookup matched. This is the generation-worker analogue of the context branch's first-chunk latch and uses the same definition (tokens matched, partial-block match included). Transfer granularity is a separate concern: the transceiver skips only whole matched blocks and re-receives a trailing partially matched block, so on a warm local hit the reported count can exceed the skipped tokens by up to tokens_per_block - 1.

Not changed: the set-once property (chunked prefill relies on it), the response sites and router (they now read a correct value), and the ctx_usage path (the context worker's count still reaches the generation worker over the KV aux buffer and the serve postprocessor still adopts it, so trtllm-serve output via the disaggregated server is unchanged).

Behaviour that changes on a generation worker:

  • RequestOutput.cached_tokens, gRPC usage and the Prometheus metric report the locally reused prefix (0 on a cold cache) instead of the prompt length.
  • ADP router: a decoding generation-only request now contributes prompt_len - local_reuse active tokens for its whole life, on the same scale as aggregated requests, instead of dropping to 0 after its first step. Flagging for the router owners since attention-DP generation workers will balance differently.

Test Coverage

  • tests/unittest/_torch/executor/test_gen_only_cached_tokens.py (cpu_only): builds a real generation-only LlmRequest through the new shared llm_request_factory.make_llm_request (also adopted by test_kv_connector_generation_only.py), drives _prepare_disagg_gen_resources with a fake KV manager that settles prepopulated_prompt_len to 0 or 8, asserts the latch equals the reuse, and asserts a subsequent decode-position write bounces off it.
  • tests/unittest/_torch/executor/test_pytorch_model_engine.py::test_promoted_context_uses_prompt_token_during_overlap still asserts a promoted chunk latches context_current_position.
  • Reproduced on EOS (H100, NGC release container 1.3.0rc29, Qwen3-0.6B, context-only and generation-only trtllm-serve workers on one node, two-call flow driven directly so no ctx_usage is attached). Before, with the container as shipped: the generation side reported cached_tokens=186 of 186 prompt tokens on a cold request and again on the warm repeat, and its Prometheus prompt_cached_tokens_total advanced by 186 each time. After, with this fix cherry-picked onto v1.3.0rc29 (clean merge) and the two files swapped into the container: cold 0, warm repeat 185 (the prefix the generation worker already held and did not receive). The context side (0, 185) and an aggregated control request on the generation worker (185) were identical in both runs, as was the generated text.
  • tests/integration/defs/disaggregated/test_disaggregated.py usage check and test_disaggregated_single_gpu.py cached-token checks cover the disaggregated path end to end.

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.

…he decode position

LlmRequest.cached_tokens is set once per request and reports the prompt
prefix served from the KV cache. The generation branch of
_prepare_tp_inputs also wrote it, from the decode position
(max_beam_num_tokens - 1). That write is a no-op for a request whose
context phase ran on this worker, because the context branch already
latched the real prefix. For a disaggregated generation-only request the
context phase ran elsewhere, so the decode write was the first one and
latched the whole prompt as a cache hit. Every consumer of the field then
saw it: the five response sites, the ADP router's active-token load, the
Prometheus prompt_cache_cached_tokens metric, the gRPC servicers and
RequestOutput.cached_tokens.

Only a promoted one-token context chunk may latch on the decode path; that
is its context-phase forward. Generation-only requests latch in
_prepare_disagg_gen_resources from prepopulated_prompt_len, the prefix
this worker matched in its own cache and will not receive, at the point
the allocation decided it.

Signed-off-by: Iman Tabrizian <[email protected]>
@Tabrizian

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@coderabbitai

coderabbitai Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

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: 61dbc027-b2a0-4760-873d-6300002335b4

📥 Commits

Reviewing files that changed from the base of the PR and between c1f76dc and 5795897.

📒 Files selected for processing (1)
  • tests/unittest/_torch/executor/test_disagg_receive_ordering.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

The executor copies prepopulated prompt lengths to cached_tokens before connector reporting. The model engine sets cached_tokens for promoted rows and removes assignments from other request paths. Tests cover prefix reuse and request construction.

Changes

Cached-token accounting

Layer / File(s) Summary
Initialize cached tokens for disaggregated requests
tensorrt_llm/_torch/pyexecutor/py_executor.py, tests/unittest/_torch/executor/llm_request_factory.py, tests/unittest/_torch/executor/test_gen_only_cached_tokens.py, tests/unittest/_torch/executor/test_kv_connector_generation_only.py, tests/unittest/_torch/executor/test_disagg_receive_ordering.py
The executor copies each request’s prepopulated prompt length to cached_tokens before connector reporting. Tests cover prefix reuse and use the shared request factory. The receive-ordering test mock sets prepopulated_prompt_len to 0.
Update model-engine cached-token assignments
tensorrt_llm/_torch/pyexecutor/model_engine.py
The model engine sets cached_tokens to the context position for promoted rows and removes assignments from other request paths.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: litaotju

Merge Risk: ⚪ Minimal · up to 57958

The reviewed paths preserve cached-token accounting for generation-only and promoted requests, so no actionable merge risk remains; proceed with normal validation.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.44% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly identifies the fix: latching cached_tokens from prefix reuse instead of the decode position. It uses the required [None][fix] format and is concise.
Description check ✅ Passed The description explains the problem, implementation, behavior changes, and test coverage. It includes the required sections and marks the review checklist as completed.
  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #75885 [ run ] triggered by Bot. Commit: 03d7acb Link to invocation

…n-only request factory

Move the promoted-context latch to the categorization loop where
is_promoted_context is decided, so neither decode branch carries a
cached_tokens write. Lift the real-LlmRequest factory from the
KV-connector gen-only test into llm_request_factory.py and use it from
both tests; drop the test that exercised no changed code and trim the
comments that restated each other.

Signed-off-by: Iman Tabrizian <[email protected]>
@Tabrizian

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #75909 [ run ] triggered by Bot. Commit: c1f76dc Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #75885 [ run ] completed with state ABORTED. Commit: 03d7acb

Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #75909 [ run ] completed with state FAILURE. Commit: c1f76dc
/LLM/main/L0_MergeRequest_PR pipeline #62585 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

@Tabrizian

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #75942 [ run ] triggered by Bot. Commit: c1f76dc Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #75942 [ run ] completed with state SUCCESS. Commit: c1f76dc
/LLM/main/L0_MergeRequest_PR pipeline #62617 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

…t_len

_prepare_disagg_gen_resources now latches cached_tokens from
prepopulated_prompt_len. test_disagg_receive_ordering.py drives the real
method with SimpleNamespace requests, which lacked the attribute every
real request carries, so ten parametrizations failed with AttributeError
on the H100, B300 and SBSA CPU stages.

Signed-off-by: Iman Tabrizian <[email protected]>
@Tabrizian

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #75974 [ run ] triggered by Bot. Commit: 5795897 Link to invocation

@allisonlim-nv allisonlim-nv left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@github-actions

github-actions Bot commented Oct 1, 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.

@trtllm-agent

This comment has been minimized.

@coderabbitai

This comment has been minimized.

@github-actions

github-actions Bot commented Oct 1, 2026

Copy link
Copy Markdown

Semantic conflict review

The verdict of record is the Semantic conflict with target branch / PR #19743 commit status on the requested head commit. This summary updates on reply events and may lag between a new request and its reply.

Latest recorded state: No semantic conflict found (best effort) for head 57958979cbf4b401dd09ac64e4f7c4eaabdd3171, target 28c5d5a5c5605b2824514bba631f943fcd88ad21, merge base 6ae42bb89253aaf47b728880bb31ec0edd005474 (request 6f9b0984-652c-4488-8c8e-c34ad2750896). CodeRabbit analysis.

Best-effort AI judgment for the recorded revisions. PASS, FAIL and INCONCLUSIVE may be incomplete or incorrect. PR authors and reviewers should independently verify the evidence and relevant behavior. This semantic review and its status/workflow are advisory, not required merge checks under current repository rules; other merge requirements still apply. Advisory status does not make a confirmed defect safe to ignore.

Requested (UTC) Head Target Verdict Comment
2026-10-01T19:03:53Z 57958979cbf4 28c5d5a5c560 PASS reply

Processed request and reply comments are minimized to reduce timeline noise; they remain expandable for audit.

@chienchunhung chienchunhung 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. Added one non-blocking comment/question.

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #75974 [ run ] completed with state FAILURE. Commit: 5795897
/LLM/main/L0_MergeRequest_PR pipeline #62645 completed with status: 'UNSTABLE'

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

Link to invocation

@Tabrizian

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

1 similar comment
@Tabrizian

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #76024 [ run ] triggered by Bot. Commit: 5795897 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #76025 [ run ] triggered by Bot. Commit: 5795897 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #76024 [ run ] completed with state ABORTED. Commit: 5795897

Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #76025 [ run ] completed with state SUCCESS. Commit: 5795897
/LLM/main/L0_MergeRequest_PR pipeline #62684 completed with status: 'SUCCESS'

CI Report

Link to invocation

@Tabrizian
Tabrizian merged commit b75bcd1 into NVIDIA:main Oct 2, 2026
16 of 17 checks passed
@Tabrizian
Tabrizian deleted the fix/gen-only-cached-tokens-root-cause branch October 2, 2026 01:32
lori-ren added a commit to lori-ren/TensorRT-LLM that referenced this pull request Oct 6, 2026
Keep prefill capture on local call state after NVIDIA#18060 and take NVIDIA#19743's cached_tokens change.

Signed-off-by: Lori Ren <[email protected]>
lori-ren added a commit to lori-ren/TensorRT-LLM that referenced this pull request Oct 6, 2026
…factor/decoder-runner-migration

Port the main-side engine changes (NVIDIA#18813, NVIDIA#18060, NVIDIA#19743) into DecoderRunner and share the startup metrics dict with the engine.

Signed-off-by: Lori Ren <[email protected]>
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.

5 participants