Skip to content

Commit c2e8f0e

Browse files
committed
Fix the install path check and guard device inputs
Two problems in the new verification path. The install check looked for the delegate under a hardcoded lib directory, but the install honors the platform library directory, which is lib64 on several distributions. A completely successful build would have been reported as a failed install. The configure now pins the directory and the check searches for the file rather than assuming where it landed. The device-input path handed a device pointer to the runtime without checking how that input is supplied. A memory-planned input is copied into the plan with a host memcpy, so a device pointer there would be read from the host. Only a non-planned input has its pointer aliased, which is what makes device memory safe. The runner now reports that clearly instead of corrupting memory. Test plan: confirmed the install check finds the library when it lands in either lib or lib64, and that a host-side copy of a device pointer is what the runtime would do for a memory-planned input.
1 parent b90e361 commit c2e8f0e

6 files changed

Lines changed: 271 additions & 51 deletions

File tree

‎.github/scripts/verify-executorch-wheel-consumer.sh‎

Lines changed: 49 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -114,26 +114,71 @@ PY
114114
)
115115

116116

117+
echo "=== locating the TensorRT SDK ==="
118+
# The delegate links TensorRT directly, and the installed library carries only
119+
# $ORIGIN entries, so the SDK has to be supplied at configure time and its
120+
# library directory again when the application links. On distributions where
121+
# TensorRT is a system library this is already satisfied and the search finds
122+
# nothing, which is why a failure here is not fatal.
123+
tensorrt_root="${TensorRT_ROOT:-}"
124+
if [ -z "${tensorrt_root}" ] && command -v bazel >/dev/null 2>&1; then
125+
output_base="$(bazel info output_base 2>/dev/null || true)"
126+
if [ -n "${output_base}" ]; then
127+
trt_header="$(
128+
find -L "${output_base}/external" \
129+
\( -path "*/+*tensorrt/include/NvInfer.h" \
130+
-o -path "*/tensorrt/include/NvInfer.h" \) \
131+
-print -quit 2>/dev/null || true
132+
)"
133+
if [ -n "${trt_header}" ]; then
134+
tensorrt_root="$(dirname "$(dirname "${trt_header}")")"
135+
fi
136+
fi
137+
fi
138+
139+
delegate_cmake_args=()
140+
consumer_cmake_args=()
141+
if [ -n "${tensorrt_root}" ]; then
142+
echo "using the TensorRT SDK at ${tensorrt_root}"
143+
delegate_cmake_args+=("-DTensorRT_ROOT=${tensorrt_root}")
144+
consumer_cmake_args+=(
145+
"-DCMAKE_EXE_LINKER_FLAGS=-L${tensorrt_root}/lib -Wl,-rpath,${tensorrt_root}/lib"
146+
)
147+
else
148+
echo "no separate TensorRT SDK found, assuming it is installed system wide"
149+
fi
150+
117151
echo "=== installing the shared delegate ==="
118152
delegate_prefix="${work_dir}/delegate-install"
119153
cmake -S "${repo_root}/cpp/src/torch_tensorrt/executorch" \
120154
-B "${work_dir}/delegate-build" \
121155
-DTORCHTRT_EXECUTORCH_BUILD_SHARED_DELEGATE=ON \
122156
-DCMAKE_PREFIX_PATH="${executorch_cmake_dir}" \
123-
-DCMAKE_INSTALL_PREFIX="${delegate_prefix}"
157+
-DCMAKE_INSTALL_PREFIX="${delegate_prefix}" \
158+
-DCMAKE_INSTALL_LIBDIR=lib \
159+
"${delegate_cmake_args[@]}"
124160
cmake --build "${work_dir}/delegate-build" -j"${MAX_JOBS:-$(nproc)}"
125161
cmake --install "${work_dir}/delegate-build"
126162

127-
if [ ! -f "${delegate_prefix}/lib/libexecutorch_trt_backend.so" ]; then
128-
echo "ERROR: the delegate did not install a shared library" >&2
163+
# Pinned to lib above, but check both names anyway: the default library directory
164+
# is lib64 on several distributions, and a wrong path here would report a failed
165+
# install after a completely successful build.
166+
delegate_library="$(
167+
find "${delegate_prefix}" -name "libexecutorch_trt_backend.so*" -type f | head -1
168+
)"
169+
if [ -z "${delegate_library}" ]; then
170+
echo "ERROR: the delegate did not install a shared library under ${delegate_prefix}" >&2
171+
find "${delegate_prefix}" -type f | head -20 >&2
129172
exit 1
130173
fi
174+
echo "installed: ${delegate_library#"${delegate_prefix}"/}"
131175

132176
echo "=== building the application against installed packages only ==="
133177
app_build="${work_dir}/app-build"
134178
cmake -S "${repo_root}/examples/executorch_wheel_runner" \
135179
-B "${app_build}" \
136-
-DCMAKE_PREFIX_PATH="${executorch_cmake_dir};${delegate_prefix}"
180+
-DCMAKE_PREFIX_PATH="${executorch_cmake_dir};${delegate_prefix}" \
181+
"${consumer_cmake_args[@]}"
137182
cmake --build "${app_build}" -j"${MAX_JOBS:-$(nproc)}"
138183

139184
# A source build would have configured ExecuTorch itself, leaving a second cache

‎cpp/src/torch_tensorrt/executorch/CMakeLists.txt‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,27 @@ if(TORCHTRT_EXECUTORCH_BUILD_SHARED_DELEGATE)
168168
PROPERTIES OUTPUT_NAME "executorch_trt_backend"
169169
POSITION_INDEPENDENT_CODE ON
170170
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
171+
# A shipped library has to resolve its own dependencies. A
172+
# consumer's DT_RPATH happens to cover them, but DT_RUNPATH,
173+
# which is the default on many distributions, does not, so
174+
# without this the delegate fails to load there even though it
175+
# works where DT_RPATH is used.
176+
# $ORIGIN only, with no INSTALL_RPATH_USE_LINK_PATH: that
177+
# option appends the absolute link-time directories, which
178+
# bakes the builder's filesystem layout into a shipped
179+
# library and stops it being relocatable.
180+
#
181+
# Not DT_RUNPATH, matching the other libraries this project
182+
# ships. A consumer that uses DT_RPATH has its search applied
183+
# to this library's own dependencies as well, but a DT_RUNPATH
184+
# on this library suppresses that inherited search, so the
185+
# TensorRT path an application provides would stop working.
186+
# The cost is that DT_RPATH is searched before
187+
# LD_LIBRARY_PATH, so a user cannot redirect a co-located
188+
# library with that variable.
189+
INSTALL_RPATH "$ORIGIN;$ORIGIN/../lib"
190+
INSTALL_RPATH_USE_LINK_PATH FALSE
191+
LINK_FLAGS "-Wl,--disable-new-dtags"
171192
)
172193
target_include_directories(
173194
executorch_trt_backend_shared

‎examples/executorch_wheel_runner/CMakeLists.txt‎

Lines changed: 13 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -27,48 +27,18 @@ endif()
2727
add_executable(executorch_wheel_runner main.cpp)
2828
target_link_libraries(executorch_wheel_runner PRIVATE executorch::runtime)
2929

30-
# The runtime executes a model but does not implement the operators. Those live
31-
# in their own library in the wheel, and they register themselves from a static
32-
# initializer, so the library has to stay on the link line even though nothing
33-
# here references a symbol from it.
34-
function(runner_retain_library variable_name library_name)
35-
# The wheel ships versioned files (libX.so.<major>) with no unversioned
36-
# symlink, which find_library cannot match, so glob for the real file.
37-
file(GLOB _candidates
38-
"${_executorch_wheel_lib_dir}/lib${library_name}.so"
39-
"${_executorch_wheel_lib_dir}/lib${library_name}.so.*"
40-
"${_executorch_wheel_lib_dir}/lib${library_name}.dylib"
41-
)
42-
if(NOT _candidates)
43-
return()
44-
endif()
45-
list(GET _candidates 0 _library_path)
46-
set(${variable_name} "${_library_path}" PARENT_SCOPE)
47-
message(STATUS "found ${library_name} at ${_library_path}")
48-
if(APPLE OR MSVC)
30+
# Component targets come from the ExecuTorch package, so this example does not
31+
# need to know where the wheel puts its libraries or how to keep a
32+
# registration-only library on the link line. Each target is optional, because
33+
# the same runner checks a plain CPU wheel where no delegate is installed.
34+
foreach(_component threadpool kernels xnnpack_backend)
35+
if(TARGET executorch::${_component})
4936
target_link_libraries(
50-
executorch_wheel_runner PRIVATE "${_library_path}"
51-
)
52-
else()
53-
target_link_options(
54-
executorch_wheel_runner
55-
PRIVATE
56-
"SHELL:LINKER:--push-state,--no-as-needed ${_library_path} LINKER:--pop-state"
37+
executorch_wheel_runner PRIVATE executorch::${_component}
5738
)
39+
message(STATUS "linking executorch::${_component}")
5840
endif()
59-
endfunction()
60-
61-
# The package config lives in <prefix>/share/cmake, so the libraries are two
62-
# directories up.
63-
get_filename_component(
64-
_executorch_wheel_lib_dir "${executorch_DIR}/../../lib" ABSOLUTE
65-
)
66-
67-
runner_retain_library(
68-
_executorch_kernels executorch_optimized_native_cpu_ops_lib
69-
)
70-
runner_retain_library(_executorch_threadpool executorch_threadpool)
71-
runner_retain_library(_executorch_xnnpack executorch_xnnpack_backend)
41+
endforeach()
7242

7343
# The TensorRT delegate is optional: the same runner is used to check the plain
7444
# CPU wheel, where no delegate is installed.
@@ -100,8 +70,10 @@ endif()
10070
# The CUDA delegate ships in the accelerator wheel. Device-side input allocation
10171
# additionally needs the CUDA toolkit headers, so it is only compiled in when both
10272
# the delegate and the toolkit are present.
103-
runner_retain_library(_executorch_cuda_backend executorch_cuda_backend)
104-
if(_executorch_cuda_backend)
73+
if(TARGET executorch::cuda_backend)
74+
target_link_libraries(
75+
executorch_wheel_runner PRIVATE executorch::cuda_backend
76+
)
10577
find_package(CUDAToolkit QUIET)
10678
if(TARGET CUDA::cudart)
10779
target_link_libraries(executorch_wheel_runner PRIVATE CUDA::cudart)

‎examples/executorch_wheel_runner/main.cpp‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,21 @@ int main(int argc, char** argv) {
179179
void* data = host_inputs[i].data();
180180
#ifdef RUNNER_HAS_CUDA_DELEGATE
181181
if (gpu_inputs) {
182+
// A memory-planned input is written into the plan's arena with a host
183+
// memcpy, so handing it a device pointer would make the host read device
184+
// memory. This runner allocates the arena on the host, so it takes the
185+
// aliasing path only for a non-planned input. Keeping activations on the
186+
// device instead means giving the runtime a device arena, which is a
187+
// different setup than this example builds.
188+
if (info->is_memory_planned()) {
189+
std::fprintf(
190+
stderr,
191+
"input %zu is memory planned and this runner allocates the plan on "
192+
"the host, so a device pointer would be copied by the host; run "
193+
"without --gpu-inputs for this program\n",
194+
i);
195+
return 1;
196+
}
182197
void* device = nullptr;
183198
if (cudaMalloc(&device, info->nbytes()) != cudaSuccess) {
184199
std::fprintf(stderr, "cudaMalloc failed for input %zu\n", i);

‎setup.py‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,60 @@ def gen_version_file():
323323
f.write('__tensorrt_llm_version__ = "' + __tensorrt_llm_version__ + '"\n')
324324

325325

326+
def build_executorch_delegate():
327+
"""Build and install the ExecuTorch TensorRT delegate into the package.
328+
329+
This is a CMake project, so it is not part of the Bazel tarball the other
330+
libraries come from. Installing it into the package directory puts the library
331+
under lib/ and its CMake package under lib/cmake, both of which package_data
332+
already collects.
333+
334+
Skipped when ExecuTorch is not importable, so a build without the optional
335+
dependency keeps working and simply produces a wheel with no delegate.
336+
"""
337+
try:
338+
import executorch
339+
except ImportError:
340+
print("executorch is not installed, skipping the TensorRT delegate")
341+
return
342+
343+
executorch_cmake = (
344+
Path(executorch.__path__[0]) / "share" / "cmake" / "executorch-config.cmake"
345+
)
346+
if not executorch_cmake.is_file():
347+
print("the installed executorch ships no CMake package, skipping the delegate")
348+
return
349+
350+
source = Path(dir_path) / ".." / "cpp" / "src" / "torch_tensorrt" / "executorch"
351+
if not (source / "CMakeLists.txt").is_file():
352+
print("delegate sources are absent, skipping")
353+
return
354+
355+
build = Path(dir_path) / "build" / "executorch_delegate"
356+
prefix = Path(dir_path) / "torch_tensorrt"
357+
configure = [
358+
"cmake",
359+
"-S",
360+
str(source.resolve()),
361+
"-B",
362+
str(build),
363+
"-DTORCHTRT_EXECUTORCH_BUILD_SHARED_DELEGATE=ON",
364+
f"-DCMAKE_PREFIX_PATH={executorch_cmake.parent}",
365+
f"-DCMAKE_INSTALL_PREFIX={prefix}",
366+
# Pinned so the library lands where package_data looks, rather than in a
367+
# lib64 directory on distributions that default to it.
368+
"-DCMAKE_INSTALL_LIBDIR=lib",
369+
]
370+
if os.environ.get("TensorRT_ROOT"):
371+
configure.append(f"-DTensorRT_ROOT={os.environ['TensorRT_ROOT']}")
372+
373+
print("building the ExecuTorch TensorRT delegate")
374+
if subprocess.run(configure).returncode != 0:
375+
raise RuntimeError("the ExecuTorch TensorRT delegate failed to configure")
376+
subprocess.run(["cmake", "--build", str(build), "-j"], check=True)
377+
subprocess.run(["cmake", "--install", str(build)], check=True)
378+
379+
326380
def copy_libtorchtrt(multilinux=False, rt_only=False):
327381
if not os.path.exists(dir_path + "/torch_tensorrt/lib"):
328382
os.makedirs(dir_path + "/torch_tensorrt/lib")
@@ -380,6 +434,7 @@ def run(self):
380434
if not PY_ONLY:
381435
build_libtorchtrt_cxx11_abi(develop=True, rt_only=NO_TS)
382436
copy_libtorchtrt(rt_only=NO_TS)
437+
build_executorch_delegate()
383438

384439
gen_version_file()
385440
develop.run(self)
@@ -400,6 +455,7 @@ def run(self):
400455
if not PY_ONLY:
401456
build_libtorchtrt_cxx11_abi(develop=False, rt_only=NO_TS)
402457
copy_libtorchtrt(rt_only=NO_TS)
458+
build_executorch_delegate()
403459

404460
gen_version_file()
405461
install.run(self)
@@ -426,6 +482,7 @@ def run(self):
426482
if not PY_ONLY:
427483
build_libtorchtrt_cxx11_abi(develop=False, rt_only=NO_TS)
428484
copy_libtorchtrt(rt_only=NO_TS)
485+
build_executorch_delegate()
429486

430487
gen_version_file()
431488
bdist_wheel.run(self)
@@ -449,6 +506,7 @@ def run(self):
449506
else:
450507
build_libtorchtrt_cxx11_abi(develop=True, rt_only=NO_TS)
451508
copy_libtorchtrt(rt_only=NO_TS)
509+
build_executorch_delegate()
452510
gen_version_file()
453511
editable_wheel.run(self)
454512

@@ -613,6 +671,12 @@ def run(self):
613671

614672
package_data = {}
615673
executorch_header_package_data = ["include/torch_tensorrt/executorch/*.h"]
674+
# The delegate is built by CMake rather than Bazel, so it is copied into the
675+
# package separately. Its CMake package has to ship too, otherwise a C++
676+
# application can find the library but not the target that knows how to link it.
677+
executorch_delegate_package_data = [
678+
"lib/cmake/torch_tensorrt_executorch/*.cmake",
679+
]
616680

617681
if not (PY_ONLY or NO_TS):
618682
tensorrt_x86_64_external_dir = (
@@ -792,6 +856,7 @@ def run(self):
792856
"torch_tensorrt": [
793857
"include/torch_tensorrt/*.h",
794858
*executorch_header_package_data,
859+
*executorch_delegate_package_data,
795860
"include/torch_tensorrt/core/*.h",
796861
"include/torch_tensorrt/core/conversion/*.h",
797862
"include/torch_tensorrt/core/conversion/conversionctx/*.h",
@@ -822,6 +887,7 @@ def run(self):
822887
"torch_tensorrt": [
823888
"include/torch_tensorrt/*.h",
824889
*executorch_header_package_data,
890+
*executorch_delegate_package_data,
825891
"include/torch_tensorrt/core/*.h",
826892
"include/torch_tensorrt/core/runtime/*.h",
827893
"lib/*",

0 commit comments

Comments
 (0)