KEMBAR78
[None][feat] Support cached tokens for Openai server by wjueyao · Pull Request #7637 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@wjueyao
Copy link
Contributor

@wjueyao wjueyao commented Sep 9, 2025

Summary by CodeRabbit

  • New Features

    • Usage metrics now include prompt_tokens_details with cached_tokens, aligning with OpenAI's protocol and giving visibility into how many prompt tokens were served from cache.
    • Applied across chat and completion APIs, including streaming and merged responses; cached_tokens are accumulated correctly in aggregated usage.
    • Generation results propagate cached_tokens to ensure consistent reporting in all response paths.
  • Tests

    • None noted.
  • Documentation

    • None noted.

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)
1757409196032-62cefd31-851b-41a4-80bf-7873478e404f

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 the stage-list parameter 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.md
and the scripts/test_to_stage_mapping.py helper.

kill

kill

Kill all running builds associated with pull request.

skip

skip --comment COMMENT

Skip 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-pipeline

Reuse 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.

@wjueyao wjueyao requested review from a team as code owners September 9, 2025 06:10
@wjueyao wjueyao requested a review from syuoni September 9, 2025 06:10
@svc-trtllm-gh-bot svc-trtllm-gh-bot added the Community want to contribute PRs initiated from Community label Sep 9, 2025
@wjueyao wjueyao changed the title [None][feat]support cached tokens [None][feat]Support cached tokens Sep 9, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 9, 2025

📝 Walkthrough

Walkthrough

Adds 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

Cohort / File(s) Summary of changes
Token caching capture
tensorrt_llm/_torch/pyexecutor/py_executor.py, tensorrt_llm/executor/result.py
PyExecutor now computes cached_tokens via new _fetch_cached_tokens(req_id) and attaches it to response.result. GenerationResultBase gains a cached_tokens field (initialized to 0) and propagates it in _handle_response.
OpenAI protocol model changes
tensorrt_llm/serve/openai_protocol.py
Adds PromptTokensDetails model with cached_tokens: int = 0. Extends UsageInfo with optional prompt_tokens_details: Optional[PromptTokensDetails] = None.
Server usage aggregation
tensorrt_llm/serve/openai_server.py
Imports PromptTokensDetails. Extends merge/aggregation to accumulate num_cached_tokens from each response’s usage.prompt_tokens_details.cached_tokens, populating final UsageInfo.prompt_tokens_details.
Postprocess handlers wiring
tensorrt_llm/serve/postprocess_handlers.py
Imports PromptTokensDetails. Updates streaming and non-streaming postprocessors to pass UsageInfo(prompt_tokens_details=PromptTokensDetails(cached_tokens=rsp.cached_tokens)) alongside existing token counts.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~55 minutes

Suggested reviewers

  • syuoni
  • nv-guomingz
  • Funatiq
  • Superjomn
  • ziyixiong-nv

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.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

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)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ⚠️ Warning The pull request description does not include the required PR title and summary header (the template’s @coderabbitai summary or a manually written title is missing), and the Test Coverage section is empty rather than listing the relevant tests. Although a brief description of the issue and solution is provided, the author left the template placeholders uncommented and did not replace them with actual content. Please add a PR title at the top following the repository template (e.g. **[None][feat] support cached tokens** or use @coderabbitai summary), and fill in the Test Coverage section with the names or descriptions of the tests that validate the new cached tokens functionality.
Title Check ❓ Inconclusive The title “[None][feat] Support cached tokens for Openai server” touches on the new cached tokens feature but limits the scope to the OpenAI server component, whereas the PR implements cached token support across executor, result models, protocol definitions, server, and postprocessing layers. It partly reflects the core feature but is overly narrow given the broader impact on multiple modules. Consider revising to succinctly capture the main change holistically, for example “Add cached token support across executor, result, and OpenAI protocol/server layers” to clearly reflect updates spanning multiple system components.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 crashes

usage.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_tokens

Prevent 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 responders

If 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 errors

Catching 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 guideline

Optional: 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

📥 Commits

Reviewing files that changed from the base of the PR and between ecc0e68 and c6b2135.

📒 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.py
  • tensorrt_llm/executor/result.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/serve/openai_server.py
  • tensorrt_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.py
  • tensorrt_llm/executor/result.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/serve/openai_server.py
  • tensorrt_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.py
  • tensorrt_llm/executor/result.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/serve/openai_server.py
  • tensorrt_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 clients

No action needed.

tensorrt_llm/executor/result.py (1)

161-161: Initialize cached_tokens: LGTM

Clear default; matches downstream usage.

tensorrt_llm/_torch/pyexecutor/py_executor.py (1)

1850-1851: Propagating cached_tokens to response: LGTM

This 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 on cached_tokens
rsp.cached_tokens is always initialized to an integer (default 0 in GenerationResultBase) and never None, so the defensive fallback is redundant.

Likely an incorrect or invalid review comment.

@wjueyao wjueyao changed the title [None][feat]Support cached tokens [None][feat]Support cached tokens for Openai server Sep 9, 2025
@LinPoly LinPoly changed the title [None][feat]Support cached tokens for Openai server [None][feat] Support cached tokens for Openai server Sep 9, 2025
@LinPoly LinPoly self-requested a review September 9, 2025 13:12
@LinPoly
Copy link
Collaborator

LinPoly commented Sep 9, 2025

@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

@wjueyao wjueyao force-pushed the openai_cached_tokens branch from b917362 to 3546f85 Compare September 10, 2025 04:01
@wjueyao
Copy link
Contributor Author

wjueyao commented Sep 10, 2025

@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

@LinPoly Thanks for the comment. The commit has been signed-off

Copy link
Collaborator

@LinPoly LinPoly left a 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

@LinPoly
Copy link
Collaborator

LinPoly commented Sep 10, 2025

Also need someone familiar with kv cache reuse/pyexecutor to review the executor change.

@wjueyao
Copy link
Contributor Author

wjueyao commented Sep 11, 2025

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

@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

@LinPoly
Copy link
Collaborator

LinPoly commented Sep 15, 2025

@QiJune @HuiGao-NV Could you pls review the _fetch_cached_tokens added in PyExecutor? My concern is that retrieving cached tokens seems to have n^2 time complexity for batch size and maybe CPU bottleneck when BS is large, but not sure if it is proper to change request_ids into dict.

@wjueyao wjueyao requested a review from a team as a code owner September 19, 2025 06:13
@wjueyao wjueyao requested a review from hlu1 September 19, 2025 06:13
@wjueyao
Copy link
Contributor Author

wjueyao commented Sep 19, 2025

@LinPoly Thanks for the comment. I added a dict _request_id_to_index to help reduce time complexity. _request_id_to_index is initiated when we set up request_ids. The time complexity should be reduced to n under current implementation.

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
@wjueyao
Copy link
Contributor Author

wjueyao commented Sep 28, 2025

@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!

@wjueyao wjueyao requested a review from LinPoly September 28, 2025 02:52
Copy link
Collaborator

@Superjomn Superjomn left a 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>
@LinPoly
Copy link
Collaborator

LinPoly commented Sep 29, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20242 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20242 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15264 completed with status: 'FAILURE'

@LinPoly
Copy link
Collaborator

LinPoly commented Sep 29, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20273 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20273 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15285 completed with status: 'FAILURE'

@LinPoly
Copy link
Collaborator

LinPoly commented Oct 9, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20862 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20862 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15779 completed with status: 'FAILURE'

@LinPoly
Copy link
Collaborator

LinPoly commented Oct 15, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21455 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21455 [ run ] completed with state FAILURE
/LLM/main/L0_MergeRequest_PR pipeline #16200 completed with status: 'FAILURE'

@LinPoly
Copy link
Collaborator

LinPoly commented Oct 16, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21533 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21533 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #16258 completed with status: 'SUCCESS'

@LinPoly LinPoly merged commit 9865d3d into NVIDIA:main Oct 16, 2025
2 checks passed
@LinPoly
Copy link
Collaborator

LinPoly commented Oct 16, 2025

Merged, thanks for contributing @wjueyao !

@wjueyao wjueyao deleted the openai_cached_tokens branch October 17, 2025 02:20
govind-ramnarayan pushed a commit to nv-auto-deploy/TensorRT-LLM that referenced this pull request Oct 21, 2025
Signed-off-by: wjueyao <wyao123@terpmail.umd.edu>
Co-authored-by: Pengyun Lin <81065165+LinPoly@users.noreply.github.com>
yufeiwu-nv pushed a commit to yufeiwu-nv/TensorRT-LLM that referenced this pull request Oct 24, 2025
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Community want to contribute PRs initiated from Community

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants