Skip to content

[6403893][ONNX][AutoCast] Fix false-success TRT parse for large ModelProto#1928

Open
galagam wants to merge 2 commits into
NVIDIA:mainfrom
galagam:dev-gagam-bug-6403893
Open

[6403893][ONNX][AutoCast] Fix false-success TRT parse for large ModelProto#1928
galagam wants to merge 2 commits into
NVIDIA:mainfrom
galagam:dev-gagam-bug-6403893

Conversation

@galagam

@galagam galagam commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: ? Bugfix

get_custom_layers silently returned 0 layers/tensors for in-memory ModelProtos at/above the protobuf 2GiB limit. Route such models through a temporary external-data file and parse_from_file(), matching the string-path behavior. Verified on the 8.12GB VLA trunk (28 layers/5468 tensors) and a synthetic 2.2GB model. Adds a regression test forcing the file-backed path.

Usage

# Add a code snippet demonstrating how to use this

Testing

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?: ❌
  • Did you get Claude approval on this PR?: ✅

Additional Information

Summary by CodeRabbit

Summary

  • Bug Fixes

    • Improved ONNX-to-TensorRT custom layer handling for very large or difficult in-memory ONNX models by automatically switching to a file-backed parsing workflow when needed (via temporary external-data files), with a conservative fallback if size checks fail.
    • Ensured custom layer and tensor metadata remain consistent between in-memory parsing and the file-backed approach.
  • Tests

    • Added a regression test validating identical get_custom_layers results for in-memory models versus file-path parsing, including a forced file-backed routing scenario.

@galagam galagam requested review from a team as code owners July 6, 2026 10:28
@galagam galagam requested a review from cjluo-nv July 6, 2026 10:28
@galagam

galagam commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

/claude review

@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 24d6b33e-55e9-4e6a-be6a-7315bd54d44a

📥 Commits

Reviewing files that changed from the base of the PR and between d5228a7 and 55b0296.

📒 Files selected for processing (2)
  • modelopt/onnx/trt_utils.py
  • tests/gpu/onnx/quantization/test_plugin.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • modelopt/onnx/trt_utils.py
  • tests/gpu/onnx/quantization/test_plugin.py

📝 Walkthrough

Walkthrough

Adds a helper to detect oversized in-memory ONNX models, routes those models through temporary external-data files for TensorRT parsing, and adds a regression test that compares parsing results across modes.

Changes

File-backed ONNX parsing support

Layer / File(s) Summary
ByteSize check and imports
modelopt/onnx/trt_utils.py
Adds copy import and _requires_file_backed_parse() to check ModelProto.ByteSize() against onnx.checker.MAXIMUM_PROTOBUF, defaulting to True on computation failure with debug logging.
Three-way parsing flow in get_custom_layers
modelopt/onnx/trt_utils.py
Updates get_custom_layers() to use parse_from_file for string paths, deep-copy + onnx.save external-data + parse_from_file for large in-memory models, and direct parse(SerializeToString()) otherwise, preserving existing error aggregation.
Regression test for parity
tests/gpu/onnx/quantization/test_plugin.py
Imports get_custom_layers and adds test_get_custom_layers_file_backed_matches_in_memory, comparing results across file-path, in-memory, and monkeypatched forced file-backed parsing.

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

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant get_custom_layers
  participant _requires_file_backed_parse
  participant TempFileSave
  participant TrtParser

  Caller->>get_custom_layers: onnx_path (str or ModelProto)
  alt onnx_path is string
    get_custom_layers->>TrtParser: parse_from_file(onnx_path)
  else onnx_path is ModelProto
    get_custom_layers->>_requires_file_backed_parse: check ByteSize()
    alt requires file-backed parse
      _requires_file_backed_parse-->>get_custom_layers: True
      get_custom_layers->>TempFileSave: deepcopy + save external data
      get_custom_layers->>TrtParser: parse_from_file(temp_path)
    else
      _requires_file_backed_parse-->>get_custom_layers: False
      get_custom_layers->>TrtParser: parse(SerializeToString())
    end
  end
  TrtParser-->>get_custom_layers: parsed layers or errors
Loading
🚥 Pre-merge checks | ✅ 5 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Security Anti-Patterns ❓ Inconclusive Repository clone failed, so this custom check could not run with code access. Retry the review run. If this persists, inspect pre-merge custom-check logs for infrastructure or agent runtime failures.
✅ 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 accurately describes the core bug fix: TensorRT parsing behavior for large in-memory ModelProto inputs.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

with tempfile.TemporaryDirectory(prefix="modelopt_trt_") as tmpdir:
model_path = os.path.join(tmpdir, "model.onnx")
# Deep-copy so externalization doesn't strip weights from the caller's model.
model_copy = copy.deepcopy(onnx_path)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[SUGGESTION] copy.deepcopy(onnx_path) transiently doubles peak RAM for exactly the models this path targets — an 8GB ModelProto needs ~16GB before onnx.save streams weights to disk. The deep-copy is necessary for correctness (onnx.save(save_as_external_data=True) mutates the proto in place, stripping raw_data from the caller's model), so this isn't a bug — but on the 8GB VLA trunk case cited in the PR description it may be tight on constrained hosts.

If it ever bites, an alternative that avoids the copy is to externalize in place and restore afterward (e.g. onnx.save(onnx_path, ...) then onnx.load_external_data_for_model(onnx_path, tmpdir) to re-hydrate the caller's proto), or wrap in try/finally to guarantee re-hydration on parse failure. Non-blocking; the current approach is the safest correctness-wise.

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.

The peak memory usage is at ReferenceRunner where we define an auxiliary graph with every intermediate tensor being a graph output. The 2x memory usage here is not a bottleneck.

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.

Agree!

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude review passed — no blocking issues found. LGTM

Scope: Reviewed the 2 files in this PR's authoritative changed-file list (modelopt/onnx/trt_utils.py, tests/gpu/onnx/quantization/test_plugin.py). The two-dot git diff origin/main HEAD surfaced many unrelated files due to the shallow-checkout divergence between the local origin/main tip and the true merge base — those are not part of this PR and were excluded.

Findings: CRITICAL: 0, IMPORTANT: 0, SUGGESTION: 1

Assessment — low risk. Focused, well-targeted bugfix. get_custom_layers previously silently returned an empty network (0 layers/0 tensors) for in-memory ModelProtos at/above the protobuf 2 GiB limit because TensorRT's parser.parse(bytes) fails quietly while SerializeToString() succeeds. The fix routes over-limit (or un-sizeable) in-memory models through a temporary external-data file + parse_from_file(), matching the existing string-path branch and ModelOpt's file-backed policy elsewhere in this module.

Verified:

  • onnx.checker.MAXIMUM_PROTOBUF is a valid constant, already used with the same >= MAXIMUM_PROTOBUF idiom at trt_utils.py:382.
  • The ByteSize()-overflow except branch conservatively routes to the file path, consistent with load_onnx_model's handling.
  • copy.deepcopy correctly shields the caller's model from in-place externalization by onnx.save; both in-memory callers pass a model the caller still owns.
  • The regression test forces the file-backed path via monkeypatch and cross-checks results against both the in-memory fast path and the string-path baseline. Backward compatible — the small-model fast path is unchanged.

The single SUGGESTION concerns transient peak-RAM doubling from the deep-copy on multi-GB models — non-blocking, and the current approach is the correctness-safe choice.

@galagam galagam self-assigned this Jul 6, 2026
@galagam galagam requested review from ajrasane and gcunhase July 6, 2026 10:37
@codecov

codecov Bot commented Jul 6, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 21.05263% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.71%. Comparing base (6b4ad85) to head (55b0296).

Files with missing lines Patch % Lines
modelopt/onnx/trt_utils.py 21.05% 15 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1928      +/-   ##
==========================================
- Coverage   77.73%   77.71%   -0.02%     
==========================================
  Files         519      519              
  Lines       57886    57902      +16     
==========================================
+ Hits        45000    45001       +1     
- Misses      12886    12901      +15     
Flag Coverage Δ
unit 55.25% <21.05%> (-0.01%) ⬇️

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.

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

Do you think the comment from Claude review should be a concern?

The single SUGGESTION concerns transient peak-RAM doubling from the deep-copy on multi-GB models.

Otherwise, LGTM!

@galagam

galagam commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

Do you think the comment from Claude review should be a concern?

The single SUGGESTION concerns transient peak-RAM doubling from the deep-copy on multi-GB models.

Otherwise, LGTM!

@gcunhase Thanks for holding me accountable... Replied in the original thread.
#1928 (comment)

@galagam galagam force-pushed the dev-gagam-bug-6403893 branch from b52dc3f to c8a5a30 Compare July 7, 2026 11:15
@copy-pr-bot

copy-pr-bot Bot commented Jul 7, 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.

@coderabbitai coderabbitai Bot 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.

Warning

CodeRabbit couldn't request changes on this pull request because it doesn't have sufficient GitHub permissions.

Please grant CodeRabbit Pull requests: Read and write permission and re-run the review.

👉 Steps to fix this

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/gpu/onnx/quantization/test_plugin.py`:
- Line 163: Move the `modelopt.onnx.trt_utils as trt_utils` import out of the
test body and into the module-level imports in `test_plugin.py`. This import is
only used to support `monkeypatch.setattr`, so it should be declared alongside
the other top-level `modelopt.onnx.trt_utils` imports rather than inside the
test. Remove the in-function import and keep the `trt_utils` reference available
for the existing monkeypatch usage.
🪄 Autofix (Beta)

❌ Autofix failed (check again to retry)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: e2d67f9b-19fd-4e4f-a16a-79d54c790fd8

📥 Commits

Reviewing files that changed from the base of the PR and between d290839 and c8a5a30.

📒 Files selected for processing (2)
  • modelopt/onnx/trt_utils.py
  • tests/gpu/onnx/quantization/test_plugin.py

Comment thread tests/gpu/onnx/quantization/test_plugin.py Outdated
@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

An unexpected error occurred while generating fixes: Not Found - https://docs.github.com/rest/git/refs#get-a-reference

galagam added 2 commits July 8, 2026 17:13
…Proto

get_custom_layers silently returned 0 layers/tensors for in-memory
ModelProtos at/above the protobuf 2GiB limit. Route such models through a
temporary external-data file and parse_from_file(), matching the string-path
behavior. Verified on the 8.12GB VLA trunk (28 layers/5468 tensors) and a
synthetic 2.2GB model. Adds a regression test forcing the file-backed path.

Signed-off-by: Gal Hubara Agam <96368689+galagam@users.noreply.github.com>
Signed-off-by: Gal Hubara-Agam <96368689+galagam@users.noreply.github.com>
@galagam galagam force-pushed the dev-gagam-bug-6403893 branch from d5228a7 to 55b0296 Compare July 8, 2026 14:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants