Repository navigation
Python runtime rework - #4222
Python runtime rework #4222
Conversation
narendasan
left a comment
There was a problem hiding this comment.
Not sure this PR is clean yet
daad718 to
a328e80
Compare
a328e80 to
00e4ea2
Compare
00e4ea2 to
168bdea
Compare
|
I will revert the commit |
2b3b974 to
c6b8edf
Compare
There was a problem hiding this comment.
There are some changes that do not conform to Python style guidelines:
--- /home/runner/work/TensorRT/TensorRT/py/torch_tensorrt/dynamo/runtime/_TorchTensorRTModule.py 2026-05-04 23:59:29.343126+00:00
+++ /home/runner/work/TensorRT/TensorRT/py/torch_tensorrt/dynamo/runtime/_TorchTensorRTModule.py 2026-05-04 23:59:48.643676+00:00
@@ -38,10 +38,11 @@
Optional[SerializedTensorRTEngineFmt],
List[str],
List[str],
]
+
class TorchTensorRTModule(torch.nn.Module): # type: ignore[misc]
"""``nn.Module`` that runs a TensorRT engine inside PyTorch.
When the C++ Torch-TensorRT runtime is available, execution uses
``torch.classes.tensorrt.Engine`` and ``torch.ops.tensorrt.execute_engine``.
@@ -157,10 +158,11 @@
if k == "engine":
object.__setattr__(result, k, v) # shallow: reuse the same C++ Engine
else:
object.__setattr__(result, k, copy.deepcopy(v, memo))
return result
+
def _resolve_target_device(self) -> torch.device:
"""Resolve the engine's target CUDA device from compilation settings."""
if self.settings.device is not None:
return torch.device(f"cuda:{self.settings.device.gpu_id}")
return torch.device(f"cuda:{torch.cuda.current_device()}")
--- /home/runner/work/TensorRT/TensorRT/tests/py/dynamo/partitioning/test_000_resource_partitioning.py 2026-05-04 23:59:29.378025+00:00
+++ /home/runner/work/TensorRT/TensorRT/tests/py/dynamo/partitioning/test_000_resource_partitioning.py 2026-05-04 23:59:52.160386+00:00
@@ -17,10 +17,11 @@
ResourcePartitioner,
)
# Fixed RSS value to make memory-budget calculations deterministic.
_FIXED_RSS_BYTES = 512 * 1024 * 1024 # 512 MB
+
class TestResourcePartitioning(TestCase):
def test_atomic_subgraph_correction(self):
class net(nn.Module):
def __init__(self):
@@ -110,7 +111,8 @@
# The fusion should be fixed after the step
partitioner._verify_all_fusion_nodes_in_same_subgraph(new_subgraphs)
break
+
if __name__ == "__main__":
run_tests()
--- /home/runner/work/TensorRT/TensorRT/tests/py/dynamo/partitioning/test_001_resource_partitioning.py 2026-05-04 23:59:29.378025+00:00
+++ /home/runner/work/TensorRT/TensorRT/tests/py/dynamo/partitioning/test_001_resource_partitioning.py 2026-05-04 23:59:52.471763+00:00
@@ -25,10 +25,11 @@
resource_partition,
)
# Fixed RSS value used across all tests to make memory-budget calculations deterministic.
_FIXED_RSS_BYTES = 512 * 1024 * 1024 # 512 MB
+
class TestResourcePartitioning(TestCase):
def test_resource_partitioning(self):
class net(nn.Module):
def __init__(self):
@@ -413,7 +414,8 @@
== 4
), "The graph should have 4 accelerated subgraphs"
torch._dynamo.reset()
+
if __name__ == "__main__":
run_tests()42972f0 to
29673a1
Compare
narendasan
left a comment
There was a problem hiding this comment.
Cool I think this is looking good. One thing I think this shows is maybe we can keep the use_python_runtime but only register with torch in python only? then we arent losing user flexibility
| ABI_VERSION = "9" | ||
|
|
||
|
|
||
| class SerializedInfoIndex(IntEnum): |
There was a problem hiding this comment.
Feat. request for later is to move this into some sort of data that both C++ and python can load at build time
| Execution uses the C++ runtime engine when it is installed in the build; otherwise the | ||
| Python runtime engine is used. There is no separate process-wide backend switch | ||
| in ``torch_tensorrt.runtime``. |
There was a problem hiding this comment.
If c++ is built, is it able to switch to python runtime?
| elif ( | ||
| not ENABLED_FEATURES.torch_tensorrt_runtime and not settings.use_python_runtime | ||
| ): | ||
| if not ENABLED_FEATURES.torch_tensorrt_runtime: |
There was a problem hiding this comment.
Do you mean torch_tensorrt_cpp_runtime? the name is kind of confusing
There was a problem hiding this comment.
I think torch_tensorrt_runtime is the cpp runtime. I did not invent the name. It's been there for a while and I am just using it
| int64_t get_streamable_device_memory_budget(); | ||
| int64_t get_automatic_device_memory_budget(); | ||
| std::vector<at::Tensor> infer_outputs(std::vector<std::vector<int64_t>> input_shapes); | ||
| void set_pre_allocated_outputs(bool enable); |
There was a problem hiding this comment.
It's never used
3cd0a03 to
3538005
Compare
Rebased on top of main (post pytorch#4222 Python runtime rework). The original PR pytorch#4232 modified _PythonTorchTensorRTModule.py which was removed by pytorch#4222; the same stream-selection logic has been ported into the new _TRTEngine class. Behavior: - If the caller is on the default CUDA stream, keep legacy behavior: run the engine on a dedicated pool stream and synchronise via wait_stream. - If the caller is on a non-default stream (e.g. attached to a CUDA Green Context for SM partitioning), honor it: reuse the caller's stream for the engine and skip the wait_stream pair (saving extra syncs and preserving the caller's scheduling choice end to end). - When CUDA graphs are enabled and the engine stream changes between invocations, trigger graph recapture via runtime_states.context_changed so we don't replay a graph recorded against a stale stream. Implementation: - core/runtime/execute_engine.cpp: same logic in C++ (cudagraphs replay path + standard path). - py/torch_tensorrt/dynamo/runtime/_TRTEngine.py: new _prepare_streams helper called from both _execute_standard and _execute_output_allocator. - py/torch_tensorrt/dynamo/runtime/_CudaGraphsTorchTensorRTModule.py: same logic in the cudagraphs wrapper module.
Rebased on top of main (post pytorch#4222 Python runtime rework). The original PR pytorch#4232 modified _PythonTorchTensorRTModule.py which was removed by pytorch#4222; the same stream-selection logic has been ported into the new _TRTEngine class. Behavior: - If the caller is on the default CUDA stream, keep legacy behavior: run the engine on a dedicated pool stream and synchronise via wait_stream. - If the caller is on a non-default stream (e.g. attached to a CUDA Green Context for SM partitioning), honor it: reuse the caller's stream for the engine and skip the wait_stream pair (saving extra syncs and preserving the caller's scheduling choice end to end). - When CUDA graphs are enabled and the engine stream changes between invocations, trigger graph recapture via runtime_states.context_changed so we don't replay a graph recorded against a stale stream. Implementation: - core/runtime/execute_engine.cpp: same logic in C++ (cudagraphs replay path + standard path). - py/torch_tensorrt/dynamo/runtime/_TRTEngine.py: new _prepare_streams helper called from both _execute_standard and _execute_output_allocator. - py/torch_tensorrt/dynamo/runtime/_CudaGraphsTorchTensorRTModule.py: same logic in the cudagraphs wrapper module.
Rebased on top of main (post pytorch#4222 Python runtime rework). The original PR pytorch#4232 modified _PythonTorchTensorRTModule.py which was removed by pytorch#4222; the same stream-selection logic has been ported into the new _TRTEngine class. Behavior: - If the caller is on the default CUDA stream, keep legacy behavior: run the engine on a dedicated pool stream and synchronise via wait_stream. - If the caller is on a non-default stream (e.g. attached to a CUDA Green Context for SM partitioning), honor it: reuse the caller's stream for the engine and skip the wait_stream pair (saving extra syncs and preserving the caller's scheduling choice end to end). - When CUDA graphs are enabled and the engine stream changes between invocations, trigger graph recapture via runtime_states.context_changed so we don't replay a graph recorded against a stale stream. Implementation: - core/runtime/execute_engine.cpp: same logic in C++ (cudagraphs replay path + standard path). - py/torch_tensorrt/dynamo/runtime/_TRTEngine.py: new _prepare_streams helper called from both _execute_standard and _execute_output_allocator. - py/torch_tensorrt/dynamo/runtime/_CudaGraphsTorchTensorRTModule.py: same logic in the cudagraphs wrapper module.
Rebased on top of main (post pytorch#4222 Python runtime rework). The original PR pytorch#4232 modified _PythonTorchTensorRTModule.py which was removed by pytorch#4222; the same stream-selection logic has been ported into the new _TRTEngine class. Behavior: - If the caller is on the default CUDA stream, keep legacy behavior: run the engine on a dedicated pool stream and synchronise via wait_stream. - If the caller is on a non-default stream (e.g. attached to a CUDA Green Context for SM partitioning), honor it: reuse the caller's stream for the engine and skip the wait_stream pair (saving extra syncs and preserving the caller's scheduling choice end to end). - When CUDA graphs are enabled and the engine stream changes between invocations, trigger graph recapture via runtime_states.context_changed so we don't replay a graph recorded against a stale stream. Implementation: - core/runtime/execute_engine.cpp: same logic in C++ (cudagraphs replay path + standard path). - py/torch_tensorrt/dynamo/runtime/_TRTEngine.py: new _prepare_streams helper called from both _execute_standard and _execute_output_allocator. - py/torch_tensorrt/dynamo/runtime/_CudaGraphsTorchTensorRTModule.py: same logic in the cudagraphs wrapper module.
Rebased on top of main (post pytorch#4222 Python runtime rework). The original PR pytorch#4232 modified _PythonTorchTensorRTModule.py which was removed by pytorch#4222; the same stream-selection logic has been ported into the new _TRTEngine class. Behavior: - If the caller is on the default CUDA stream, keep legacy behavior: run the engine on a dedicated pool stream and synchronise via wait_stream. - If the caller is on a non-default stream (e.g. attached to a CUDA Green Context for SM partitioning), honor it: reuse the caller's stream for the engine and skip the wait_stream pair (saving extra syncs and preserving the caller's scheduling choice end to end). - When CUDA graphs are enabled and the engine stream changes between invocations, trigger graph recapture via runtime_states.context_changed so we don't replay a graph recorded against a stale stream. Implementation: - core/runtime/execute_engine.cpp: same logic in C++ (cudagraphs replay path + standard path). - py/torch_tensorrt/dynamo/runtime/_TRTEngine.py: new _prepare_streams helper called from both _execute_standard and _execute_output_allocator. - py/torch_tensorrt/dynamo/runtime/_CudaGraphsTorchTensorRTModule.py: same logic in the cudagraphs wrapper module.
Rebased on top of main (post pytorch#4222 Python runtime rework). The original PR pytorch#4232 modified _PythonTorchTensorRTModule.py which was removed by pytorch#4222; the same stream-selection logic has been ported into the new _TRTEngine class. Behavior: - If the caller is on the default CUDA stream, keep legacy behavior: run the engine on a dedicated pool stream and synchronise via wait_stream. - If the caller is on a non-default stream (e.g. attached to a CUDA Green Context for SM partitioning), honor it: reuse the caller's stream for the engine and skip the wait_stream pair (saving extra syncs and preserving the caller's scheduling choice end to end). - When CUDA graphs are enabled and the engine stream changes between invocations, trigger graph recapture via runtime_states.context_changed so we don't replay a graph recorded against a stale stream. Implementation: - core/runtime/execute_engine.cpp: same logic in C++ (cudagraphs replay path + standard path). - py/torch_tensorrt/dynamo/runtime/_TRTEngine.py: new _prepare_streams helper called from both _execute_standard and _execute_output_allocator. - py/torch_tensorrt/dynamo/runtime/_CudaGraphsTorchTensorRTModule.py: same logic in the cudagraphs wrapper module.
Rebased on top of main (post pytorch#4222 Python runtime rework). The original PR pytorch#4232 modified _PythonTorchTensorRTModule.py which was removed by pytorch#4222; the same stream-selection logic has been ported into the new _TRTEngine class. Behavior: - If the caller is on the default CUDA stream, keep legacy behavior: run the engine on a dedicated pool stream and synchronise via wait_stream. - If the caller is on a non-default stream (e.g. attached to a CUDA Green Context for SM partitioning), honor it: reuse the caller's stream for the engine and skip the wait_stream pair (saving extra syncs and preserving the caller's scheduling choice end to end). - When CUDA graphs are enabled and the engine stream changes between invocations, trigger graph recapture via runtime_states.context_changed so we don't replay a graph recorded against a stale stream. Implementation: - core/runtime/execute_engine.cpp: same logic in C++ (cudagraphs replay path + standard path). - py/torch_tensorrt/dynamo/runtime/_TRTEngine.py: new _prepare_streams helper called from both _execute_standard and _execute_output_allocator. - py/torch_tensorrt/dynamo/runtime/_CudaGraphsTorchTensorRTModule.py: same logic in the cudagraphs wrapper module.
Rebased on top of main (post pytorch#4222 Python runtime rework). The original PR pytorch#4232 modified _PythonTorchTensorRTModule.py which was removed by pytorch#4222; the same stream-selection logic has been ported into the new _TRTEngine class. Behavior: - If the caller is on the default CUDA stream, keep legacy behavior: run the engine on a dedicated pool stream and synchronise via wait_stream. - If the caller is on a non-default stream (e.g. attached to a CUDA Green Context for SM partitioning), honor it: reuse the caller's stream for the engine and skip the wait_stream pair (saving extra syncs and preserving the caller's scheduling choice end to end). - When CUDA graphs are enabled and the engine stream changes between invocations, trigger graph recapture via runtime_states.context_changed so we don't replay a graph recorded against a stale stream. Implementation: - core/runtime/execute_engine.cpp: same logic in C++ (cudagraphs replay path + standard path). - py/torch_tensorrt/dynamo/runtime/_TRTEngine.py: new _prepare_streams helper called from both _execute_standard and _execute_output_allocator. - py/torch_tensorrt/dynamo/runtime/_CudaGraphsTorchTensorRTModule.py: same logic in the cudagraphs wrapper module.
Rebased on top of main (post pytorch#4222 Python runtime rework). The original PR pytorch#4232 modified _PythonTorchTensorRTModule.py which was removed by pytorch#4222; the same stream-selection logic has been ported into the new _TRTEngine class. Behavior: - If the caller is on the default CUDA stream, keep legacy behavior: run the engine on a dedicated pool stream and synchronise via wait_stream. - If the caller is on a non-default stream (e.g. attached to a CUDA Green Context for SM partitioning), honor it: reuse the caller's stream for the engine and skip the wait_stream pair (saving extra syncs and preserving the caller's scheduling choice end to end). - When CUDA graphs are enabled and the engine stream changes between invocations, trigger graph recapture via runtime_states.context_changed so we don't replay a graph recorded against a stale stream. Implementation: - core/runtime/execute_engine.cpp: same logic in C++ (cudagraphs replay path + standard path). - py/torch_tensorrt/dynamo/runtime/_TRTEngine.py: new _prepare_streams helper called from both _execute_standard and _execute_output_allocator. - py/torch_tensorrt/dynamo/runtime/_CudaGraphsTorchTensorRTModule.py: same logic in the cudagraphs wrapper module.
…e rework PR pytorch#4222 merged PythonTorchTensorRTModule into TorchTensorRTModule and now wraps trt.ICudaEngine in TRTEngine. Update the integration helpers: - Drop the removed _PythonTorchTensorRTModule import; engine collection now matches only TorchTensorRTModule. - Add use_python_runtime=True to _trt_compile so the C++ runtime (which needs libtorchtrt_runtime.so to register torch.classes.tensorrt.Engine) is not required to run these tests. - Unwrap engines[0].engine via .cuda_engine in the inspector helpers since the Python runtime now returns a TRTEngine wrapper rather than a raw trt.ICudaEngine.
Drop the standalone test_001_cpp_runtime_rtx_features.py and extend the existing python-runtime test files (test_000_runtime_cache.py, test_001_dynamic_shapes_kernel_strategy.py, test_001_cuda_graph_strategy.py) to also exercise use_python_runtime=False via parameterized.expand over [(\"python\", True), (\"cpp\", False)]. Mirrors the pattern from the original pytorch#4202; updated for the post-pytorch#4222 unified runtime where there is no process-wide backend switch. Setup / whitebox introspection tests stay python-only because they read engine.runtime_config on the Python TRTEngine, which the C++ torch.classes.tensorrt.Engine does not expose. End-to-end inference, persistence, and typo-rejection tests run on both runtimes. Add a TestSerializationIndices class that verifies the new HAS_RUNTIME_CFG flag + three TRTRuntimeConfig slots are registered identically on both backends. Add a LOG_INFO(\"[torch-TensorRT C++ runtime] TRTEngine constructed from serialized info\") in the C++-only TRTEngine(std::vector<std::string>) constructor. Running compile with use_python_runtime=False under torch_tensorrt.logging.set_level(logging.INFO) produces exactly one such log line; use_python_runtime=True produces zero.
Drop the standalone test_001_cpp_runtime_rtx_features.py and extend the existing python-runtime test files (test_000_runtime_cache.py, test_001_dynamic_shapes_kernel_strategy.py, test_001_cuda_graph_strategy.py) to also exercise use_python_runtime=False via parameterized.expand over [(\"python\", True), (\"cpp\", False)]. Mirrors the pattern from the original pytorch#4202; updated for the post-pytorch#4222 unified runtime where there is no process-wide backend switch. Setup / whitebox introspection tests stay python-only because they read engine.runtime_config on the Python TRTEngine, which the C++ torch.classes.tensorrt.Engine does not expose. End-to-end inference, persistence, and typo-rejection tests run on both runtimes. Add a TestSerializationIndices class that verifies the new HAS_RUNTIME_CFG flag + three TRTRuntimeConfig slots are registered identically on both backends. Add a LOG_INFO(\"[torch-TensorRT C++ runtime] TRTEngine constructed from serialized info\") in the C++-only TRTEngine(std::vector<std::string>) constructor. Running compile with use_python_runtime=False under torch_tensorrt.logging.set_level(logging.INFO) produces exactly one such log line; use_python_runtime=True produces zero.
Two stale references on the Python-runtime branch of TorchTensorRTModule were left over from earlier in this PR and broke every test that runs a compiled module on the Python runtime: - ``setup_engine`` and ``set_extra_state`` were calling ``torch.ops.tensorrt.execute_engine_python``, but the custom op is registered as ``tensorrt::execute_engine`` (in _TRTEngine.py). The ``_python`` suffix was an intermediate name during PR pytorch#4222's dev cycle and never made it to main. Fixed both call sites to use the single shared op name, matching the C++-runtime branch and the docstring at the top of the class. - ``set_extra_state`` was still passing ``runtime_settings=self._runtime_settings`` to ``TRTEngine.__init__``, but the previous follow-up commit dropped that kwarg. Engine now constructs with default settings (matching what the caller assigned to ``self._runtime_settings`` two lines above) and applies any non-default settings via the post-load setter, same as the live ``setup_engine`` path.
test_native_nccl.py: - Fix test_distributed_mode_subgroup and test_distributed_mode_context_switch regressions introduced by PR #4222 (Python runtime rework): add dist.barrier(group=subgroup) before first TRT forward so PyTorch's lazy ncclComm_t is initialized and bind_nccl_comm() sees a non-zero getCommPtr(). - Remove all use_python_runtime=True flags (deprecated no-op in 2.13). - Add _cpp_runtime_available() guard to TestPythonRuntimePickle so it skips in C++ builds where _TRTEngine's custom op is never registered. - Fix _multirank_scatter_correctness / _multirank_gather_correctness in run_multirank_tests(): wrap with lambdas that loop over root ranks to match their (root, rank, world_size, device) signature (broken since PR #4321). - Remove _multirank_distributed_mode_subgroup_python and _multirank_distributed_mode_context_switch_python (cannot work when C++ extension is loaded); collapse _multirank_pg_migration to cpp-only. _nccl_utils.py: - setup_nccl_for_torch_tensorrt(): drop ensure_nccl_symlink() call and pre-load libnccl.so.2 directly instead of via the unversioned symlink. TRT 11.0+ (ncclWrapper.cpp) tries dlopen("libnccl.so.2") first, matching PyTorch's soname exactly; glibc reuses the already-loaded handle so no symlink is needed. ensure_nccl_symlink() is kept for TRT < 11.0 users. - Update module docstring to reflect confirmed TRT 11.0+ behavior.
test_native_nccl.py: - Fix test_distributed_mode_subgroup and test_distributed_mode_context_switch regressions introduced by PR #4222 (Python runtime rework): add dist.barrier(group=subgroup) before first TRT forward so PyTorch's lazy ncclComm_t is initialized and bind_nccl_comm() sees a non-zero getCommPtr(). - Remove all use_python_runtime=True flags (deprecated no-op in 2.13). - Add _cpp_runtime_available() guard to TestPythonRuntimePickle so it skips in C++ builds where _TRTEngine's custom op is never registered. - Fix _multirank_scatter_correctness / _multirank_gather_correctness in run_multirank_tests(): wrap with lambdas that loop over root ranks to match their (root, rank, world_size, device) signature (broken since PR #4321). - Remove _multirank_distributed_mode_subgroup_python and _multirank_distributed_mode_context_switch_python (cannot work when C++ extension is loaded); collapse _multirank_pg_migration to cpp-only. _nccl_utils.py: - setup_nccl_for_torch_tensorrt(): drop ensure_nccl_symlink() call and pre-load libnccl.so.2 directly instead of via the unversioned symlink. TRT 11.0+ (ncclWrapper.cpp) tries dlopen("libnccl.so.2") first, matching PyTorch's soname exactly; glibc reuses the already-loaded handle so no symlink is needed. ensure_nccl_symlink() is kept for TRT < 11.0 users. - Update module docstring to reflect confirmed TRT 11.0+ behavior.
test_native_nccl.py: - Fix test_distributed_mode_subgroup and test_distributed_mode_context_switch regressions introduced by PR #4222 (Python runtime rework): add dist.barrier(group=subgroup) before first TRT forward so PyTorch's lazy ncclComm_t is initialized and bind_nccl_comm() sees a non-zero getCommPtr(). - Remove all use_python_runtime=True flags (deprecated no-op in 2.13). - Add _cpp_runtime_available() guard to TestPythonRuntimePickle so it skips in C++ builds where _TRTEngine's custom op is never registered. - Fix _multirank_scatter_correctness / _multirank_gather_correctness in run_multirank_tests(): wrap with lambdas that loop over root ranks to match their (root, rank, world_size, device) signature (broken since PR #4321). - Remove _multirank_distributed_mode_subgroup_python and _multirank_distributed_mode_context_switch_python (cannot work when C++ extension is loaded); collapse _multirank_pg_migration to cpp-only. _nccl_utils.py: - setup_nccl_for_torch_tensorrt(): drop ensure_nccl_symlink() call and pre-load libnccl.so.2 directly instead of via the unversioned symlink. TRT 11.0+ (ncclWrapper.cpp) tries dlopen("libnccl.so.2") first, matching PyTorch's soname exactly; glibc reuses the already-loaded handle so no symlink is needed. ensure_nccl_symlink() is kept for TRT < 11.0 users. - Update module docstring to reflect confirmed TRT 11.0+ behavior.
…e rework PR pytorch#4222 merged PythonTorchTensorRTModule into TorchTensorRTModule and now wraps trt.ICudaEngine in TRTEngine. Update the integration helpers: - Drop the removed _PythonTorchTensorRTModule import; engine collection now matches only TorchTensorRTModule. - Add use_python_runtime=True to _trt_compile so the C++ runtime (which needs libtorchtrt_runtime.so to register torch.classes.tensorrt.Engine) is not required to run these tests. - Unwrap engines[0].engine via .cuda_engine in the inspector helpers since the Python runtime now returns a TRTEngine wrapper rather than a raw trt.ICudaEngine.
Unify Python and C++ TensorRT runtimes
PythonTorchTensorRTModule is removed. Both runtimes now live behind the same TorchTensorRTModule, with a single use_python_runtime flag (on CompilationSettings) selecting which path to take at engine setup.
What's changed
One module, two backends. TorchTensorRTModule.setup_engine() constructs either torch.classes.tensorrt.Engine (C++) or TRTEngine (Python) and binds the matching op to self.execute_engine_op. forward() just calls the bound op — no per-iteration branching, no separate module class.
Two equivalent ops. tensorrt::execute_engine (C++) and tensorrt::execute_engine_python (Python) are both registered and have the same signature, fake kernel, and semantics. The Python op is registered unconditionally so it's available even when the C++ runtime is loaded.
Checklist: