Skip to content

🐛 [Bug] int8 math with an int8 constant does not wrap around on overflow #4989

Open

Description

@shoumikhin

Bug Description

With #4978 (not merged yet), a plain int8 constant (for example an int8 buffer) is stored as int32, because TensorRT accepts int8 constants only in front of a dequantize layer (or a plugin). Before that change, these graphs failed to build. Now they build, but the math runs in int32, so a result that overflows int8 does not wrap around the way it does in PyTorch.

  • If the int8 result is returned directly, the output cast wraps it back and the answer is right.
  • If the result feeds more math first, for example a cast to float, the answer is wrong and there is no error.

Add is only one example. Multiply, subtract, where and cat with an int8 constant also build now, and an overflowing multiply also differs from PyTorch (100 * 100 gives 10000 instead of 16).

To Reproduce

import torch
import torch_tensorrt


class M(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.register_buffer("b", torch.tensor([100, -100, 120, 5], dtype=torch.int8))

    def forward(self, x):
        return (self.b + x.to(torch.int8)).to(torch.float32)


m = M().cuda().eval()
x = torch.tensor([100.0, -100.0, 120.0, 5.0], device="cuda")
trt = torch_tensorrt.dynamo.compile(torch.export.export(m, (x,)), arg_inputs=[x], min_block_size=1)
print("eager   ", m(x).tolist())
print("tensorrt", trt(x).tolist())

With #4978:

eager    [-56.0, 56.0, -16.0, 10.0]
tensorrt [200.0, -200.0, 240.0, 10.0]

Without #4978 the build fails with Quantized constant (/add_lhs) is only allowed before DQ or PLUGIN_V2 or kPLUGIN_V3 node.

Expected behavior

The result matches PyTorch. Two possible ways:

The warning that #4978 logs for this case should also fire only when the result can actually differ. Today it also fires when the int8 result is returned directly, where the answer is right.

Environment

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions