-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[None][feat] Support cached tokens for Openai server #7637
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
📝 WalkthroughWalkthroughAdds cached_tokens capture in PyExecutor, propagates it through GenerationResultBase, and surfaces it in OpenAI protocol UsageInfo via a new PromptTokensDetails model. Updates server aggregation and postprocessing to populate and merge prompt_tokens_details.cached_tokens across streaming and non-streaming paths. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Client
participant Server as OpenAI Server
participant Post as Postprocess Handlers
participant Exec as PyExecutor
participant Engine as Model Engine
Client->>Server: Create completion/chat request
Server->>Exec: enqueue(request)
Exec->>Engine: run inference
Engine-->>Exec: attn_metadata (request_ids, kv_cache_params)
Note right of Exec: _fetch_cached_tokens(req_id)<br/>find index, read num_cached_tokens
Exec-->>Server: response.result (cached_tokens set)
Server->>Post: process response/result
Post-->>Server: UsageInfo(..., prompt_tokens_details.cached_tokens)
Server->>Server: aggregate cached_tokens across parts
Server-->>Client: Response with UsageInfo.prompt_tokens_details
Estimated code review effort🎯 4 (Complex) | ⏱️ ~55 minutes Suggested reviewers
Tip 👮 Agentic pre-merge checks are now available in preview!Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.
Example: reviews:
pre_merge_checks:
custom_checks:
- name: "Undocumented Breaking Changes"
mode: "warning"
instructions: |
Flag potential breaking changes that are not documented:
1. Identify changes to public APIs/exports, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints (including removed/renamed items and changes to types, required params, return values, defaults, or behavior).
2. Ignore purely internal/private changes (e.g., code not exported from package entry points or marked internal).
3. Verify documentation exists: a "Breaking Change" section in the PR description and updates to CHANGELOG.md.Please share your feedback with us on this Discord post. Pre-merge checks (2 warnings, 1 inconclusive)❌ Failed checks (2 warnings, 1 inconclusive)
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
tensorrt_llm/serve/openai_server.py (1)
587-605: Guard None when aggregating prompt_tokens_details to avoid crashesusage.prompt_tokens_details can be None; current code would raise AttributeError during merge.
Apply:
- num_prompt_tokens = num_gen_tokens = num_cached_tokens = 0 + num_prompt_tokens = num_gen_tokens = num_cached_tokens = 0 for rsp in responses: choices, usage = rsp.choices, rsp.usage all_choices.extend(choices) num_prompt_tokens += usage.prompt_tokens num_gen_tokens += usage.completion_tokens - num_cached_tokens += usage.prompt_tokens_details.cached_tokens + if usage.prompt_tokens_details: + num_cached_tokens += usage.prompt_tokens_details.cached_tokens # Aggregate prompt token ids for context-only requests if rsp.prompt_token_ids is not None: all_prompt_token_ids.append(rsp.prompt_token_ids) - usage_info = UsageInfo( + usage_info = UsageInfo( prompt_tokens=num_prompt_tokens, completion_tokens=num_gen_tokens, total_tokens=num_gen_tokens + num_prompt_tokens, - prompt_tokens_details=PromptTokensDetails( - cached_tokens=num_cached_tokens, - ), + prompt_tokens_details=PromptTokensDetails( + cached_tokens=num_cached_tokens, + ), )tensorrt_llm/serve/postprocess_handlers.py (1)
1-3: Add NVIDIA Apache-2.0 header (2025).Repository guideline requires the NVIDIA Apache-2.0 copyright header at the top of source files.
+# Copyright (c) 2025, NVIDIA CORPORATION. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License.
🧹 Nitpick comments (13)
tensorrt_llm/serve/openai_protocol.py (2)
69-71: Add non-negative validation for cached_tokensPrevent invalid states with a lower bound; also aligns with OpenAI’s usage details semantics.
Apply:
-class PromptTokensDetails(OpenAIBaseModel): - cached_tokens: int = 0 +class PromptTokensDetails(OpenAIBaseModel): + cached_tokens: int = Field(default=0, ge=0)
1-2: Missing Apache-2.0 header (repo guideline)This file should start with the NVIDIA Apache-2.0 copyright header for 2025.
tensorrt_llm/executor/result.py (1)
343-344: Use a safe getter to avoid AttributeError on older/external respondersIf a responder doesn’t set cached_tokens, this will crash. Use getattr fallback.
Apply:
- self.cached_tokens = response_result.cached_tokens + self.cached_tokens = getattr(response_result, "cached_tokens", 0)tensorrt_llm/_torch/pyexecutor/py_executor.py (2)
1867-1875: Avoid broad Exception; guard access and catch specific errorsCatching Exception violates BLE001 and can mask bugs. Add attribute guards and handle expected failures (ValueError/IndexError/AttributeError/TypeError).
Apply:
- def _fetch_cached_tokens(self, req_id: int): - try: - idx = self.model_engine.attn_metadata.request_ids.index(req_id) - return self.model_engine.attn_metadata.kv_cache_params.num_cached_tokens_per_seq[idx] - except Exception as e: - logger.warning(f"Error in fetch_cached_tokens: {e}") - logger.warning(traceback.format_exc()) - return 0 + def _fetch_cached_tokens(self, req_id: int) -> int: + """Best-effort lookup of cached tokens for a request. Returns 0 on miss/errors.""" + attn_md = getattr(self.model_engine, "attn_metadata", None) + if attn_md is None: + return 0 + try: + req_ids = getattr(attn_md, "request_ids", None) + kv_params = getattr(attn_md, "kv_cache_params", None) + if not req_ids or kv_params is None: + return 0 + idx = req_ids.index(req_id) # may raise ValueError + per_seq = getattr(kv_params, "num_cached_tokens_per_seq", None) + if not per_seq or idx < 0 or idx >= len(per_seq): + return 0 + return int(per_seq[idx]) + except (ValueError, IndexError, AttributeError, TypeError) as e: + logger.warning(f"fetch_cached_tokens miss for req_id={req_id}: {e}") + return 0
1-1: Missing Apache-2.0 header (repo guideline)Please add the 2025 NVIDIA Apache-2.0 header at the top.
tensorrt_llm/serve/openai_server.py (2)
44-45: Import style nit: prefer module namespace per repo guidelineOptional: import the module and reference types via namespace to reduce import lists.
Example:
-from tensorrt_llm.serve.openai_protocol import (ChatCompletionRequest, ... - UsageInfo, PromptTokensDetails, - to_llm_disaggregated_params) +from tensorrt_llm.serve import openai_protocol as oai_proto # then use: oai_proto.UsageInfo, oai_proto.PromptTokensDetails, ...
1-1: Missing Apache-2.0 header (repo guideline)Please add the 2025 NVIDIA Apache-2.0 header at the top.
tensorrt_llm/serve/postprocess_handlers.py (6)
193-195: Same guard for cached_tokens in streaming chunks.Mirror the defaulting here.
- total_tokens=output.length + prompt_tokens, - prompt_tokens_details=PromptTokensDetails(cached_tokens=rsp.cached_tokens)) + total_tokens=output.length + prompt_tokens, + prompt_tokens_details=PromptTokensDetails( + cached_tokens=(getattr(rsp, "cached_tokens", 0) or 0) + ))
204-205: Apply the same default in final chat usage.- prompt_tokens_details=PromptTokensDetails(cached_tokens=rsp.cached_tokens), + prompt_tokens_details=PromptTokensDetails( + cached_tokens=(getattr(rsp, "cached_tokens", 0) or 0) + ),
269-270: Apply the same default in non-streaming chat usage.- prompt_tokens_details=PromptTokensDetails(cached_tokens=rsp.cached_tokens), + prompt_tokens_details=PromptTokensDetails( + cached_tokens=(getattr(rsp, "cached_tokens", 0) or 0) + ),
330-332: Apply the same default in completion streaming chunks.- total_tokens=output.length + prompt_tokens, - prompt_tokens_details=PromptTokensDetails(cached_tokens=rsp.cached_tokens)) + total_tokens=output.length + prompt_tokens, + prompt_tokens_details=PromptTokensDetails( + cached_tokens=(getattr(rsp, "cached_tokens", 0) or 0) + ))
341-342: Apply the same default in completion final usage (streaming).- prompt_tokens_details=PromptTokensDetails(cached_tokens=rsp.cached_tokens), + prompt_tokens_details=PromptTokensDetails( + cached_tokens=(getattr(rsp, "cached_tokens", 0) or 0) + ),
385-387: Apply the same default in completion non-streaming usage.- total_tokens=completion_tokens + prompt_tokens, - prompt_tokens_details=PromptTokensDetails(cached_tokens=rsp.cached_tokens)) + total_tokens=completion_tokens + prompt_tokens, + prompt_tokens_details=PromptTokensDetails( + cached_tokens=(getattr(rsp, "cached_tokens", 0) or 0) + ))
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
tensorrt_llm/_torch/pyexecutor/py_executor.py(2 hunks)tensorrt_llm/executor/result.py(2 hunks)tensorrt_llm/serve/openai_protocol.py(1 hunks)tensorrt_llm/serve/openai_server.py(3 hunks)tensorrt_llm/serve/postprocess_handlers.py(8 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Use only spaces, no tabs; indent with 4 spaces.
Files:
tensorrt_llm/serve/openai_protocol.pytensorrt_llm/executor/result.pytensorrt_llm/_torch/pyexecutor/py_executor.pytensorrt_llm/serve/openai_server.pytensorrt_llm/serve/postprocess_handlers.py
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Python code must target Python 3.8+.
Indent Python code with 4 spaces; do not use tabs.
Maintain module namespace when importing; prefer 'from package.subpackage import foo' then 'foo.SomeClass()' instead of importing the class directly.
Python filenames should be snake_case (e.g., some_file.py).
Python classes use PascalCase names.
Functions and methods use snake_case names.
Local variables use snake_case; prefix 'k' for variables that start with a number (e.g., k_99th_percentile).
Global variables use upper SNAKE_CASE prefixed with 'G' (e.g., G_MY_GLOBAL).
Constants use upper SNAKE_CASE (e.g., MY_CONSTANT).
Avoid shadowing variables from an outer scope.
Initialize all externally visible members of a class in the constructor.
Prefer docstrings for interfaces that may be used outside a file; comments for in-function or file-local interfaces.
Use Google-style docstrings for classes and functions (Sphinx-parsable).
Document attributes and variables inline so they render under the class/function docstring.
Avoid reflection when a simpler, explicit approach suffices (e.g., avoid dict(**locals()) patterns).
In try/except, catch the most specific exceptions possible.
For duck-typing try/except, keep the try body minimal and use else for the main logic.
Files:
tensorrt_llm/serve/openai_protocol.pytensorrt_llm/executor/result.pytensorrt_llm/_torch/pyexecutor/py_executor.pytensorrt_llm/serve/openai_server.pytensorrt_llm/serve/postprocess_handlers.py
**/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).
Files:
tensorrt_llm/serve/openai_protocol.pytensorrt_llm/executor/result.pytensorrt_llm/_torch/pyexecutor/py_executor.pytensorrt_llm/serve/openai_server.pytensorrt_llm/serve/postprocess_handlers.py
🧬 Code graph analysis (3)
tensorrt_llm/_torch/pyexecutor/py_executor.py (2)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (1)
attn_metadata(96-97)tensorrt_llm/logger.py (1)
warning(132-133)
tensorrt_llm/serve/openai_server.py (1)
tensorrt_llm/serve/openai_protocol.py (2)
UsageInfo(72-76)PromptTokensDetails(69-70)
tensorrt_llm/serve/postprocess_handlers.py (2)
tensorrt_llm/serve/openai_protocol.py (5)
FunctionCall(338-340)StreamOptions(65-67)ToolCall(348-352)UsageInfo(72-76)PromptTokensDetails(69-70)tensorrt_llm/executor/result.py (1)
length(132-133)
🪛 Ruff (0.12.2)
tensorrt_llm/_torch/pyexecutor/py_executor.py
1871-1871: Do not catch blind exception: Exception
(BLE001)
🔇 Additional comments (5)
tensorrt_llm/serve/openai_protocol.py (1)
76-76: Field addition looks correct; keep it optional to avoid breaking older clientsNo action needed.
tensorrt_llm/executor/result.py (1)
161-161: Initialize cached_tokens: LGTMClear default; matches downstream usage.
tensorrt_llm/_torch/pyexecutor/py_executor.py (1)
1850-1851: Propagating cached_tokens to response: LGTMThis makes the info available to higher layers without affecting control flow.
tensorrt_llm/serve/postprocess_handlers.py (2)
26-28: LGTM: new import for PromptTokensDetails.Import location and usage are consistent with the existing pattern in this file.
123-125: Remove unnecessary default oncached_tokens
rsp.cached_tokensis always initialized to an integer (default 0 inGenerationResultBase) and neverNone, so the defensive fallback is redundant.Likely an incorrect or invalid review comment.
|
@wjueyao Could you pls update the commit info of c6b2135? It is not correctly signed off, pls refer to this doc for details. https://github.com/NVIDIA/TensorRT-LLM/blob/main/CONTRIBUTING.md#signing-your-work |
b917362 to
3546f85
Compare
@LinPoly Thanks for the comment. The commit has been signed-off |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
trtllm-serve part looks good, we also need to add tests into tests/unittest/llmapi/apps/_test_openai_chat.py and tests/unittest/llmapi/apps/_test_openai_completions.py
|
Also need someone familiar with kv cache reuse/pyexecutor to review the executor change. |
@LinPoly Thanks for the reply. I added unit tests for this feature. Also would you mind assigning someone to review the executor change. Thanks in advance |
|
@QiJune @HuiGao-NV Could you pls review the |
|
@LinPoly Thanks for the comment. I added a dict |
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu>
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu>
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu>
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu>
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu>
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu>
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu>
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu>
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu>
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu>
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu> # Conflicts: # tensorrt_llm/_torch/pyexecutor/llm_request.py
|
@LinPoly Hi there, I modified the test case, and it works fine on my env. Would you mind re-run the bot and see if we pass the tests now? Thx! |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM on the llmapi changes.
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu>
|
/bot run |
|
PR_Github #20242 [ run ] triggered by Bot |
|
PR_Github #20242 [ run ] completed with state |
|
/bot run |
|
PR_Github #20273 [ run ] triggered by Bot |
|
PR_Github #20273 [ run ] completed with state |
|
/bot run |
|
PR_Github #20862 [ run ] triggered by Bot |
|
PR_Github #20862 [ run ] completed with state |
|
/bot run |
|
PR_Github #21455 [ run ] triggered by Bot |
|
PR_Github #21455 [ run ] completed with state |
|
/bot run |
|
PR_Github #21533 [ run ] triggered by Bot |
|
PR_Github #21533 [ run ] completed with state |
|
Merged, thanks for contributing @wjueyao ! |
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu> Co-authored-by: Pengyun Lin <81065165+LinPoly@users.noreply.github.com>
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu> Co-authored-by: Pengyun Lin <81065165+LinPoly@users.noreply.github.com> Signed-off-by: yufeiwu-nv <230315618+yufeiwu-nv@users.noreply.github.com>
Summary by CodeRabbit
New Features
Tests
Documentation
Description
Currently, the OpenAI server implementation of trt-llm is missing cached tokens in its response. We want to align this with OpenAI (see https://platform.openai.com/docs/guides/prompt-caching)

The num of cached tokens is read from attn_metadata.kv_cache_params.num_cached_tokens_per_seq.
Test Coverage
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)
Any new dependencies have been scanned for license and vulnerabilities
CODEOWNERS updated if ownership changes
Documentation updated as needed
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
/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...Provide a user friendly way for developers to interact with a Jenkins server.
Run
/bot [-h|--help]to print this help message.See details below for each supported subcommand.
run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]Launch build/test pipelines. All previously running jobs will be killed.
--reuse-test (optional)pipeline-id(OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.--disable-reuse-test(OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.--disable-fail-fast(OPTIONAL) : Disable fail fast on build/tests/infra failures.--skip-test(OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.--stage-list "A10-PyTorch-1, xxx"(OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.--gpu-type "A30, H100_PCIe"(OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.--test-backend "pytorch, cpp"(OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.--only-multi-gpu-test(OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.--disable-multi-gpu-test(OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.--add-multi-gpu-test(OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.--post-merge(OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx"(OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".--detailed-log(OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.--debug(OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in thestage-listparameter to access the appropriate container environment. Note: Does NOT update GitHub check status.For guidance on mapping tests to stage names, see
docs/source/reference/ci-overview.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip testing for latest commit on pull request.
--comment "Reason for skipping build/test"is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.reuse-pipeline
reuse-pipelineReuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.