torch-tensorrt-executorch-runtime 0.2.1__1-py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,413 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+ """Register the Torch-TensorRT delegate with the installed ExecuTorch runtime.
4
+
5
+ Importing this package is all it takes. ExecuTorch's own delegates register because they are
6
+ linked into its pybindings extension, so loading that extension pulls them in and their static
7
+ initializers run. A delegate shipped in a separate wheel cannot join that link, and ExecuTorch has
8
+ no discovery hook for out-of-tree backends, so this package performs the equivalent step itself at
9
+ import time.
10
+
11
+ There is deliberately no runtime API here. Once the backend is registered, everything else belongs
12
+ to ExecuTorch:
13
+
14
+ from pathlib import Path
15
+
16
+ import torch_tensorrt_executorch_runtime # noqa: F401
17
+ from executorch.runtime import Runtime
18
+
19
+ program = Runtime.get().load_program(Path("model.pte"))
20
+ outputs = program.load_method("forward").execute((tensor,))
21
+
22
+ Set ``TORCH_TENSORRT_SKIP_DELEGATE_REGISTRATION=1`` to import the module without loading the
23
+ delegate. That is for tooling that wants the metadata only; a normal consumer never needs it.
24
+
25
+ Registering is what this package is for, so failing to register is an import failure: importing it
26
+ without a usable ExecuTorch and delegate raises ``DelegateCompatibilityError`` and says what to
27
+ install, rather than handing back a module that registered nothing and letting the program fail
28
+ much later with a backend it cannot find. That is also why the recipes that ask this package only
29
+ for a path, in its readme and in its CMake package, set the variable above first.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import ctypes
35
+ import importlib.metadata
36
+ import os
37
+ import sys
38
+ import threading
39
+ import warnings
40
+ from types import ModuleType
41
+ from typing import Any, cast
42
+
43
+ BACKEND_NAME = "TensorRTBackend"
44
+ # The same name ExecuTorch gives its own delegates, and the exact filename the wheel ships.
45
+ _DELEGATE_LIBRARY = "libexecutorch_backend_tensorrt.so"
46
+ if sys.platform == "win32":
47
+ _DELEGATE_LIBRARY = "executorch_backend_tensorrt.dll"
48
+
49
+ # Keep AddDllDirectory handles alive for subsequent CUDA model loads too.
50
+ _dll_directories: list[Any] = []
51
+
52
+ _delegate: ctypes.CDLL | None = None
53
+ # Registration happens in the delegate's static initializer, so it takes effect inside dlopen,
54
+ # before ctypes.CDLL returns and before _delegate is assigned. Every check below therefore has to
55
+ # sit inside one critical section: a second thread that squeezed between the load and the
56
+ # assignment would see the backend registered with _delegate still None, which is exactly what a
57
+ # foreign delegate owning the name looks like.
58
+ _registration_lock = threading.Lock()
59
+
60
+
61
+ class DelegateCompatibilityError(ImportError):
62
+ """The delegate could not be loaded against the installed ExecuTorch runtime."""
63
+
64
+
65
+ _EXTENSION_CUDA_LIBRARY = "libexecutorch_extension_cuda.so"
66
+ if sys.platform == "win32":
67
+ _EXTENSION_CUDA_LIBRARY = "executorch_extension_cuda.dll"
68
+
69
+
70
+ def _configure_windows_dll_search() -> None:
71
+ if sys.platform != "win32" or _dll_directories:
72
+ return
73
+ paths = [os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")]
74
+ for distribution, relative in (
75
+ ("executorch", "executorch/lib"),
76
+ ("executorch", "executorch/backends/cuda"),
77
+ ("tensorrt-cu13-libs", "tensorrt_libs"),
78
+ ("torch", "torch/lib"),
79
+ ):
80
+ try:
81
+ paths.append(
82
+ str(importlib.metadata.distribution(distribution).locate_file(relative))
83
+ )
84
+ except importlib.metadata.PackageNotFoundError:
85
+ continue
86
+ # CUDA runtime pip wheels are Linux-only; Windows uses the toolkit DLLs.
87
+ for variable in ("CUDA_PATH", "CUDA_HOME"):
88
+ if root := os.environ.get(variable):
89
+ paths.append(os.path.join(root, "bin"))
90
+ for path in dict.fromkeys(os.path.abspath(path) for path in paths):
91
+ if os.path.isdir(path):
92
+ _dll_directories.append(os.add_dll_directory(path))
93
+
94
+
95
+ def _extension_cuda_present() -> bool:
96
+ """Whether the installed ExecuTorch actually ships the CUDA extension.
97
+
98
+ Resolved from the imported package rather than a hardcoded path, so it follows the
99
+ distribution the loader would have used. ``__file__`` as well as ``__path__``, because a
100
+ namespace-style or synthesised module may carry only one of them, and treating "no location
101
+ at all" as "the file is missing" would send a user with a working CUDA wheel off to
102
+ reinstall it.
103
+ """
104
+ try:
105
+ import executorch
106
+ except ImportError:
107
+ return False
108
+ roots = list(getattr(executorch, "__path__", None) or ())
109
+ location = getattr(executorch, "__file__", None)
110
+ if location:
111
+ roots.append(os.path.dirname(os.path.abspath(location)))
112
+ return any(
113
+ os.path.isfile(os.path.join(root, "lib", _EXTENSION_CUDA_LIBRARY))
114
+ for root in roots
115
+ )
116
+
117
+
118
+ def _delegate_path() -> str:
119
+ # Resolved next to this file rather than through the import system, so it does not depend on the
120
+ # package being on the path anywhere else. It still runs during this package's own import, and
121
+ # cannot run before it. A fixed filename now: the delegate is shipped as
122
+ # package data under its real name, not renamed by setuptools.
123
+ #
124
+ # ``lib/`` rather than the package root, matching where ExecuTorch keeps its own backends
125
+ # (``executorch/lib/libexecutorch_backend_cuda.so`` and friends). A C++ consumer finds this
126
+ # library through the CMake package in ``lib/cmake``, which searches the same directory, so
127
+ # the two consumers agree on one location.
128
+ directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")
129
+ path = os.path.join(directory, _DELEGATE_LIBRARY)
130
+ if not os.path.isfile(path):
131
+ raise DelegateCompatibilityError(
132
+ f"The Torch-TensorRT ExecuTorch delegate library is missing from {directory}. "
133
+ "This package must be installed from a wheel; a source checkout contains no "
134
+ "built delegate."
135
+ )
136
+ return path
137
+
138
+
139
+ def register() -> None:
140
+ """Load the delegate so ExecuTorch can execute TensorRT-delegated programs.
141
+
142
+ Called once when this package is imported, so a user never has to. It stays public and named
143
+ because the import side effect is the whole point of the package and a reader needs somewhere to
144
+ look, and because a caller that imported the package defensively can re-assert registration
145
+ without reaching into a private name.
146
+
147
+ Registration happens in the delegate's own static initializer, which calls into the backend
148
+ registry that lives in the ExecuTorch runtime. Importing ExecuTorch first is what puts that
149
+ runtime in the process; the delegate then binds to the same copy through its DT_NEEDED rather
150
+ than bringing one of its own.
151
+
152
+ Idempotent, and safe to call after ``executorch.runtime`` has already been imported. That used
153
+ to be an error, because the delegate arrived as a substitute for ExecuTorch's own Python
154
+ extension and had to get in first. It no longer substitutes anything.
155
+
156
+ Thread safe: the whole first registration is serialized, because it lands during ``dlopen``
157
+ while ``_delegate`` is assigned after it, and a caller observing that gap could not tell this
158
+ package's own load from a foreign delegate holding the name.
159
+ """
160
+ if _delegate is not None:
161
+ return
162
+
163
+ with _registration_lock:
164
+ # Re-checked under the lock so queued callers do not repeat the same registration work.
165
+ if _delegate is not None:
166
+ return
167
+ _register_locked()
168
+
169
+
170
+ def _register_locked() -> None:
171
+ global _delegate
172
+
173
+ _configure_windows_dll_search()
174
+ try:
175
+ import executorch.extension.pybindings.portable_lib # noqa: F401
176
+ except ImportError as error:
177
+ # "Not installed" and "installed but unloadable" need different repairs, and the second
178
+ # is what an ABI mismatch looks like: the module is found, its extension fails to load.
179
+ # Answering both with "install executorch" sends that user to reinstall what they have.
180
+ # ModuleNotFoundError covers a genuinely absent package; a bare ImportError whose message
181
+ # names no shared object is the same thing seen through a blocked sys.modules entry. An
182
+ # ABI failure, by contrast, always names the library that would not load.
183
+ # ModuleNotFoundError naming executorch itself. Testing the type alone was wrong: if an
184
+ # installed ExecuTorch fails to import because one of its own transitive dependencies is
185
+ # missing, the exception is also a ModuleNotFoundError, and its .name is that dependency.
186
+ # That user was told to install ExecuTorch, which they already have.
187
+ # Exact match, not the top-level segment: CPython sets .name to the full dotted path when a
188
+ # submodule such as executorch.extension.pybindings.portable_lib is the thing that is
189
+ # absent or blocked, and to the bare "executorch" only when the root package itself is
190
+ # missing. Splitting on "." and comparing the first segment reported a blocked submodule as
191
+ # ExecuTorch being uninstalled, which is the ABI case this branch exists to separate out.
192
+ absent = (
193
+ isinstance(error, ModuleNotFoundError)
194
+ and (error.name or "") == "executorch"
195
+ )
196
+ if absent:
197
+ raise DelegateCompatibilityError(
198
+ "ExecuTorch must be installed to load the Torch-TensorRT delegate. Install "
199
+ "executorch from the same release matrix as this package. The import failed "
200
+ f"with: {error}. Importing this package registers the delegate, which is why it "
201
+ "raises here rather than later. Set "
202
+ "TORCH_TENSORRT_SKIP_DELEGATE_REGISTRATION=1 to import it without registering."
203
+ ) from error
204
+ # A library the loader could not FIND is a different problem from one it could not USE, and
205
+ # only the second is an ABI mismatch. Blaming the ABI for the first sends the reader to
206
+ # rebuild a matched stack when nothing is mismatched.
207
+ text = str(error)
208
+ missing_file = "cannot open shared object file" in text
209
+ if missing_file:
210
+ hint = (
211
+ "so the loader could not find it, not that it is incompatible. Check that the "
212
+ "ExecuTorch wheel is installed completely."
213
+ )
214
+ # An empty entry in the search path means the working directory, and it makes every
215
+ # origin-relative entry in this package's own search path resolve from there instead,
216
+ # so a correct installation fails to load from some directories and not others. A
217
+ # trailing separator is the usual way one appears.
218
+ search_path = os.environ.get("LD_LIBRARY_PATH")
219
+ if search_path is not None and "" in search_path.split(os.pathsep):
220
+ hint = (
221
+ "so the loader could not find it. LD_LIBRARY_PATH has an empty entry, often "
222
+ "from a trailing separator, which the loader reads as the working directory "
223
+ "and which stops this package's own origin-relative search path resolving. "
224
+ f"Remove it and retry. Current value: {search_path!r}"
225
+ )
226
+ raise DelegateCompatibilityError(
227
+ f"ExecuTorch is installed but a library it needs was not found, {hint} "
228
+ f"The import failed with: {error}"
229
+ ) from error
230
+ raise DelegateCompatibilityError(
231
+ "ExecuTorch is installed but its Python bindings could not be loaded, which "
232
+ "usually means it was built against a different C++ or CUDA runtime than this "
233
+ f"delegate. The import failed with: {error}"
234
+ ) from error
235
+
236
+ path = _delegate_path()
237
+ # A preloaded library may have lost registration to another copy. Check ownership below.
238
+ if BACKEND_NAME in _registered_backend_names():
239
+ loaded = _delegate_already_loaded(path)
240
+ if loaded is None:
241
+ raise DelegateCompatibilityError(
242
+ f"{BACKEND_NAME} is already registered before loading {path}, and that library is "
243
+ "not the one in this process, so another copy of the delegate is present. "
244
+ "ExecuTorch keeps the first registration, so the copy this package ships would "
245
+ "not be the one used. Import this package once, and do not load a second "
246
+ "Torch-TensorRT delegate alongside it."
247
+ )
248
+ else:
249
+ try:
250
+ # Eagerly, so a missing dependency surfaces here as an OSError this code can explain,
251
+ # rather than later as a failed lookup with nothing to say about the cause.
252
+ loaded = (
253
+ ctypes.CDLL(path)
254
+ if sys.platform == "win32"
255
+ else ctypes.CDLL(path, mode=os.RTLD_NOW | os.RTLD_LOCAL)
256
+ )
257
+ except OSError as error:
258
+ # A present CUDA extension can also fail to load because of an ABI mismatch.
259
+ if (
260
+ "executorch_extension_cuda" in str(error) or sys.platform == "win32"
261
+ ) and not _extension_cuda_present():
262
+ raise DelegateCompatibilityError(
263
+ f"Could not load the Torch-TensorRT ExecuTorch delegate from {path}. This "
264
+ f"requires a CUDA build of executorch, which ships {_EXTENSION_CUDA_LIBRARY}; "
265
+ "a CPU build satisfies the version pin but "
266
+ "not this dependency. Install torch, executorch, torch-tensorrt, and this "
267
+ "package from the same release matrix."
268
+ ) from error
269
+ raise DelegateCompatibilityError(
270
+ f"Could not load the Torch-TensorRT ExecuTorch delegate from {path}: {error}. "
271
+ "The delegate links ExecuTorch's prebuilt runtime, TensorRT, and the CUDA runtime "
272
+ "from their own wheels, so install torch, executorch, torch-tensorrt, and this "
273
+ "package from the same release matrix."
274
+ ) from error
275
+
276
+ if BACKEND_NAME not in _registered_backend_names():
277
+ raise DelegateCompatibilityError(
278
+ f"Loading {path} did not register {BACKEND_NAME} with the ExecuTorch runtime, so "
279
+ "a delegated program would fail to load. The delegate and the installed "
280
+ "ExecuTorch were probably built against different runtimes."
281
+ )
282
+ try:
283
+ query_ownership = loaded.torch_tensorrt_owns_executorch_registration
284
+ except AttributeError as error:
285
+ raise DelegateCompatibilityError(
286
+ f"The delegate at {path} has no registration ownership query. "
287
+ "Reinstall this package so its Python module and native library match."
288
+ ) from error
289
+ query_ownership.argtypes = []
290
+ query_ownership.restype = ctypes.c_bool
291
+ if not query_ownership():
292
+ raise DelegateCompatibilityError(
293
+ f"The delegate at {path} does not own the {BACKEND_NAME} registration. "
294
+ "ExecuTorch keeps the first registration, so another library would execute "
295
+ "the delegated program. Do not load a second Torch-TensorRT delegate alongside it."
296
+ )
297
+ _delegate = loaded
298
+
299
+
300
+ def _delegate_already_loaded(path: str) -> ctypes.CDLL | None:
301
+ """The handle for ``path`` if that exact library is already in this process, else ``None``.
302
+
303
+ ``dlopen`` on an already-loaded library returns the existing handle and bumps its reference
304
+ count rather than mapping a second copy, so this cannot introduce the duplicate it is checking
305
+ for. ``RTLD_NOLOAD`` is what makes the question safe to ask: it refuses to load anything, so a
306
+ library that is not present yields ``None`` instead of being pulled in as a side effect of the
307
+ test. It is absent on some platforms; this delegate is Linux-only, where CPython always defines
308
+ it, and a build without it answers ``None`` here, the same answer as a library that is not
309
+ loaded.
310
+ """
311
+ if sys.platform == "win32":
312
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
313
+ kernel.GetModuleHandleW.argtypes = [ctypes.c_wchar_p]
314
+ kernel.GetModuleHandleW.restype = ctypes.c_void_p
315
+ kernel.GetModuleFileNameW.argtypes = [
316
+ ctypes.c_void_p,
317
+ ctypes.c_wchar_p,
318
+ ctypes.c_uint,
319
+ ]
320
+ kernel.GetModuleFileNameW.restype = ctypes.c_uint
321
+ handle = kernel.GetModuleHandleW(path)
322
+ if not handle:
323
+ return None
324
+ filename = ctypes.create_unicode_buffer(32768)
325
+ size = kernel.GetModuleFileNameW(handle, filename, len(filename))
326
+ if not size or size >= len(filename):
327
+ return None
328
+ if os.path.normcase(os.path.realpath(filename.value)) != os.path.normcase(
329
+ os.path.realpath(path)
330
+ ):
331
+ return None
332
+ return ctypes.CDLL(path, handle=handle)
333
+ noload = getattr(os, "RTLD_NOLOAD", None)
334
+ if noload is None:
335
+ return None
336
+ try:
337
+ return ctypes.CDLL(path, mode=noload | os.RTLD_LOCAL)
338
+ except OSError:
339
+ return None
340
+
341
+
342
+ def _registered_backend_names() -> list[str]:
343
+ # A private ExecuTorch name, and registration runs at import, so an ExecuTorch that does not
344
+ # export it would turn a plain import of this package into a bare ImportError traceback. Say
345
+ # what is wrong and what to do instead.
346
+ try:
347
+ from executorch.extension.pybindings.portable_lib import (
348
+ _get_registered_backend_names,
349
+ )
350
+ except ImportError as error:
351
+ raise DelegateCompatibilityError(
352
+ "The installed ExecuTorch does not expose its registered backend names, so this "
353
+ "delegate cannot confirm it owns its registration. Install the ExecuTorch build this "
354
+ f"package pins. Underlying error: {error}"
355
+ ) from error
356
+
357
+ return cast(list[str], _get_registered_backend_names())
358
+
359
+
360
+ def activate() -> ModuleType:
361
+ """Deprecated: register the backend and return ExecuTorch's own portable runtime.
362
+
363
+ The companion published before this change swapped in its own bundled ``_portable_lib`` and
364
+ returned it. This package no longer bundles one, so it registers the backend and hands back
365
+ ExecuTorch's module, which is the one that now carries the delegate. A caller that only wanted
366
+ registration is unaffected; one that used the return value gets the module it was reaching for.
367
+ """
368
+ warnings.warn(
369
+ "activate() is deprecated; the backend registers on import. Call register() if you "
370
+ "need to register explicitly.",
371
+ DeprecationWarning,
372
+ stacklevel=2,
373
+ )
374
+ register()
375
+ from executorch.extension.pybindings import portable_lib
376
+
377
+ return cast(ModuleType, portable_lib)
378
+
379
+
380
+ def get_runtime() -> Any:
381
+ """Deprecated: ExecuTorch's runtime, which now owns execution for this backend.
382
+
383
+ The companion used to return a runtime of its own. ExecuTorch's ``Runtime.get()`` is that
384
+ object now, so this forwards to it rather than failing, and a caller that asked for a runtime
385
+ still gets one that can see the registered backend.
386
+ """
387
+ warnings.warn(
388
+ "get_runtime() is deprecated; use executorch.runtime.Runtime.get().",
389
+ DeprecationWarning,
390
+ stacklevel=2,
391
+ )
392
+ register()
393
+ from executorch.runtime import Runtime
394
+
395
+ return Runtime.get()
396
+
397
+
398
+ # Tooling can opt out; normal imports must fail if this delegate cannot own registration.
399
+ if os.getenv("TORCH_TENSORRT_SKIP_DELEGATE_REGISTRATION", "0").lower() not in (
400
+ "1",
401
+ "true",
402
+ "yes",
403
+ "on",
404
+ ):
405
+ register()
406
+
407
+ __all__ = [
408
+ "BACKEND_NAME",
409
+ "DelegateCompatibilityError",
410
+ "activate",
411
+ "get_runtime",
412
+ "register",
413
+ ]
@@ -0,0 +1,37 @@
1
+ # Generated by setup.py. The version is only known when the wheel is built.
2
+ set(PACKAGE_VERSION "0.2.1")
3
+ set(EXECUTORCH_BACKEND_TENSORRT_FULL_VERSION "0.2.1+cu132")
4
+
5
+ if(PACKAGE_FIND_VERSION_MAJOR STREQUAL "0")
6
+ if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
7
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
8
+ else()
9
+ set(PACKAGE_VERSION_COMPATIBLE TRUE)
10
+ endif()
11
+ else()
12
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
13
+ endif()
14
+
15
+ if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
16
+ set(PACKAGE_VERSION_EXACT TRUE)
17
+ endif()
18
+
19
+ # A version RANGE, find_package(pkg 2.14...<2.15). Without this the upper bound is
20
+ # silently ignored and the range behaves like its lower bound alone.
21
+ if(PACKAGE_FIND_VERSION_RANGE)
22
+ if(PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE"
23
+ AND NOT PACKAGE_FIND_VERSION_MAX_MAJOR STREQUAL "0")
24
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
25
+ elseif(PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE"
26
+ AND PACKAGE_FIND_VERSION_MAX VERSION_GREATER "1")
27
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
28
+ elseif(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION_MIN)
29
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
30
+ elseif(PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE"
31
+ AND PACKAGE_VERSION VERSION_GREATER PACKAGE_FIND_VERSION_MAX)
32
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
33
+ elseif(PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE"
34
+ AND NOT PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION_MAX)
35
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
36
+ endif()
37
+ endif()
@@ -0,0 +1,184 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+ # CMake package for the Torch-TensorRT ExecuTorch delegate, as installed by the
5
+ # torch-tensorrt-executorch-runtime wheel.
6
+ #
7
+ # ExecuTorch ships its own backends as prebuilt shared libraries plus a CMake
8
+ # package, so a C++ app links executorch::backend_cuda and gets the backend
9
+ # registered. This file gives the TensorRT delegate the same treatment, so a C++
10
+ # app can link it out of the installed wheel instead of building this repo from
11
+ # source:
12
+ #
13
+ # find_package(executorch REQUIRED COMPONENTS backend_cuda kernels_optimized)
14
+ # find_package(executorch_backend_tensorrt REQUIRED)
15
+ # target_link_libraries(my_app PRIVATE
16
+ # executorch::runtime
17
+ # executorch::backend_cuda
18
+ # executorch::backend_tensorrt
19
+ # executorch::kernels_optimized
20
+ # )
21
+ #
22
+ # kernels_optimized supplies the et_copy host/device copy operators.
23
+ # There is nothing to include. The wheel ships no header: the delegate
24
+ # registers itself with ExecuTorch's backend registry from a static initializer
25
+ # inside the shared library, and everything a caller does afterwards is
26
+ # ExecuTorch's own Runtime API. Choosing an optimization profile needs
27
+ # OptimizationProfileGuard, which only the source tree and the release tarball
28
+ # carry; linked from this wheel, every engine runs its profile 0.
29
+ #
30
+ # Point CMake at it with either of the two lines below. Which one matters: importing this package loads the delegate,
31
+ # which raises where ExecuTorch is not installed yet, and asking for a path does not need it loaded.
32
+ # -Dexecutorch_backend_tensorrt_DIR=$(TORCH_TENSORRT_SKIP_DELEGATE_REGISTRATION=1 python -c "import torch_tensorrt_executorch_runtime as m, pathlib; print(pathlib.Path(m.__file__).parent / 'lib/cmake/executorch_backend_tensorrt')")
33
+ # -DCMAKE_PREFIX_PATH=$(TORCH_TENSORRT_SKIP_DELEGATE_REGISTRATION=1 python -c "import torch_tensorrt_executorch_runtime as m, pathlib; print(pathlib.Path(m.__file__).parent)")
34
+
35
+ # No cmake_minimum_required here. A package config that calls it raises the consumer's own recorded
36
+ # minimum, and nothing in this file needs anything newer than 3.19: the token that misbehaves on older
37
+ # CMake is $ORIGIN, which appears in ExecuTorch's link options and not in ours, since ours are an
38
+ # absolute path.
39
+ #
40
+ # What ExecuTorch does below 3.28 depends on how it is asked. Found without components it succeeds and
41
+ # offers plain path variables instead of imported targets. Asked for a component it fails outright, so
42
+ # the recipe this package's own readme gives cannot be used below 3.28. A consumer on 3.19 to 3.27 has
43
+ # to find ExecuTorch without components and link its variables alongside this package's target, which
44
+ # this package's readme spells out.
45
+ #
46
+ # 3.19, checked rather than declared, so the consumer's own minimum is left alone.
47
+ if(CMAKE_VERSION VERSION_LESS 3.19)
48
+ message(FATAL_ERROR
49
+ "executorch_backend_tensorrt needs CMake 3.19 or newer, the same floor ExecuTorch's own package "
50
+ "declares. This CMake is ${CMAKE_VERSION}.")
51
+ endif()
52
+
53
+ include(FindPackageHandleStandardArgs)
54
+
55
+ # The package root is a fixed distance from this file, because the wheel installs this file to
56
+ # lib/cmake/executorch_backend_tensorrt and nowhere else. It used to be found by walking up until a delegate
57
+ # turned up under lib/, and that walk reached the directory above the package: with this package's own
58
+ # lib/ empty, it accepted a same-named library belonging to something else and reported success. Only
59
+ # this package's own copy is acceptable, so look in exactly one place and let the check below report a
60
+ # missing one.
61
+ get_filename_component(_executorch_backend_tensorrt_root "${CMAKE_CURRENT_LIST_DIR}/../../.." ABSOLUTE)
62
+ unset(EXECUTORCH_BACKEND_TENSORRT_BACKEND_LIBRARY)
63
+ if(WIN32)
64
+ set(_executorch_backend_tensorrt_filename "executorch_backend_tensorrt.dll")
65
+ else()
66
+ set(_executorch_backend_tensorrt_filename "libexecutorch_backend_tensorrt.so")
67
+ endif()
68
+ if(EXISTS "${_executorch_backend_tensorrt_root}/lib/${_executorch_backend_tensorrt_filename}")
69
+ set(EXECUTORCH_BACKEND_TENSORRT_BACKEND_LIBRARY
70
+ "${_executorch_backend_tensorrt_root}/lib/${_executorch_backend_tensorrt_filename}")
71
+ endif()
72
+ set(_executorch_backend_tensorrt_required_vars EXECUTORCH_BACKEND_TENSORRT_BACKEND_LIBRARY)
73
+ if(WIN32)
74
+ unset(EXECUTORCH_BACKEND_TENSORRT_IMPORT_LIBRARY)
75
+ if(EXISTS "${_executorch_backend_tensorrt_root}/lib/executorch_backend_tensorrt.lib")
76
+ set(EXECUTORCH_BACKEND_TENSORRT_IMPORT_LIBRARY
77
+ "${_executorch_backend_tensorrt_root}/lib/executorch_backend_tensorrt.lib")
78
+ endif()
79
+ list(APPEND _executorch_backend_tensorrt_required_vars EXECUTORCH_BACKEND_TENSORRT_IMPORT_LIBRARY)
80
+ endif()
81
+
82
+ find_package_handle_standard_args(
83
+ executorch_backend_tensorrt
84
+ REQUIRED_VARS ${_executorch_backend_tensorrt_required_vars}
85
+ )
86
+
87
+ if(NOT executorch_backend_tensorrt_FOUND)
88
+ return()
89
+ endif()
90
+
91
+ set(EXECUTORCH_BACKEND_TENSORRT_LIBRARIES executorch::backend_tensorrt)
92
+
93
+ if(TARGET executorch::backend_tensorrt)
94
+ # Reusing is right when another subproject already ran this same config, and wrong when the name
95
+ # belongs to something else. The in-tree build defines it as an interface library over a private
96
+ # static copy, so a project that pulls that in and then calls find_package would silently link
97
+ # the private copy and never touch the shared library in the wheel. Only an imported shared
98
+ # library can be the one this config created.
99
+ get_target_property(_executorch_backend_tensorrt_existing_type executorch::backend_tensorrt TYPE)
100
+ if(NOT _executorch_backend_tensorrt_existing_type STREQUAL "SHARED_LIBRARY")
101
+ message(FATAL_ERROR
102
+ "executorch::backend_tensorrt already exists as a ${_executorch_backend_tensorrt_existing_type}, "
103
+ "not as the imported shared library this package provides. The in-tree delegate target and "
104
+ "the installed one cannot both be used in a single configure: drop one of them.")
105
+ endif()
106
+ # Type alone does not identify it. A shared imported target of the same name pointing at another
107
+ # file would pass, and the consumer would link that file while believing it linked this one.
108
+ get_target_property(_executorch_backend_tensorrt_existing_location
109
+ executorch::backend_tensorrt IMPORTED_LOCATION)
110
+ if(NOT _executorch_backend_tensorrt_existing_location STREQUAL "${EXECUTORCH_BACKEND_TENSORRT_BACKEND_LIBRARY}")
111
+ message(FATAL_ERROR
112
+ "executorch::backend_tensorrt already points at "
113
+ "${_executorch_backend_tensorrt_existing_location}, not at the "
114
+ "${EXECUTORCH_BACKEND_TENSORRT_BACKEND_LIBRARY} this package found. Two different delegates cannot "
115
+ "both be used in a single configure: drop one of them.")
116
+ endif()
117
+ message(STATUS "executorch_backend_tensorrt: executorch::backend_tensorrt is already defined, reusing it")
118
+ return()
119
+ endif()
120
+
121
+ # GLOBAL, so the one target this package exists to publish is visible outside the directory that
122
+ # called find_package. Without it a consumer who finds the package at the top level and links it from
123
+ # a subdirectory gets a message about a target that plainly exists, which is the ordinary layout for
124
+ # a project of more than one directory.
125
+ add_library(executorch::backend_tensorrt SHARED IMPORTED GLOBAL)
126
+ # Aliased to the name this target had before. An alias to an imported target needs it to be
127
+ # global, which it is above, and this keeps a consumer that has not been updated working.
128
+ add_library(torchtrt::executorch_backend ALIAS executorch::backend_tensorrt)
129
+ # The plain name too. Both existed before the rename and a consumer could link either.
130
+ add_library(torchtrt_executorch_backend ALIAS executorch::backend_tensorrt)
131
+ set_target_properties(
132
+ executorch::backend_tensorrt
133
+ PROPERTIES
134
+ IMPORTED_LOCATION "${EXECUTORCH_BACKEND_TENSORRT_BACKEND_LIBRARY}"
135
+ INTERFACE_COMPILE_FEATURES cxx_std_17
136
+ )
137
+ if(WIN32)
138
+ set_target_properties(executorch::backend_tensorrt PROPERTIES
139
+ IMPORTED_IMPLIB "${EXECUTORCH_BACKEND_TENSORRT_IMPORT_LIBRARY}"
140
+ INTERFACE_COMPILE_FEATURES cxx_std_20)
141
+ set_property(TARGET executorch::backend_tensorrt APPEND PROPERTY
142
+ INTERFACE_LINK_OPTIONS "LINKER:/INCLUDE:torch_tensorrt_owns_executorch_registration")
143
+ endif()
144
+
145
+ # Retain the static registration even when the consumer references no delegate symbol.
146
+ # Scope --no-as-needed to this library so unrelated dependencies can still be dropped.
147
+ if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
148
+ set_property(
149
+ TARGET executorch::backend_tensorrt
150
+ APPEND
151
+ PROPERTY
152
+ INTERFACE_LINK_OPTIONS
153
+ "LINKER:--push-state,--no-as-needed,${EXECUTORCH_BACKEND_TENSORRT_BACKEND_LIBRARY},--pop-state"
154
+ )
155
+ # So the loader finds the library in the installed wheel at run time. The delegate is not a
156
+ # dependency the consumer copies around: it lives in site-packages next to the executorch wheel
157
+ # whose runtime it links, and both have to be found from the same place.
158
+ # This is the path on the machine that configured, and it lands in every consumer binary, so a
159
+ # binary built here does not run anywhere else. That is the right default for building against an
160
+ # installed wheel, which is what this package is for, and wrong for anything redistributable.
161
+ # Not option(): inside a package config that creates a cache entry in the consumer's project
162
+ # and, depending on the policy in force, overrides a plain variable the consumer already
163
+ # set, so an opt-out they set could be ignored. Honour what the consumer set.
164
+ if(NOT DEFINED EXECUTORCH_BACKEND_TENSORRT_EMBED_RUNPATH)
165
+ set(EXECUTORCH_BACKEND_TENSORRT_EMBED_RUNPATH ON)
166
+ endif()
167
+ if(EXECUTORCH_BACKEND_TENSORRT_EMBED_RUNPATH)
168
+ set_property(
169
+ TARGET executorch::backend_tensorrt
170
+ APPEND
171
+ PROPERTY INTERFACE_LINK_OPTIONS "LINKER:--enable-new-dtags,-rpath,${_executorch_backend_tensorrt_root}/lib"
172
+ )
173
+ else()
174
+ # This removes the run path this package adds, not the one CMake adds by itself:
175
+ # linking an imported library records its directory as DT_RUNPATH regardless, which is
176
+ # still this machine's absolute path. Only CMAKE_SKIP_BUILD_RPATH in the consumer's own
177
+ # project removes that, and a package config has no business setting it there.
178
+ message(STATUS
179
+ "executorch_backend_tensorrt: not adding a run path. CMake still records "
180
+ "${_executorch_backend_tensorrt_root}/lib as a build run path when linking an imported "
181
+ "library, so a redistributable binary also needs CMAKE_SKIP_BUILD_RPATH, and then has "
182
+ "to locate the delegate itself at run time.")
183
+ endif()
184
+ endif()
@@ -0,0 +1,100 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+ """Deprecated: loading moved to ExecuTorch's own Module API.
5
+
6
+ The published Torch-TensorRT wheel imports ``load`` from this submodule by name, so removing it
7
+ would turn ``torch_tensorrt.load(..., format="executorch")`` into a ModuleNotFoundError for anyone
8
+ who upgrades this package on its own. It stays until that call is gone from a released main wheel.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import sys
14
+ import warnings
15
+ from pathlib import Path
16
+ from typing import Any, Union
17
+
18
+ # Program resolves through __getattr__ below rather than being bound here, so the linter cannot see
19
+ # it and is told so. It stays exported because the published package exported it.
20
+ __all__ = ["load", "Program"] # noqa: F822
21
+
22
+
23
+ def _cannot_forward(error: ImportError) -> ImportError:
24
+ """Name the case the reader is actually in.
25
+
26
+ This package does not declare Torch-TensorRT, so absent is the ordinary state and too old is the
27
+ rare one. Reporting the rare one told a reader with no Torch-TensorRT at all to go and upgrade it,
28
+ and offered them a call in the module they do not have.
29
+
30
+ Read from sys.modules: the failed import above already put the package there if it imported at
31
+ all, so absent here means absent.
32
+ """
33
+ if "torch_tensorrt" not in sys.modules:
34
+ return ImportError(
35
+ "This deprecated door forwards into torch_tensorrt, which is not installed. This "
36
+ "package does not require it. Either install torch-tensorrt, or drop the deprecated "
37
+ "call: import this package to register the TensorRT delegate, then load with "
38
+ "executorch.runtime.Runtime.get().load_program(path). "
39
+ f"Underlying error: {error}"
40
+ )
41
+ # No advice to call torch_tensorrt.load(format="executorch") here: on the wheel that reaches
42
+ # this branch, that call is what forwards into this function, so it returns the reader to the
43
+ # error they already have.
44
+ return ImportError(
45
+ "This deprecated door forwards into torch_tensorrt, and the installed Torch-TensorRT does "
46
+ "not carry the receiving module. Upgrade Torch-TensorRT to a build that has it, or drop "
47
+ "the deprecated call: import this package to register the TensorRT delegate, then load "
48
+ "with executorch.runtime.Runtime.get().load_program(path). "
49
+ f"Underlying error: {error}"
50
+ )
51
+
52
+
53
+ def __getattr__(name: str) -> Any:
54
+ """Resolve Program from the main wheel on first use.
55
+
56
+ The published package exported this name alongside load, so code that imported it by name has to
57
+ keep working. Resolving it lazily rather than at module import keeps this module importable
58
+ against a main wheel that does not have it, which is the same reason load defers its own import.
59
+ """
60
+ if name == "Program":
61
+ # Guarded for the same reason load is, and with the same message. Left bare, this door
62
+ # produced the very error the other door's guard exists to avoid, so an install that skipped
63
+ # dependency resolution got a bare module-not-found naming a module the caller never asked
64
+ # for, depending only on which name they reached for first.
65
+ try:
66
+ from torch_tensorrt._executorch_compat import Program
67
+ except ImportError as error:
68
+ raise _cannot_forward(error) from error
69
+
70
+ return Program
71
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
72
+
73
+
74
+ def load(path: Union[str, Path]) -> Any:
75
+ """Deprecated: register the delegate and load through ExecuTorch.
76
+
77
+ Registration is what this package exists for, and ExecuTorch owns execution, so this does the
78
+ first and forwards the second rather than carrying a loader of its own.
79
+
80
+ The parameter matches the shim that forwards to it; it is spelled the same way as its only
81
+ caller for readability.
82
+ """
83
+ warnings.warn(
84
+ "torch_tensorrt_executorch_runtime.runtime.load() is deprecated; import this package to "
85
+ "register the TensorRT delegate, then load with "
86
+ "executorch.runtime.Runtime.get().load_program(path) and run with "
87
+ "program.load_method('forward').execute(inputs).",
88
+ DeprecationWarning,
89
+ stacklevel=2,
90
+ )
91
+ # Forward to the main wheel's loader rather than ExecuTorch's. The API this replaces returned a
92
+ # Program carrying run() and forward() and raised FileNotFoundError for a missing path, and
93
+ # ExecuTorch's own loader returns neither, so a caller of the published API would break on the
94
+ # return value instead of on the import.
95
+ try:
96
+ from torch_tensorrt._executorch_compat import load as _load
97
+ except ImportError as error:
98
+ raise _cannot_forward(error) from error
99
+
100
+ return _load(path)
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.4
2
+ Name: torch-tensorrt-executorch-runtime
3
+ Version: 0.2.1
4
+ Summary: Torch-TensorRT delegate for the ExecuTorch Python runtime
5
+ Requires-Python: >=3.11,<3.15
6
+ Requires-Dist: torch
7
+ Requires-Dist: executorch==1.6.0
8
+ Requires-Dist: tensorrt-cu13==11.4.0.106
9
+ Dynamic: requires-dist
10
+ Dynamic: requires-python
11
+ Dynamic: summary
@@ -0,0 +1,10 @@
1
+ torch_tensorrt_executorch_runtime/__init__.py,sha256=AFZle3bokiQQ359F0l_lG5Oo5y_oiQkIPMnQx9bAxL4,20320
2
+ torch_tensorrt_executorch_runtime/runtime.py,sha256=sSSOxF3UTqQRy1vFhU9WNoSK6Re5ZSOBt_9G_87TVHU,4960
3
+ torch_tensorrt_executorch_runtime/lib/executorch_backend_tensorrt.dll,sha256=acD8X6jZYNItMd9YZfauzik1iIZqayfJ6HMfgRdJAog,169472
4
+ torch_tensorrt_executorch_runtime/lib/executorch_backend_tensorrt.lib,sha256=WreJojIcJuLipnDXCLuAXgLmEHa5BjeUKyi7bL3LBIQ,1780
5
+ torch_tensorrt_executorch_runtime/lib/cmake/executorch_backend_tensorrt/executorch_backend_tensorrt-config-version.cmake,sha256=et0V7_XnGeNuspk1qDDJgbLvEk4qpEbS8xObxn7c714,1521
6
+ torch_tensorrt_executorch_runtime/lib/cmake/executorch_backend_tensorrt/executorch_backend_tensorrt-config.cmake,sha256=LhdiER9M2gbHwgCJ0RtY9w34NTuAQ0uNRzRj3xgXrDY,10779
7
+ torch_tensorrt_executorch_runtime-0.2.1.dist-info/METADATA,sha256=CuD3PwCnVoed2o99pyZB1gVlaCKCUOm6M-9Dl4YX5As,345
8
+ torch_tensorrt_executorch_runtime-0.2.1.dist-info/WHEEL,sha256=5n-CgQld_6-f-anITl61evRb_9II0FYTIGlQ4GPzXJc,106
9
+ torch_tensorrt_executorch_runtime-0.2.1.dist-info/top_level.txt,sha256=EDL5EcnNTN6SNWZn-k7R1pwDHMZyz4_YXfn6JT0vH2g,34
10
+ torch_tensorrt_executorch_runtime-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: false
4
+ Tag: py3-none-win_amd64
5
+ Build: 1
@@ -0,0 +1 @@
1
+ torch_tensorrt_executorch_runtime