Repository navigation
Description
Bug Description
I checked the 2.15 "Mutable QDP Plugins" feature (#4761) against the 2.15 release candidate on the test channel. The cases the release notes name work when the compiled module is called: operators returning None, a mutation-only graph, dynamic shapes, two mutated tensors in one operator, and the docs example. All 25 tests in tests/py/dynamo/automatic_plugin/test_automatic_plugin_inplace*.py and test_automatic_plugin_mutation.py pass. Saving and reloading in a fresh process also works for the docs example, for dynamic shapes, and for two mutated tensors.
Three problems remain. Each has its own section below with a standalone repro and its measured output:
- A non-contiguous mutated input silently doesn't get the update. The return value is right; no error is raised.
- A mutation-only graph can be saved but not loaded. With
retrace=False, the save itself fails. - QDP plugin attributes are dropped when an engine is saved. After a reload, the plugin fails with
KeyError. This isn't specific to mutation, but it means a mutating operator with a scalar argument can't be reloaded.
Environment
- Torch-TensorRT 2.15.0+cu132 from
https://download.pytorch.org/whl/test/cu132. Its Python sources are identical tov2.15.0-rc2, andv2.15.0-rc3doesn't change any file involved here. - PyTorch 2.15.0+cu132, TensorRT 11.4.0.106 (
tensorrt-cu13), CUDA 13.2 - Installed with pip, default C++ runtime
- Python 3.12, Linux x86_64, one NVIDIA A40, driver 580.95.05
1. A non-contiguous mutated input silently doesn't get the update
When the mutated input isn't contiguous, for example a transposed tensor or a column slice of a larger buffer, the compiled module returns the right value but leaves the caller's tensor unchanged. Eager PyTorch updates the tensor in place whatever its layout.
import torch
import torch_tensorrt
@torch.library.custom_op("repro::state_add", mutates_args=("state",))
def state_add(state: torch.Tensor, update: torch.Tensor) -> None:
state.add_(update)
@state_add.register_fake
def _(state, update):
return None
torch_tensorrt.dynamo.conversion.plugins.custom_op(
"repro::state_add", supports_dynamic_shapes=True
)
class Model(torch.nn.Module):
def forward(self, state, update):
state_add(state, update)
return state * 2
inputs = [torch.randn(8, 16, device="cuda") for _ in range(2)]
trt_model = torch_tensorrt.compile(Model(), ir="dynamo", inputs=inputs, min_block_size=1)
for name, state in {
"contiguous": torch.randn(8, 16, device="cuda"),
"transposed": torch.randn(16, 8, device="cuda").t(),
"column slice": torch.randn(8, 32, device="cuda")[:, :16],
}.items():
update = torch.randn(8, 16, device="cuda")
expected_state = state + update
out = trt_model(state, update)
print(
f"{name:>12}: return value correct: {torch.allclose(out, expected_state * 2)},"
f" state updated: {torch.allclose(state, expected_state)}"
)Output:
contiguous: return value correct: True, state updated: True
transposed: return value correct: True, state updated: False
column slice: return value correct: True, state updated: False
Expected: state updated: True in all three cases, as in eager PyTorch.
Cause: the C++ runtime binds a contiguous version of each input, which for a non-contiguous tensor is a new copy:
TensorRT/core/runtime/execute_engine.cpp
Line 164 in 6e8fc7d
| compiled_engine->active_input_tensors[i] = inputs[i].view(shape).contiguous(); |
The aliased mutation output is then bound to that copy, so the plugin writes into it. Nothing copies the result back to the caller's tensor:
TensorRT/core/runtime/execute_engine.cpp
Line 244 in 6e8fc7d
| outputs[pyt_idx] = aliased_input; |
Possible fix: after the engine runs, copy each mutated input's bound buffer back into the caller's tensor when they differ. Alternatively, raise an error for non-contiguous mutated inputs instead of silently dropping the update.
2. A mutation-only graph can be saved but not loaded
A model whose only effect is the mutation (it returns None) compiles and runs correctly. The default torch_tensorrt.save then writes a file that torch_tensorrt.load can't read, and retrace=False fails inside save.
import torch
import torch_tensorrt
@torch.library.custom_op("repro::state_add", mutates_args=("state",))
def state_add(state: torch.Tensor, update: torch.Tensor) -> None:
state.add_(update)
@state_add.register_fake
def _(state, update):
return None
torch_tensorrt.dynamo.conversion.plugins.custom_op(
"repro::state_add", supports_dynamic_shapes=True
)
class MutationOnly(torch.nn.Module):
def forward(self, state, update):
state_add(state, update)
inputs = [torch.randn(8, 16, device="cuda") for _ in range(2)]
trt_model = torch_tensorrt.compile(
MutationOnly(), ir="dynamo", inputs=inputs, min_block_size=1
)
state, update = torch.randn(8, 16, device="cuda"), torch.randn(8, 16, device="cuda")
expected_state = state + update
print("returns None:", trt_model(state, update) is None)
print("state updated:", torch.allclose(state, expected_state))
# The default save succeeds, but the file can't be loaded.
torch_tensorrt.save(trt_model, "mutation_only.ep", arg_inputs=inputs)
try:
torch_tensorrt.load("mutation_only.ep")
except Exception as e:
print(f"load failed: {type(e).__name__}: {e}")
# With retrace=False, the save itself fails.
torch_tensorrt.save(trt_model, "mutation_only_retrace_false.ep", retrace=False)Output, trimmed:
returns None: True
state updated: True
W1030 torch/export/__init__.py:403] ...
W1030 torch/export/__init__.py:403] File ".../torch/_export/serde/serialize.py", line 3402, in deserialize_multiple_outputs
W1030 torch/export/__init__.py:403] if not isinstance(serialized_node.outputs[0].value[0], TensorArgument):
W1030 torch/export/__init__.py:403] IndexError: list index out of range
load failed: ValueError: The file mutation_only.ep doesn't correspond to a valid Torchscript module or ExportedProgram. Please verify the file path.
Traceback (most recent call last):
File "repro_2_mutation_only_save.py", line 43, in <module>
torch_tensorrt.save(trt_model, "mutation_only_retrace_false.ep", retrace=False)
File ".../torch_tensorrt/_compile.py", line 1299, in save
exp_program = export(
File ".../torch_tensorrt/dynamo/_exporter.py", line 85, in export
patched_module = transform(
File ".../torch_tensorrt/dynamo/_exporter.py", line 131, in transform
inline_trt_modules(gm, cross_compile_module, expose_aliased_mutations)
File ".../torch_tensorrt/dynamo/_exporter.py", line 1049, in inline_trt_modules
assert num_outputs > 0
AssertionError
Expected: the saved file loads and still updates state when called. Failing that, save should raise a clear error rather than write a file that can't be loaded.
Cause: the saved execute_engine node has no outputs (outputs=[Argument(as_tensors=[])] in the deserializer's warning). The engine's fake kernel builds its outputs only from the user outputs recorded in inout_symexprs["outputs"], and that list doesn't include the hidden mutation outputs:
| output_info = shape_info.get("outputs", []) |
For a mutation-only engine, that list is empty. PyTorch 2.15's deserializer reads its first element without checking (torch/_export/serde/serialize.py:3402). The exporter used with retrace=False explicitly refuses engines without outputs:
TensorRT/py/torch_tensorrt/dynamo/_exporter.py
Line 1049 in 6e8fc7d
| assert num_outputs > 0 |
TorchScript isn't a way around it either: torch.jit.trace refuses a function that returns nothing ("The traced function didn't return any values!").
Possible fix: keep the hidden mutation outputs as outputs of the saved execute_engine node, so its output list is never empty, and drop them after the call as the module does now. At minimum, save could raise for engines with no outputs.
3. QDP plugin attributes are dropped when an engine is saved
This one isn't specific to mutation: the repro uses a functional operator, and a mutating operator with a scalar argument (state.add_(update * scale)) fails the same way. I also reproduced it on the 2.15.0.dev20260930 nightly with TensorRT 11.3.0.99, so it isn't new in TensorRT 11.4.
An operator registered with torch_tensorrt.dynamo.conversion.plugins.custom_op that takes a non-tensor argument runs correctly until it's saved. After it's reloaded, the plugin's enqueue fails with a KeyError for that argument.
import torch
import torch_tensorrt
@torch.library.custom_op("repro::scaled", mutates_args=())
def scaled(x: torch.Tensor, scale: float) -> torch.Tensor:
return x * scale
@scaled.register_fake
def _(x, scale):
return torch.empty_like(x)
torch_tensorrt.dynamo.conversion.plugins.custom_op(
"repro::scaled", supports_dynamic_shapes=True
)
class Model(torch.nn.Module):
def forward(self, x):
return scaled(x, 0.25) + 1
x = torch.randn(8, 16, device="cuda")
trt_model = torch_tensorrt.compile(Model(), ir="dynamo", inputs=[x], min_block_size=1)
print("before save, correct:", torch.allclose(trt_model(x), x * 0.25 + 1))
torch_tensorrt.save(trt_model, "scaled.ep", arg_inputs=[x])
reloaded = torch_tensorrt.load("scaled.ep").module()
print("after reload, correct:", torch.allclose(reloaded(x), x * 0.25 + 1))Output, trimmed:
before save, correct: True
[ERROR] Return value of get_fields_to_serialize() could not be interpreted as nvinfer1::PluginFieldCollection
[ERROR] Return value of get_fields_to_serialize() could not be interpreted as nvinfer1::PluginFieldCollection
[ERROR] Exception thrown from enqueue() KeyError: 'scale'
At:
.../tensorrt_bindings/plugin/_plugin_class.py(302): enqueue
...
ERROR: [Torch-TensorRT] - [pluginV3Runner.cpp::execute::252] Error Code 2: Internal Error (Assertion pluginUtils::isSuccess(status) failed. In execute at /_src/runtime/gpu/cuda/pluginV3Runner.cpp:252)
RuntimeError: [Error thrown at core/runtime/execute_engine.cpp:547] Expected ctx->enqueueV3(compiled_engine->engine_stream) to be true but got false
TensorRT failed to run engine _run_on_acc_0_engine, see the TensorRT error above
Expected: after reload, correct: True.
Cause: I wrapped TensorRT's _TemplatePluginBase.get_fields_to_serialize (tensorrt_bindings/plugin/_plugin_class.py) to log its calls. It's called four times in this script, and each call returns a valid PluginFieldCollection holding ('scale', FLOAT64). The two calls made while compiling, from interpreter_result.engine.serialize() in _conversion.py, succeed. The two calls made while save re-serializes the engine both print the [ERROR] above, so the saved engine has no scale field:
TensorRT/py/torch_tensorrt/_compile.py
Line 1674 in 6e8fc7d
| state = constant.__getstate__() |
Plugins without attributes, like the one in repros 1 and 2, still work after a reload, but every save of them prints the same [ERROR]. TorchTensorRTModule.state_dict() prints it too, for example in test_automatic_plugin_mutation.py::test_state_dict_preserves_hidden_output_count.
The Python side returns a valid collection, so the failure to read it looks like a TensorRT Python plugin bindings problem that may need a TensorRT bug. Until that's fixed, save could fail when a plugin's fields can't be serialized, instead of writing an engine that breaks when it runs.
Activity