Repository navigation
Description
Bug Description
When a model takes a non-tensor argument, such as scale: float or mask=None, torch.export folds its value into the graph as a constant. Torch-TensorRT compiles and runs that graph correctly, and the engine's only input is the tensor x. Saving fails: torch_tensorrt.save(..., retrace=False) raises KeyError inside torch serialization, because the saved program's signature declares the folded inputs as tensors.
This issue covers the frozen case only. Each saved program serves one fixed value of scale and mask, which is what torch.export produces by default. Dynamic float inputs (SymFloat) are out of scope.
To Reproduce
Steps to reproduce the behavior:
- Save the script below as
repro.py. - Run
python repro.pyon a machine with a CUDA GPU. torch_tensorrt.saveraisesKeyError: 'scale'.
import torch
import torch_tensorrt
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(8, 8)
def forward(self, x, scale: float = 1.0, mask=None):
out = torch.relu(self.linear(x)) * scale
return out if mask is None else out * mask
model = Model().cuda().eval()
x = torch.randn(2, 8, device="cuda")
ep = torch.export.export(model, (x,), {"scale": 2.0, "mask": None})
trt_gm = torch_tensorrt.dynamo.compile(ep, arg_inputs=[x], kwarg_inputs={"scale": 2.0}, min_block_size=1)
torch_tensorrt.save(trt_gm, "trt.ep", retrace=False) File ".../torch/_export/serde/serialize.py", line 2274, in serialize
canonicalize(serialized_ep, set(constants.keys()))
File ".../torch/_export/serde/serialize.py", line 4351, in canonicalize
replace_input(spec)
File ".../torch/_export/serde/serialize.py", line 4247, in replace_input
t.name = replace_table[t.name]
KeyError: 'scale'
Passing only mask=None fails the same way, with KeyError: 'mask'.
The two programs declare the folded inputs differently:
| Program | x |
scale |
mask |
|---|---|---|---|
torch.export.export(...) (saves fine) |
TensorArgument |
ConstantArgument |
ConstantArgument |
Built by save(retrace=False) |
TensorArgument |
TensorArgument |
TensorArgument |
Neither graph reads scale or mask. torch.export writes aten.mul.Tensor(relu, 2.0), and after compilation the engine is called as execute_engine([x], engine)
Expected behavior
save(retrace=False) declares folded non-tensor user inputs as ConstantArgument, as torch.export does. The saved program then loads and runs with scale=2.0, mask=None, and rejects other values the way a torch.export program does: Expected input at 'scale' to be equal to 2.0, but got 3.0.
If saving these inputs is out of scope, save should reject them up front with an error that names the input, and the docs should say so. Today's KeyError reads like an internal bug.
Environment
Build information about Torch-TensorRT can be found by turning on debug messages
- Torch-TensorRT Version (e.g. 1.0.0): 2.14.0 (also reproduced on 2.13.0 and 2.8.0)
- PyTorch Version (e.g. 1.0): 2.14.1+cu130 (2.13.0+cu130, 2.8.0+cu128)
- CPU Architecture: x86_64
- OS (e.g., Linux): Ubuntu 24.04.5 LTS
- How you installed PyTorch (
conda,pip,libtorch, source): pip wheels, installed with uv - Build command you used (if compiling from source): N/A
- Are you using local sources or building from archives: prebuilt wheels
- Python version: 3.11.14 (3.12.3 for 2.8.0)
- CUDA version: 13.0 (12.8 for 2.8.0)
- GPU models and configuration: NVIDIA RTX PRO 6000 Blackwell Workstation Edition
- Any other relevant information: TensorRT 11.1.0.106 (11.0.0.114 with 2.13.0, 10.12.0.36 with 2.8.0); NVIDIA driver 595.99.02
Additional context
Cause: create_trt_exp_program builds every user input spec as a TensorArgument (_exporter.py#L496-L499, current main).
Possible fix: after lift(), change each user input whose placeholder meta["val"] is an int, float, bool, str or None to ConstantArgument(name=..., value=meta["val"]). The change has to run after lift(). ExportGraphSignature.user_inputs returns a constant's value rather than its name, and lift() uses node.name in graph_signature.user_inputs to find where to insert the lifted parameters.
We apply the same change outside Torch-TensorRT in AITune (ai-dynamo/aitune#123). With it, saving, loading with torch_tensorrt.load in a fresh process, and running inference give outputs that match eager on 2.8, 2.13 and 2.14, for static and dynamic batch.
Why wrapping the values in torch.tensor doesn't cover this: #3377 suggests passing Python-typed inputs as torch.tensor(...). That works for a float used in arithmetic, like scale, but not for:
-
None: an optional argument passed asNonehas no tensor form, and the model takes a different code path when it isNone. -
Flags that choose a code path:
torch.exportaccepts a Pythonboolbut fails on the tensor version (torch 2.14.1):class M(torch.nn.Module): def forward(self, x, use_relu=True): return torch.relu(x) if use_relu else x x = torch.randn(2, 4) torch.export.export(M(), (x,), {"use_relu": True}) # OK: ConstantArgument(use_relu) torch.export.export(M(), (x,), {"use_relu": torch.tensor(True)}) # GuardOnDataDependentSymNode
Libraries that compile models they don't own can't change the model's signature. We hit this in AITune, where models arrive with arguments like mask=None, or Hugging Face's return_dict=False and output_hidden_states=True.
Other save mode: retrace=True fails as well, because save accepts only tensor example inputs: ValueError: kwargs should not include None., and on 2.13 and 2.14 a float gives TypeError: Unsupported input type: <class 'float'>.
Related: #3377.
Activity
fix(torch-tensorrt): link save errors to upstream issue pytorch/Tenso…