Skip to content

[6915422] Fix TensorRT 11 inference shape validation - #2798

Merged
ajrasane merged 4 commits into
mainfrom
ajrasane/trt-shape-validation
Oct 28, 2026
Merged

ajrasane merged 4 commits into
mainfrom
ajrasane/trt-shape-validation

Conversation

@ajrasane

@ajrasane ajrasane commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: Bug fix

TensorRT inference fails during session initialization on TensorRT 11 because IExecutionContext.all_shape_inputs_specified was removed. Replace that legacy check with infer_shapes() after input values are available, including when io_shapes is supplied.

Select the optimization profile before setting input dimensions, honor TensorRT's host/device buffer locations, and reject missing inputs and invalid dimensions. Host input copies finish before shape inference reads their values. Add real-engine regression coverage and a changelog entry.

The 0.48.0 changelog also records the already merged TensorRT plugin compatibility fixes from #2796 and #2801.

Usage

pytest -o addopts= tests/gpu/torch/deploy/_runtime/test_trt_client.py -k test_trt_session_inference

Testing

  • Four real-engine cases pass on TensorRT 11.1.0.106 and 10.13.3.9: static shapes, inferred static shapes, dynamic dimensions, and a shape-tensor reshape. They compare actual inference outputs and check missing inputs, invalid profile dimensions, and invalid reshape values.
  • Reverting the production fix makes all four cases fail on TensorRT 11 with the removed-property error. The minimal identity-engine reproduction completes inference with the fix.
  • Full test module: 4 passed, 11 skipped per environment. Four existing compile/profile tests require an ORT TensorRT provider library that cannot load libcublas.so.12; seven manual vision tests were not selected. Full ImageNet accuracy and FP8/INT8 evaluation were not run.
  • Focused pre-commit hooks and git diff --check pass.
  • A 100-iteration identity-engine sample on TensorRT 10 with [16, 3, 224, 224] buffers showed unchanged peak allocated GPU memory (67,436,544 bytes). Median inference time was 40.3 μs before and 43.4 μs after validation.

Before your PR is "Ready for review"

Make sure you read and follow Contributor guidelines and your commits are signed (git commit -s -S).

Make sure you read and follow the Security Best Practices (e.g. avoiding hardcoded trust_remote_code=True, torch.load(..., weights_only=False), pickle, etc.).

  • Is this change backward compatible?: ✅
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: N/A
  • Did you write any new necessary tests?: ✅
  • Did you update Changelog?: ✅

Summary by CodeRabbit

  • Bug Fixes
    • Improved TensorRT inference initialization for static, dynamic, and shape-tensor inputs.
    • Improved handling of inputs stored on the host or GPU during inference.
    • Added validation for supplied inputs and shapes. Missing inputs, invalid shapes, and dynamic shapes outside the supported profile now produce errors.
    • Fixed preprocessing for custom TensorRT plugin libraries and corrected the custom plugin example build process.

@copy-pr-bot

copy-pr-bot Bot commented Oct 14, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review.

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: NVIDIA/Model-Optimizer/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Enterprise
  • Run ID: 97c3ddde-f41d-4c6c-9a41-a85758f50923
📥 Commits

Reviewing files that changed from the base of the PR and between 8785337 and df38cb7.

📒 Files selected for processing: 1
  • CHANGELOG.rst
🚧 Files skipped from review as they are similar to previous changes: 1
  • CHANGELOG.rst

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

TensorRT session initialization now selects an optimization profile before configuring input shapes and allocates tensors according to engine tensor location. Inference validates input counts and shape inference results. Tests cover four input kinds and invalid-input cases. The changelog lists TensorRT fixes under 0.48.0 and removes an entry from 0.49.0.

Changes: TensorRT Session Inference

Layer / File(s) Summary
Configure TensorRT session inputs
modelopt/torch/_deploy/_runtime/trt_client.py
Initialization selects optimization profile 0 before configuring shapes. It allocates tensors on CPU for host-located engine tensors and on CUDA otherwise. It asserts that TensorRT accepts each input shape.
Validate inference inputs and execution
modelopt/torch/_deploy/_runtime/trt_client.py, tests/gpu/torch/deploy/_runtime/test_trt_client.py, CHANGELOG.rst
Inference checks the supplied input count. If an initialized input tensor is on CPU, it synchronizes the stream before shape inference. It then asserts that no inputs are missing. Tests cover static, inferred-static, dynamic, and shape-tensor inputs, including invalid-input cases. The changelog lists TensorRT fixes under 0.48.0 and removes an entry from 0.49.0.

Priority: Normal

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

Change: Bug fix

Suggested reviewers: aanoosheh

Merge Risk: Minimal · previous review df38c

No identified issue blocks merging this change after normal checks.

Pre-merge checks: Passed 5 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 2 files. (1 skipped: 1 … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 5 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: fixing TensorRT 11 inference shape validation.
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.
Security Anti-Patterns Passed PASS. The pull request changes only TensorRT runtime logic, tests, and the changelog. The added Python code contains no unsafe torch.load, numpy.load, trust_remote_code=True, eval(), exec(), or # nose…
Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 2 files. (1 skipped: 1 unsupported.)

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@ajrasane
ajrasane marked this pull request as ready for review October 14, 2026 18:03
@ajrasane
ajrasane requested review from a team as code owners October 14, 2026 18:03
@ajrasane
ajrasane requested a review from cjluo-nv October 14, 2026 18:03

@cjluo-nv cjluo-nv 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.

Bot review (bedrock-claude-opus-5-5) — DM the bot to share feedback.

LGTM: the fix is correct and small, and real-engine regression tests cover it. I'm only asking for a human because it edits the skip gating in an existing test file.

Needs action:

  • Confirm the skip change in tests/gpu/torch/deploy/_runtime/test_trt_client.py: module-level skips are now inside _compile_and_profile plus importorskip("tensorrt"). Existing tests keep the same gating and assertions, and the new tests no longer need trtexec or ORT's TRT EP.

No action needed:

  • The fix drops the removed all_shape_inputs_specified property. It now selects the profile before calling set_input_shape, checks that call's return value, and runs infer_shapes() on each call to run() after the inputs are copied. When any input lives on the host, it synchronizes first so shape tensors are read correctly.
  • Host-located tensors are now allocated on the CPU, which shape-tensor inputs need.
  • The tests cover static, inferred-static, dynamic and shape-tensor engines. They check outputs and the failure paths: wrong input count, out-of-profile dims and an invalid reshape. I read the tests but didn't run them; the PR reports they pass on TRT 10.13 and 11.1.
  • infer_shapes() now runs on every call, which costs about 3 μs per call according to the PR's measurement. That's acceptable.

@github-actions

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-10-28 19:22 UTC

@ajrasane

Copy link
Copy Markdown
Contributor Author

Confirmed the dependency-gating change against the base diff and the TensorRT 10.13.3.9 / 11.1.0.106 runs:

  • Existing compile/profile tests still call both skip_if_no_tensorrt() and skip_if_no_trtexec() before compilation. All existing latency, profiling-results, client-type, and numerical-output assertions are unchanged. Model/input preparation now precedes the helper-level guards; those guards still determine whether compilation runs.
  • pytest.importorskip("tensorrt") retains the module's TensorRT Python-package requirement. The new regression cases build and execute engines directly, so they do not require trtexec or a working ORT TensorRT execution provider. This is not a claim that transitive Python dependencies are absent.
  • The full module produced 4 passed, 11 skipped on each TensorRT version: the four original compile/profile cases skipped because ORT's provider could not load libcublas.so.12, the seven manual vision cases stayed skipped, and all four new real-engine cases ran and passed.

No source change is needed for this confirmation. This is automated verification, not the human sign-off requested by the review. Full ImageNet accuracy and FP8/INT8 evaluation remain unverified, as disclosed in the PR description.

Comment thread CHANGELOG.rst Outdated

**Bug Fixes**

- Fix TensorRT inference initialization on TensorRT 11 and retain shape validation for static, dynamic, and shape-tensor inputs.

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.

is this under 0.48.0?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, I have moved this to the 0.48 entry in changelog.

@ajrasane
ajrasane force-pushed the ajrasane/trt-shape-validation branch from adef98c to 35d82b5 Compare October 14, 2026 20:16
Comment thread CHANGELOG.rst

- Fix ONNX preprocessing with custom TensorRT plugin libraries on TensorRT 11.
- Fix building the custom TensorRT plugin example with TensorRT 11.
- Fix TensorRT inference initialization on TensorRT 11 and retain shape validation for static, dynamic, and shape-tensor inputs.

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.

@ajrasane are all 3 lines addressed in this PR or is that to cover the changelog cherry-picks for other related PRs?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

These are acutally the changelong entries from #2801 and #2796 that were added to the 0.49 section by mistake. They belong to the 0.48 section. This PR only fixes the last item.

@gcunhase gcunhase 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, added a minor comment.

@ajrasane
ajrasane force-pushed the ajrasane/trt-shape-validation branch from 8785337 to df38cb7 Compare October 15, 2026 19:00
@codecov

codecov Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 78.44%. Comparing base (7092db6) to head (7c1e074).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2798      +/-   ##
==========================================
+ Coverage   73.86%   78.44%   +4.57%     
==========================================
  Files         662      662              
  Lines       75835    77541    +1706     
==========================================
+ Hits        56019    60826    +4807     
+ Misses      19816    16715    -3101     
Flag Coverage Δ
examples-diffusers 19.92% <0.00%> (+0.03%) ⬆️
examples-gpt-oss 13.47% <0.00%> (+0.04%) ⬆️
examples-hf_ptq 23.47% <0.00%> (-0.01%) ⬇️
examples-llm_distill 13.54% <0.00%> (+0.04%) ⬆️
examples-llm_eval 17.22% <0.00%> (+0.04%) ⬆️
examples-llm_qat 17.39% <0.00%> (+0.01%) ⬆️
examples-llm_sparsity 16.75% <0.00%> (+0.03%) ⬆️
examples-megatron_bridge 26.51% <0.00%> (-0.21%) ⬇️
examples-specdec_bench 13.25% <0.00%> (+0.04%) ⬆️
examples-speculative_decoding 17.47% <0.00%> (-0.03%) ⬇️
examples-torch_onnx 21.23% <0.00%> (+0.02%) ⬆️
examples-torch_trt 15.21% <0.00%> (+0.04%) ⬆️
examples-vllm_serve 17.43% <0.00%> (+0.04%) ⬆️
gpu 59.07% <100.00%> (+24.28%) ⬆️
regression 15.04% <0.00%> (+0.03%) ⬆️
unit 61.83% <0.00%> (-0.02%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ajrasane
ajrasane force-pushed the ajrasane/trt-shape-validation branch from df38cb7 to 8c3e8b1 Compare October 16, 2026 17:30
Use infer_shapes after input values are copied instead of the execution-context property removed in TensorRT 11. Select the profile before input dimensions and allocate shape buffers at their declared locations.

Signed-off-by: ajrasane <[email protected]>
@ajrasane
ajrasane force-pushed the ajrasane/trt-shape-validation branch from 8c3e8b1 to a7304e2 Compare October 16, 2026 20:00
@ajrasane
ajrasane enabled auto-merge (squash) October 16, 2026 20:08
Resolve the TensorRT runtime overlap while retaining deferred shape inference and the removal of the obsolete API. Preserve upstream changelog additions and the PR's TensorRT 0.48 entries.

Signed-off-by: Ajinkya Rasane <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Oct 28, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@ajrasane

Copy link
Copy Markdown
Contributor Author

/ok to test 7c1e074

@ajrasane
ajrasane merged commit 86c2177 into main Oct 28, 2026
51 checks passed
@ajrasane
ajrasane deleted the ajrasane/trt-shape-validation branch October 28, 2026 19:22
@rohansjoshi rohansjoshi added the cherry-pick-done Added by bot once PR is cherry-picked to the release branch label Oct 28, 2026
rohansjoshi added a commit that referenced this pull request Oct 28, 2026
## Cherry-picked PRs

- #2980
- #3041
- #2798
- #2979

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* INT4 and W4A8 exports now include more accurate quantization metadata.
* Layerwise checkpoint loading is safer and provides clearer guidance
when a checkpoint cannot be resumed.
* **Bug Fixes**
* TensorRT inference now handles dynamic and host-based inputs more
reliably, validates input shapes and counts, and improves
initialization.
* Added warnings when fused-expert quantization stages are skipped or
ModelOpt state saving is unsupported during layerwise export.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Fridah-nv <[email protected]>
Signed-off-by: Rohan Joshi <[email protected]>
Signed-off-by: yingguo-trt <[email protected]>
Signed-off-by: ajrasane <[email protected]>
Co-authored-by: Frida Hou <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: yingguo-trt <[email protected]>
Co-authored-by: Ajinkya Rasane <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cherry-pick-0.48.0 cherry-pick-done Added by bot once PR is cherry-picked to the release branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants