Skip to content

[TRTLLM-16707][feat] Add model_kwargs support to encoder CUDA graphs - #19736

Closed
tingyangk wants to merge 1 commit into
NVIDIA:release/1.3from
tingyangk:tingyangk/encoder-cuda-graph-model_kwargs-support-1.3
Closed

tingyangk wants to merge 1 commit into
NVIDIA:release/1.3from
tingyangk:tingyangk/encoder-cuda-graph-model_kwargs-support-1.3

Conversation

@tingyangk

@tingyangk tingyangk commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Dev Engineer Review

The available diff shows changes in five files. EncodeExtraInputSpec and EncodeCudaGraphConfig define and expose encoder graph extra-input configuration. The encoder graph runner adds extra-input support, and llm.encode() updates kwargs handling. The embeddings command rejects extra inputs that its HTTP endpoint cannot accept.

QA Engineer Review

No test changes.

Per-File QA Perspective

  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py — Adds encoder graph support for declared extra inputs. Verify capture, replay, and padding behavior.
  • tensorrt_llm/commands/serve.py — Rejects extra-input configuration for embeddings serving. Verify the rejection for supported config formats.
  • tensorrt_llm/llmapi/__init__.py — Changes the public package exports. Verify existing exports remain available and the new spec can be imported.
  • tensorrt_llm/llmapi/llm.py — Changes encode() kwargs handling. Verify reserved inputs and eager fallback behavior.
  • tensorrt_llm/llmapi/llm_args.py — Changes graph config and extra-input spec declarations. Verify spec validation and symbolic shape handling.

Description

LLM.encode() passes model-specific tensors (**model_kwargs, e.g. BERT token_type_ids) to the model's forward(), but the encoder runner rejected them whenever encoder CUDA graphs were enabled, so models that need an extra input had to run eagerly.

This PR replaces that rejection with a declaration. Each tensor kwarg is declared in EncodeCudaGraphConfig.extra_model_inputs; the runner gives it a static buffer, captures every bucket with a zero-filled stand-in so the graph sees the full forward() signature, and copies the caller's tensor into the buffer on each replay (zero-filling the padding tail).

A spec has exactly one symbolic dimension, which is what lets it cover every bucket:

  • "num_tokens" — scales with the packed token count (e.g. token_type_ids)
  • "batch_size" — one row per request (e.g. per-request features)

Other dimensions are fixed integers. Before forward(), a declared kwarg must be a tensor matching its spec; an undeclared tensor raises (almost always a forgotten spec, and falling back silently would hide the lost speedup), while an undeclared non-tensor runs that call eagerly instead of being frozen into the graph at its capture-time value. Tensors may be on host or device.

Example

from tensorrt_llm import LLM
from tensorrt_llm.llmapi import EncodeCudaGraphConfig, EncodeExtraInputSpec

cuda_graph_config = EncodeCudaGraphConfig(
    batch_sizes=[1, 2, 4],
    num_tokens=[64, 128],
    seq_lens=[32, 64],
    enable_padding=True,
    extra_model_inputs=[
        EncodeExtraInputSpec(name="token_type_ids", shape=("num_tokens",), dtype="int32"),
        EncodeExtraInputSpec(name="per_request_feature", shape=("batch_size", 20), dtype="float32"),
    ],
)

llm = LLM(model=MODEL, encode_only=True, cuda_graph_config=cuda_graph_config)

outputs = llm.encode(
    prompts,
    token_type_ids=token_type_ids,     # (total_tokens,) int32
    per_request_feature=per_request_feats,  # (len(prompts), 20) float32
)

Not supported

extra_model_inputs is rejected for feature-mode encoders, encoder-decoder models, and trtllm-serve embeddings.

Test Coverage

tests/unittest/llmapi/test_llm_encode.py (GPU, l0_a100)

  • TestEncodeExtraInputSpec (11): symbolic-dim rules, resolve_shape, reserved and non-identifier names, unknown dtypes, duplicate declarations.
  • Declared token_type_ids under graphs: accepted; rejects undeclared / missing / wrong dtype / wrong rank / non-tensor inputs.
  • Host and device inputs: test_encode_declared_kwarg_accepts_either_device[cpu|cuda], and test_encode_declared_kwarg_follows_values_across_devices, which alternates host/device values through one captured graph and compares each call to eager.
  • Eager paths: host input on an eager fallback; undeclared non-tensor falls back to eager.
  • "batch_size" inputs: accepted; wrong symbolic dim, literal dim and dtype rejected; test_encode_batch_size_extra_replay_matches_eager[cpu|cuda × 3|4 prompts] covers the padded-batch path.

tests/unittest/_torch/executor/engine/test_encoder.py (cpu_only, l0_cpu)

  • Undeclared tensor input raises when a graph is usable (replaces the old NotImplementedError test).
  • Multi-item batches and unsupported attention backends skip validation and run eagerly.
  • supports_metadata_type accepts only TrtllmAttentionMetadata (and subclasses).
  • _prepare_capture_inputs builds zero stand-ins with the right shape and dtype (("batch_size", 40) → (2, 40) int32, ("num_tokens", 768) → (8, 768) float16), and passes model_inputs=None when nothing is declared.

tests/unittest/llmapi/test_embedding_arch_routing.py (l0_a10)

  • trtllm-serve embeddings rejects extra_model_inputs from a YAML mapping or a parsed config, and accepts configs without them.

tests/integration/defs/accuracy/test_llm_api_pytorch_encode.py (added to l0_a100 and llm_function_core.txt)

  • test_encoder_encode_with_token_type_ids_matches_huggingface[bert-yelp]: non-zero token_type_ids through the captured graph match HuggingFace and differ from the all-zero result, proving the input reaches the model rather than being dropped.

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.

@tingyangk
tingyangk requested review from a team as code owners September 30, 2026 18:19
@tingyangk tingyangk added the api-compatible Accepted LLM API contract change that is backwards-compatible label Sep 30, 2026
@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: 24ef45c5-dc78-4026-90e6-ee0ce1021470

📥 Commits

Reviewing files that changed from the base of the PR and between acf5859 and 727b24a.

📒 Files selected for processing (14)
  • docs/source/features/embeddings.md
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
  • tensorrt_llm/_torch/pyexecutor/engine/runners/encoder.py
  • tensorrt_llm/commands/serve.py
  • tensorrt_llm/llmapi/__init__.py
  • tensorrt_llm/llmapi/llm.py
  • tensorrt_llm/llmapi/llm_args.py
  • tensorrt_llm/usage/llm_args_golden_manifest.json
  • tests/integration/defs/accuracy/test_llm_api_pytorch_encode.py
  • tests/integration/test_lists/qa/llm_function_core.txt
  • tests/integration/test_lists/test-db/l0_a100.yml
  • tests/unittest/_torch/executor/engine/test_encoder.py
  • tests/unittest/llmapi/test_embedding_arch_routing.py
  • tests/unittest/llmapi/test_llm_encode.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

Encoder CUDA graphs now support declared extra tensor inputs with symbolic token or batch dimensions. The encoder validates inputs for graph-eligible calls and stages them in graph buffers. Embeddings server configuration rejects extra-input declarations.

Changes

Encoder CUDA Graph Extra Inputs

Layer / File(s) Summary
Input declaration and API contract
tensorrt_llm/llmapi/llm_args.py, tensorrt_llm/llmapi/__init__.py, tensorrt_llm/llmapi/llm.py, tensorrt_llm/usage/llm_args_golden_manifest.json, docs/source/features/embeddings.md, tensorrt_llm/commands/serve.py, tests/unittest/llmapi/test_embedding_arch_routing.py, tests/unittest/llmapi/test_llm_encode.py
Adds EncodeExtraInputSpec and extra_model_inputs configuration, defines validation for names, shapes, and dtypes, and exports the specification. Documents graph behavior and rejects non-empty extra-input declarations in embeddings server configuration.
Encoder input validation and graph selection
tensorrt_llm/_torch/pyexecutor/engine/runners/encoder.py, tests/unittest/_torch/executor/engine/test_encoder.py, tests/unittest/llmapi/test_llm_encode.py
Passes declarations to the encoder runner. Graph-eligible calls validate declared tensor inputs; calls that cannot use graphs fall back to eager execution.
Graph input buffers and replay
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py, tests/unittest/_torch/executor/engine/test_encoder.py, tests/unittest/llmapi/test_llm_encode.py
Allocates static host and device buffers for declared inputs, stages values with padding, and captures bucket-sized input views. Tests cover capture shapes and graph-versus-eager outputs.
BERT token-type integration verification
tests/integration/defs/accuracy/test_llm_api_pytorch_encode.py, tests/integration/test_lists/qa/llm_function_core.txt, tests/integration/test_lists/test-db/l0_a100.yml
Adds a BERT test for token_type_ids propagation through graph replay and comparison with Hugging Face output. Registers the test in integration lists.

Priority: ⬇️ Low

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

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant EncodeAPI
  participant EncoderRunner
  participant EncoderCUDAGraphRunner
  EncodeAPI->>EncoderRunner: pass declared extra tensors
  EncoderRunner->>EncoderCUDAGraphRunner: validate and stage extra tensors
  EncoderCUDAGraphRunner->>EncoderCUDAGraphRunner: replay captured token graph
Loading

Suggested reviewers: lori-ren, xwang233

Merge Risk: ⚪ Minimal · up to 727b2

This change adds optional extra tensor inputs for encoder CUDA graphs, with validation and eager fallback for ineligible calls. No concrete merge-blocking risk was identified from the supplied context. GPU replay behavior still depends on the listed unit and integration tests passing.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 90 functions across 10 files. (4 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and clearly identifies the main change: adding model_kwargs support to encoder CUDA graphs. It also follows the required ticket and type format.
Description check ✅ Passed The description explains the problem, solution, API usage, limitations, and relevant test coverage. It includes the required sections and checklist. Test results and explicit API-label or reviewer-sta…
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 57.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 90 functions across 10 files. (4 skipped: 4 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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

@Mgluhovskoi Mgluhovskoi 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.

Approved from the telemetry perspective. Capturing the new shape fields is tracked separately in #19779. Please regenerate the golden manifest after the other PR merges so both shape entries use list[tuple[int|literal]].

@brnguyen2 brnguyen2 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.

Approving — the comments below are optional touch-ups, not blockers.

This is a cherry-pick of #19439 (merged to main on 2026-10-02); a range-diff against that commit shows only the _buffers→_deps and PackedInputs→PackedEncoderBatch adaptations the release branch needs. The PR description and title don't say so. Please link #19439 in the description and use the same title as the main commit so the two are traceable to each other.

Three process items before merge:

  • Release-branch scope. This is a [feat] landing on release/1.3 after the branch's version string moved to 1.3.0. Please note the release owner's sign-off on the PR so it's clear this was deliberately pulled into 1.3 rather than waiting for the next release.
  • Release notes. docs/source/release-notes.md already has a "TensorRT-LLM Release 1.3 / API Changes" section. This adds a public config class (EncodeExtraInputSpec), a new EncodeCudaGraphConfig.extra_model_inputs field, and changes behavior under encoder CUDA graphs: tensor kwargs now raise ValueError instead of NotImplementedError, and non-tensor kwargs now run eagerly instead of raising. A line there would save users from discovering it in the diff.
  • Follow-ups go to main first. Since the code is identical to main, anything raised inline below applies there too; fix on main and re-pick rather than diverging the branch.

Local sanity: the CPU-only tests in test_encoder.py, test_embedding_arch_routing.py and TestEncodeExtraInputSpec pass against a prebuilt wheel (50 tests). The GPU parity tests and the A100 accuracy test are CI's to confirm.

raise ValueError(
"Encoder received tensor model_kwargs not declared in "
f"cuda_graph_config.extra_model_inputs: {undeclared_tensor}. "
"Add them to the spec or disable encoder CUDA graphs. "

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.

position_ids is not in ENCODER_RUNNER_MANAGED_INPUTS, so encode(prompts, position_ids=<tensor>) reaches this check as an undeclared tensor and the message tells the user to add it to extra_model_inputs. But EncodeExtraInputSpec._validate_name rejects position_ids as reserved, so the advice is a dead end. Either filter with ENCODER_RESERVED_INPUT_NAMES here (and say position_ids is ignored under graphs), or special-case the message for reserved names. Same code is on main via #19439; fix there and re-pick.

torch.narrow(host_buf, axis, 0, actual_len).copy_(user_tensor)
if pad_len > 0:
torch.narrow(host_buf, axis, actual_len, pad_len).zero_()
device_buf.copy_(host_buf, non_blocking=True)

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.

For a spec whose symbolic dim is not axis 0 (the validator allows shape=(32, "batch_size")), torch.narrow along that axis gives strided host and device views. A copy_(..., non_blocking=True) from a non-contiguous pinned source goes through a temporary contiguous buffer and loses its asynchrony, and the captured graph reads a strided view too. Not a correctness problem, but the non-zero-axis case is only exercised at the Pydantic level (test_batch_size_symbolic_axis_nonzero). Either add a GPU parity test for a non-zero symbolic axis, or document in the shape field description that the symbolic dim should come first for the asynchronous fast path.

@tingyangk tingyangk closed this Oct 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api-compatible Accepted LLM API contract change that is backwards-compatible

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants