Repository navigation
Description
Description
INetworkDefinition.add_attention_v2 (IAttention, with decomposable = True) returns wrong values when the key length is 1 and the head size is small: 2 to 15 in FP32, and 2 to 8 in FP16 and BF16. With one key, softmax is 1, so the output should equal value. Instead:
- FP32: the output contains inf.
- BF16: the output is off by about half (relative error 0.42 to 0.58, sometimes NaN).
- FP16: the output contains inf.
The query length does not matter (1, 3 and 5 all fail). Head size 1, head sizes of 16 or more, and any key length of 2 or more are correct. With 4 or more heads, some of these shapes (for example FP32, query length 1, head size 8) come out right, while head size 6 is wrong for every batch and head count tried. The wrong values change with the inputs and the GPU, so it may be reading memory it should not.
Separately, an FP16 attention whose query and key both have length 1 does not build with head size 32 or 64 (batch 1, 1 or 2 heads). Head sizes 16, 24, 128 and 256 build and are correct:
Error Code: 9: Skipping tactic 0x0000000000000000 due to exception [myelin_graph.h:1295: attachExceptionMsgToGraph] MyelinCheckException: nvrtc_compile.cpp:1179: CHECK(success) failed. NVRTC Compilation failure
Error Code 10: Internal Error (Could not find any implementation for node {ForeignNode[(Unnamed Layer* 0) [Constant]...(Unnamed Layer* 4) [AttentionOutput]]}.)
FP32 and BF16 build for those shapes. With decomposable = False, none of the shapes below build ("Attention operation was not supported by a dedicated kernel"), so the wrong results come from the decomposed path.
Environment
- TensorRT 11.4.0.106 (Python wheel)
- GPUs: NVIDIA A100 80GB and NVIDIA H100, same results
- Driver 580, CUDA 13.2, Linux x86_64
- PyTorch is used only to allocate buffers and compute the reference
Steps to reproduce
import math
import tensorrt as trt
import torch
TRT_TYPE = {torch.float32: trt.float32, torch.float16: trt.float16, torch.bfloat16: trt.bfloat16}
def attention(q, k, v):
logger = trt.Logger(trt.Logger.ERROR)
builder = trt.Builder(logger)
net = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED))
dt = TRT_TYPE[q.dtype]
tq, tk, tv = (net.add_input(n, dt, tuple(t.shape)) for n, t in (("q", q), ("k", k), ("v", v)))
scale = torch.full((1, 1, 1, 1), 1 / math.sqrt(q.shape[-1]), dtype=q.dtype)
c = net.add_constant((1, 1, 1, 1), trt.Weights(dt, scale.data_ptr(), 1))
sq = net.add_elementwise(tq, c.get_output(0), trt.ElementWiseOperation.PROD)
layer = net.add_attention_v2(
sq.get_output(0), tk, tv, trt.AttentionNormalizationOp.SOFTMAX, trt.CausalMaskKind.NONE
)
layer.decomposable = True
out = layer.get_output(0)
out.name = "out"
net.mark_output(out)
plan = builder.build_serialized_network(net, builder.create_builder_config())
if plan is None:
return "build failed"
ctx = trt.Runtime(logger).deserialize_cuda_engine(plan).create_execution_context()
o = torch.empty(q.shape[:-1] + v.shape[-1:], dtype=q.dtype, device="cuda")
for name, t in (("q", q), ("k", k), ("v", v), ("out", o)):
ctx.set_tensor_address(name, t.data_ptr())
ctx.execute_async_v3(torch.cuda.current_stream().cuda_stream)
torch.cuda.synchronize()
return o
print("TensorRT", trt.__version__, torch.cuda.get_device_name())
for dtype, lq, lk, d in [
(torch.float32, 1, 1, 8), (torch.bfloat16, 1, 1, 8), (torch.float16, 1, 1, 8),
(torch.float32, 1, 1, 16), (torch.float32, 1, 2, 8),
(torch.float16, 1, 1, 32), (torch.float16, 1, 1, 64),
]:
torch.manual_seed(0)
q = torch.randn(1, 1, lq, d, dtype=dtype, device="cuda")
k = torch.randn(1, 1, lk, d, dtype=dtype, device="cuda")
v = torch.randn(1, 1, lk, d, dtype=dtype, device="cuda")
ref = torch.nn.functional.scaled_dot_product_attention(q.double(), k.double(), v.double())
o = attention(q, k, v)
err = o if isinstance(o, str) else f"max abs error {(o.double() - ref).abs().max().item():.3g}"
print(f"{str(dtype)[6:]:8} Lq={lq} Lk={lk} D={d:2}: {err}")Expected
Every case builds, and the max abs error is close to 0 (with one key the output is v).
Actual (A100)
TensorRT 11.4.0.106 NVIDIA PG509-210
float32 Lq=1 Lk=1 D= 8: max abs error inf
bfloat16 Lq=1 Lk=1 D= 8: max abs error 0.902
float16 Lq=1 Lk=1 D= 8: max abs error inf
float32 Lq=1 Lk=1 D=16: max abs error 0
float32 Lq=1 Lk=2 D= 8: max abs error 1.65e-07
float16 Lq=1 Lk=1 D=32: build failed
float16 Lq=1 Lk=1 D=64: build failed
On an H100 the same shapes fail. There, FP32 with one query gives a relative error of 0.42 (head size 6) and 0.58 (head size 8) instead of inf, and gives inf with 5 queries.
As a workaround, Torch-TensorRT can avoid IAttention for these shapes and build the attention from matrix multiplies and softmax, which gives exact results (pytorch/TensorRT#5074).
Activity