Repository navigation
Description
Bug Description
True division of integer tensors (a / b, torch.div(a, b) without rounding_mode) returns truncated values when the operands are int64, or when one operand is a Python int. PyTorch returns a floating-point result there. Torch-TensorRT runs an integer DIV instead, so ratios like torch.arange(n) / 10 or count / total silently come out as whole numbers (mostly zeros).
int32 tensor / int32 tensor works, because cast_int_int_div_trt_tensor in py/torch_tensorrt/dynamo/conversion/converter_utils.py only casts when both operands are trt.int32 TRT tensors:
if lhs_val.dtype == trt.int32 and rhs_val.dtype == trt.int32:and impl.elementwise.div only calls it when both operands are TRT tensors. int64 (PyTorch's default integer type), int8, uint8 and bool tensors, and any Python scalar divisor, keep integer division.
To Reproduce
import torch
import torch_tensorrt
class Norm(torch.nn.Module):
def forward(self, idx):
return idx / 10
class Ratio(torch.nn.Module):
def forward(self, count, total):
return count / total
def trt(model, *args):
return torch_tensorrt.compile(model.eval().cuda(), ir="dynamo", inputs=list(args), min_block_size=1)(*args)
idx = torch.arange(5, device="cuda")
print(Norm()(idx).tolist(), trt(Norm(), idx).tolist())
count = torch.tensor([1, 2, 3], device="cuda")
total = torch.tensor([4, 4, 4], device="cuda")
print(Ratio()(count, total).tolist(), trt(Ratio(), count, total).tolist())
print(Ratio()(count.int(), total.int()).tolist(), trt(Ratio(), count.int(), total.int()).tolist())Output:
[0.0, 0.10000000149011612, 0.20000000298023224, 0.30000001192092896, 0.4000000059604645] [0.0, 0.0, 0.0, 0.0, 0.0]
[0.25, 0.5, 0.75] [0.0, 0.0, 0.0]
[0.25, 0.5, 0.75] [0.25, 0.5, 0.75]
Expected behavior
The same floating-point results as PyTorch, as the int32 case already gives.
Environment
- Torch-TensorRT Version: 2.14.0 (pip).
cast_int_int_div_trt_tensorandimpl.elementwise.divare the same on main. - PyTorch Version: 2.14.1+cu130
- CPU Architecture: x86_64
- OS: Ubuntu 26.04 (WSL2)
- How you installed PyTorch: pip
- Python version: 3.12
- CUDA version: 13.0 (TensorRT 11.1.0.106)
- GPU models and configuration: NVIDIA GeForce RTX 5060 Ti, driver 596.49
Additional context
I found this by comparing converted models with eager PyTorch on a range of inputs. I have a fix with tests and can open a PR. It casts both operands of a true division to float32 when both are integer or bool, whether they are TRT tensors, PyTorch tensors or Python scalars.
Activity