Skip to content

feat(executorch): optional .ptd file for TensorRT engines, refuse engines without weights - #4848

Merged
cehongwang merged 4 commits into
pytorch:mainfrom
shoumikhin:executorch-external-engine-data
Oct 21, 2026
Merged

cehongwang merged 4 commits into
pytorch:mainfrom
shoumikhin:executorch-external-engine-data

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What is wrong today

The ExecuTorch TensorRT delegate stores every engine, weights included, inside the .pte, so that file is as large as the model. ExecuTorch keeps large data in a .ptd file beside it, and other backends already put their weights there.

Also, a TensorRT engine can be saved without its weights (STRIP_PLAN, for example immutable_weights=False, strip_engine_weights=True, or EXCLUDE_WEIGHTS). It loads and runs with no error, but silently computes with placeholder weights.

What this change does

  1. Refuse an engine saved without its weights. The delegate checks getEngineStat(kSTRIPPED_WEIGHTS_SIZE) (-1 with weights) and fails with InvalidProgram. A stripped engine with no weights at all (kTOTAL_WEIGHTS_SIZE is 0) still loads, since it has nothing to restore. So does one that was refit and saved again with its weights. For an ordinary engine with weights, TensorRT logs one harmless warning about this query. The README explains it.
  2. Fix two test leaks. Two tests left a copy of the delegate module in sys.modules. A later test in the same process imported that copy, which registers nothing, and failed with "Backend TensorRTBackend is not registered".
  3. external_engine_data, a new keyword on torch_tensorrt.save and torch_tensorrt.executorch.export. It takes the file name without .ptd:
torch_tensorrt.save(trt_module, "out/model.pte", output_format="executorch",
                    arg_inputs=inputs, external_engine_data="engines")
# out/model.pte (small) + out/engines.ptd (the engine)
program = Runtime.get().load_program("out/model.pte", data_path="out/engines.ptd")

Each engine is already saved as named data, with only its key in the delegate blob. This keyword moves that data from the .pte into the .ptd. The blob and the engine bytes stay the same. Without the keyword, nothing changes.

Loading without the .ptd, or with one that lacks the engine, fails with InvalidExternalData and a message that asks for the .ptd. The name may not contain a directory, a drive (D:engines) or a NUL, or end in .ptd. With the CUDA backend, pass aoti_cuda_blob to share its file: the Python loader takes one data file.

What was tested

On Jetson AGX Thor (TensorRT 11.4, the pinned ExecuTorch), with the delegate built from this branch:

  • The C++ delegate tests for the code this change touches pass, including the new cases for stripped engines, the missing .ptd and read errors.
  • A small model saved with external_engine_data writes a 5 KB .pte and a 200 KB .ptd (209 KB embedded). It runs through the ExecuTorch runtime, matches eager PyTorch, and matches the embedded program bit for bit.
  • Loading it without the .ptd fails with InvalidExternalData.
  • A model compiled with strip_engine_weights=True is refused at load.

@meta-cla meta-cla Bot added the cla signed label Oct 11, 2026
@github-actions github-actions Bot added component: tests Issues re: Tests component: api [Python] Issues re: Python API component: api [C++] Issues re: C++ API labels Oct 11, 2026
@github-actions
github-actions Bot requested a review from narendasan October 11, 2026 01:26
@shoumikhin
shoumikhin force-pushed the executorch-external-engine-data branch 4 times, most recently from 846c968 to bb19487 Compare October 12, 2026 06:39
@shoumikhin
shoumikhin marked this pull request as ready for review October 12, 2026 06:47
@narendasan narendasan added this to the v2.15.0 milestone Oct 13, 2026
@shoumikhin
shoumikhin force-pushed the executorch-external-engine-data branch 2 times, most recently from f5562c6 to e1f15bc Compare October 21, 2026 01:31
A TensorRT plan can be serialized without its weights: either built with
STRIP_PLAN, or saved with the EXCLUDE_WEIGHTS flag. Such a plan deserializes
and runs without any error, but it computes with placeholder weights. The
ExecuTorch delegate never refits an engine, so today it loads such a plan and
can silently return wrong results. For example, a model compiled with
immutable_weights=False and strip_engine_weights=True gives such a plan.

The delegate now asks the deserialized engine itself whether it was
serialized without its weights and refuses the load with InvalidProgram.
ICudaEngine::getEngineStat with kSTRIPPED_WEIGHTS_SIZE is -1 for a plan that
carries its weights, and a stripped plan can report 0, so 0 counts as
stripped. A stripped plan whose kTOTAL_WEIGHTS_SIZE is 0 has no weights to
restore and computes correctly, so it still loads. The error says the engine
has no weights, and asks to compile it with strip_engine_weights=False, or to
serialize it with its weights, and export again. The check reads the engine,
not the export settings, so it also catches programs exported before this
change and plans produced by any other tool. A stripped plan that was refit
and serialized again with its weights reads -1 and still loads.

Querying the stripped size of an engine built without STRIP_PLAN makes
TensorRT log one warning per deserialization, which the delegate forwards at
Info level. The total is read first, so an engine without weights logs
nothing. An engine with weights still logs it: isRefittable() cannot tell the
cases apart beforehand, since a plan built with STRIP_PLAN alone reports that
it is not refittable. The README says so.

The C++ tests build the same matmul engine with and without STRIP_PLAN and
check that the stripped plan is refused on both the shared and the private
load path, and when it arrives as named data the way a .pte stores it. A
second stripped matmul, small enough that the stripped size reads 0, is
refused on both paths too. A stripped relu with no weights loads on both
paths and computes correctly. A third check refits the stripped engine,
serializes it with its weights, and checks that it loads and matches the
ordinary engine.
…hind

test_examples_use_the_module_loader records the example's import of
torch_tensorrt_executorch_runtime with a finder whose loader creates an empty
module. The import system puts that module into sys.modules, and nothing
removes it at teardown: the test only deletes the name before it runs.

Any later test in the same pytest process that imports the real package then
gets the empty stand-in instead. The import registers nothing, so loading a
TensorRT-delegated program fails with "Backend TensorRTBackend is not
registered". Under pytest-xdist this depends on which tests share a worker.

The loader now records the stand-in through monkeypatch, so teardown removes
it. A new test runs that test in its own pytest process and checks that the
stand-in is gone from sys.modules afterwards. It fails without the fix.
test_the_kept_entry_points_actually_warn_and_forward imports
torch_tensorrt_executorch_runtime from the source tree with delegate
registration turned off. It removes any earlier copy from sys.modules through
monkeypatch, so teardown puts that copy back, but nothing removes the copy the
test itself imported when there was none before.

Any later test in the same pytest process that imports the real package then
gets this unregistered copy instead. The import registers nothing, so loading
a TensorRT-delegated program fails with "Backend TensorRTBackend is not
registered". Under pytest-xdist this depends on which test files share a
worker.

The test now records the module it imported through monkeypatch, so teardown
removes it. A new test runs that test in its own pytest process and checks
that the module is gone from sys.modules afterwards. It fails without the fix.
…e_data

The TensorRT delegate stores every engine, weights included, inside the .pte,
so the program file is as large as the model. ExecuTorch has a standard place
for large data, the .ptd file next to the .pte, and other backends already
keep their weights there.

export() and save() take a new keyword, external_engine_data, naming that
file without its .ptd extension. preprocess already stores each engine as
named data under the key tensorrt_engine_<sha256 of the engine>, with only
the key in the blob. With the keyword, it tags that named data with the given
name, so ExecuTorch writes the engine to <name>.ptd instead of into the .pte.
save() already writes the .ptd next to the .pte. The blob, the key and the
engine bytes are the same either way, so nothing is rebuilt or refit, results
are identical, and the engine is still handed over without a copy.

    torch_tensorrt.save(trt_module, "out/model.pte", output_format="executorch",
                        arg_inputs=inputs, external_engine_data="engines")
    # out/model.pte (small) + out/engines.ptd (the engine)

    program = Runtime.get().load_program("out/model.pte",
                                         data_path="out/engines.ptd")

The name must be a str. It may not contain a directory, a drive (on Windows
"D:engines" is relative to drive D), a NUL, or the .ptd extension. With the
extension, ExecuTorch would write it to the same file as
another backend's data of the same base name, and one would silently replace
the other. One helper, normalize_external_engine_data, checks the name, like
the helpers for the other ExecuTorch options. save() calls it before it
exports anything, and export(), TensorRTPartitioner and preprocess call it
too, so a caller that lowers with the partitioner directly gets the same
checks. A wrong type raises TypeError. preprocess also refuses a spec value
that is not UTF-8 bytes. export() refuses a raw CompileSpec with the
external_engine_data key and asks for the keyword instead, as it already does
for use_cuda_graphs. The Python loader takes one data file, so a program that
also uses the CUDA backend should pass that backend's name, aoti_cuda_blob,
to share one file. The C++ Module can load several.

Loading such a program without its .ptd, or with one that lacks the engine,
now fails with InvalidExternalData and a message that asks for the .ptd file,
instead of InvalidProgram or NotFound. Any other failure to read the engine
keeps its own error. Without the keyword, nothing changes.

The README gets a short section on loading with the .ptd file. It says to
treat the .ptd as trusted input, like the .pte, since the key is a name and
nothing checks the engine against it at load, and that a program sharing
aoti_cuda_blob.ptd with the CUDA backend can fail first in that backend.

New C++ tests cover the load errors and a read error that is passed
through. New Python tests cover preprocess, the name checks in every entry
point, the keyword plumbing on each save() branch, the warning for other
formats, and an end-to-end run that saves one engine both ways and checks
that both programs give the same output bit for bit, and that loading
without the .ptd fails with InvalidExternalData.
@shoumikhin
shoumikhin force-pushed the executorch-external-engine-data branch from e1f15bc to 50e6a57 Compare October 21, 2026 05:10
@cehongwang
cehongwang merged commit 395492d into pytorch:main Oct 21, 2026
shoumikhin added a commit to shoumikhin/TensorRT that referenced this pull request Oct 22, 2026
…ghts

The load check from pytorch#4848 refuses a TensorRT plan serialized without its
weights, because such a plan runs without an error but computes with
placeholder weights. It treated any kSTRIPPED_WEIGHTS_SIZE of 0 or more as
"weights missing". But for a plan built with STRIP_PLAN, that number is the
weight bytes the plan still holds, and it equals the total when TensorRT had
nothing to strip. Those plans compute correctly and used to load, including
.pte files exported before the check. Now a plan is refused only when it holds
fewer weight bytes than its total.

The comment and README said -1 means the plan carries its weights. It only
means the plan is not marked as stripped: a stripped plan saved again without
a refit reads -1, so the check cannot catch it. Both now say that.

New tests: a stripped plan that kept all its weights loads and matches an
ordinary engine, and a refittable plan saved with EXCLUDE_WEIGHTS is refused.
shoumikhin added a commit to shoumikhin/TensorRT that referenced this pull request Oct 23, 2026
…ghts

The load check from pytorch#4848 refuses a TensorRT plan serialized without its
weights, because such a plan runs without an error but computes with
placeholder weights. It treated any kSTRIPPED_WEIGHTS_SIZE of 0 or more as
"weights missing". But for a plan built with STRIP_PLAN, that number is the
weight bytes the plan still holds, and it equals the total when TensorRT had
nothing to strip. Those plans compute correctly and used to load, including
.pte files exported before the check. Now a plan is refused only when it holds
fewer weight bytes than its total.

The comment and README said -1 means the plan carries its weights. It only
means the plan is not marked as stripped: a stripped plan saved again without
a refit reads -1, so the check cannot catch it. Both now say that.

New tests: a stripped plan that kept all its weights loads and matches an
ordinary engine, and a refittable plan saved with EXCLUDE_WEIGHTS is refused.
shoumikhin added a commit to shoumikhin/TensorRT that referenced this pull request Oct 23, 2026
…ghts

The load check from pytorch#4848 refuses a TensorRT plan serialized without its
weights, because such a plan runs without an error but computes with
placeholder weights. It treated any kSTRIPPED_WEIGHTS_SIZE of 0 or more as
"weights missing". But for a plan built with STRIP_PLAN, that number is the
weight bytes the plan still holds, and it equals the total when TensorRT had
nothing to strip. Those plans compute correctly and used to load, including
.pte files exported before the check. Now a plan is refused only when it holds
fewer weight bytes than its total.

The comment and README said -1 means the plan carries its weights. It only
means the plan is not marked as stripped. A plain re-save of a stripped plan
keeps the mark and is refused. But a stripped plan saved again with
EXCLUDE_WEIGHTS cleared and no refit reads -1, so this check cannot catch it,
and the old one could not either. Both now say that.

New tests: a stripped plan that kept all its weights loads and matches an
ordinary engine, and it fails without this fix. A refittable plan saved with
EXCLUDE_WEIGHTS is refused. The old check refused it too, so that test guards
the behavior rather than proving the fix.
shoumikhin added a commit to shoumikhin/TensorRT that referenced this pull request Oct 26, 2026
…ghts

The load check from pytorch#4848 refuses a TensorRT plan serialized without its
weights, because such a plan runs without an error but computes with
placeholder weights. It treated any kSTRIPPED_WEIGHTS_SIZE of 0 or more as
"weights missing". But for a plan built with STRIP_PLAN, that number is the
weight bytes the plan still holds, and it equals the total when TensorRT had
nothing to strip. Those plans compute correctly and used to load, including
.pte files exported before the check. Now a plan is refused only when it holds
fewer weight bytes than its total.

The comment and README said -1 means the plan carries its weights. It only
means the plan is not marked as stripped. A plain re-save of a stripped plan
keeps the mark and is refused. But a stripped plan saved again with
EXCLUDE_WEIGHTS cleared and no refit reads -1, so this check cannot catch it,
and the old one could not either. Both now say that.

New tests: a stripped plan that kept all its weights loads and matches an
ordinary engine, and it fails without this fix. A refittable plan saved with
EXCLUDE_WEIGHTS is refused. The old check refused it too, so that test guards
the behavior rather than proving the fix.
shoumikhin added a commit to shoumikhin/TensorRT that referenced this pull request Oct 26, 2026
…ghts

The load check from pytorch#4848 refuses a TensorRT plan serialized without its
weights, because such a plan runs without an error but computes with
placeholder weights. It treated any kSTRIPPED_WEIGHTS_SIZE of 0 or more as
"weights missing". But for a plan built with STRIP_PLAN, that number is the
weight bytes the plan still holds, and it equals the total when TensorRT had
nothing to strip. Those plans compute correctly and used to load, including
.pte files exported before the check. Now a plan is refused only when it holds
fewer weight bytes than its total.

The comment and README said -1 means the plan carries its weights. It only
means the plan is not marked as stripped. A plain re-save of a stripped plan
keeps the mark and is refused. But a stripped plan saved again with
EXCLUDE_WEIGHTS cleared and no refit reads -1, so this check cannot catch it,
and the old one could not either. Both now say that.

New tests: a stripped plan that kept all its weights loads and matches an
ordinary engine, and it fails without this fix. A refittable plan saved with
EXCLUDE_WEIGHTS is refused. The old check refused it too, so that test guards
the behavior rather than proving the fix.
lanluo-nvidia pushed a commit that referenced this pull request Oct 26, 2026
cehongwang added a commit that referenced this pull request Oct 30, 2026
main now stores each engine once, as named data (#4821), optionally in a .ptd
file (#4848). An engine still in its file reaches named data as ExecuTorch's
FileBackedData, so the save streams it from the file and never reads it into
memory. This replaces dropping the file's pages after copying them into the
delegate blob (17e7cb5), which named data made unnecessary.

engine_file_tensor maps the engine file and records it by the mapping's
address, because lowering hands the backend another tensor object over the
same storage; preprocess finds the file again with engine_file_of.
test_executorch_save_streams_engines_from_their_files replaces the page-drop
test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cla signed component: api [C++] Issues re: C++ API component: api [Python] Issues re: Python API component: tests Issues re: Tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants