Skip to content

Commit f2a0c63

Browse files
committed
fix(conversion): decompose attention over a single key that TensorRT gets wrong
TensorRT 11.4's attention layer returns wrong values when the key length is 1 and the head size is small. With one key the softmax is 1, so the right answer is the value itself. Instead the output is off by up to about half (BF16) or holds inf (FP16 and FP32). FP16 and BF16 are wrong for head sizes 2 to 8, FP32 for head sizes 2 to 15. The query length does not matter, and with several heads some of these shapes happen to come out right. Separately, an FP16 attention whose query and key both have length 1 does not build with a head size of 32 or 64. A network built with the TensorRT Python API alone fails the same way, so this is a TensorRT bug. Seen on an A100 and an H100. The attention validators now decline these shapes when the key length is known to be 1: a head size below 16, or FP16 with a query length of 1 at any head size, since only a few head sizes were measured there. A declined scaled_dot_product_attention is decomposed into matmuls and softmax, which is exact here. A declined flash, efficient or cuDNN attention runs in PyTorch, as other declined cases of those ops already do. An FP32 attention cast from FP16 inputs, which TensorRT runs as an FP16 layer, is decomposed in FP32 for the FP16 shapes, like the one-row query case. They are declined on every TensorRT version, like the shared bfloat16 query case, because the result is correct either way. Other head sizes and keys longer than 1 keep the attention layer. test_single_key compiles these shapes and compares with PyTorch; each case fails without this change. test_other_short_keys_are_kept checks that nearby shapes still reach the attention layer. Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>
1 parent c516939 commit f2a0c63

3 files changed

Lines changed: 126 additions & 1 deletion

File tree

‎py/torch_tensorrt/dynamo/conversion/aten_ops_converters.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5635,6 +5635,29 @@ def _shares_bf16_query_with_another_attention(node: Node) -> bool:
56355635
)
56365636

56375637

5638+
def _single_key_attention_fails(
5639+
node: Node, dtype: Optional[torch.dtype] = None
5640+
) -> bool:
5641+
# TensorRT 11.4's attention layer gives wrong results (or inf) for a single key with a head size below 16, and
5642+
# cannot build some float16 ones whose query also has length 1. Seen on an A100 and an H100, and declined on
5643+
# every version, because a declined attention is still computed correctly.
5644+
query, key = (
5645+
arg.meta.get("val") if isinstance(arg, Node) else None for arg in node.args[:2]
5646+
)
5647+
if query is None or key is None or not statically_known_true(key.size(-2) == 1):
5648+
return False
5649+
if statically_known_true(query.size(-1) < 16) or (
5650+
(dtype or query.dtype) == torch.float16
5651+
and statically_known_true(query.size(-2) == 1)
5652+
):
5653+
_LOGGER.debug(
5654+
"Declining attention %s: TensorRT's attention layer fails for a single key of this shape.",
5655+
node.name,
5656+
)
5657+
return True
5658+
return False
5659+
5660+
56385661
def _output_quantized_to_fp8(node: Node) -> bool:
56395662
# Imported here: the lowering passes import this module.
56405663
from torch_tensorrt.dynamo.lowering.passes.annotate_fp8_sdpa import (
@@ -5724,6 +5747,8 @@ def scaled_dot_product_attention_validator(
57245747
node.name,
57255748
)
57265749
return False
5750+
if _single_key_attention_fails(node):
5751+
return False
57275752

57285753
attn_mask = args_bounds_check(node.args, 3, None)
57295754
is_causal = args_bounds_check(node.args, 5, False)
@@ -5830,6 +5855,9 @@ def scaled_dot_product_flash_attention_validator(
58305855
_LOGGER.debug("return_debug_mask is not yet supported.")
58315856
return False
58325857

5858+
if _single_key_attention_fails(node):
5859+
return False
5860+
58335861
query_shape, key_shape, value_shape = None, None, None
58345862
if "val" in node.args[0].meta:
58355863
query_shape = node.args[0].meta["val"].size()
@@ -5927,6 +5955,9 @@ def scaled_dot_product_efficient_attention_validator(
59275955
_LOGGER.debug("compute_log_sumexp is not yet supported.")
59285956
return False
59295957

5958+
if _single_key_attention_fails(node):
5959+
return False
5960+
59305961
query_shape, key_shape, value_shape = None, None, None
59315962
if "val" in node.args[0].meta:
59325963
query_shape = node.args[0].meta["val"].size()

‎py/torch_tensorrt/dynamo/lowering/passes/decompose_unsupported_attention.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from torch_tensorrt.dynamo.conversion.aten_ops_converters import (
1313
_PASS_THROUGH_OPS,
1414
_inputs_quantized_to_fp8,
15+
_single_key_attention_fails,
1516
attention_capability_validator,
1617
scaled_dot_product_attention_validator,
1718
scaled_dot_product_cudnn_attention_validator,
@@ -502,6 +503,12 @@ def decompose_unsupported_attention(
502503
node, settings, _folded_half(node) or torch.float32
503504
)
504505
)
506+
# It also fails to build like an FP16 layer.
507+
or (
508+
_decomposable(node)
509+
and _folded_half(node) == torch.float16
510+
and _single_key_attention_fails(node, torch.float16)
511+
)
505512
):
506513
declined.append((node, _FP32_ATTENTION[node.target]))
507514
elif _single_query_mask_ignored(node, settings):

‎tests/py/dynamo/conversion/test_attention_aten.py‎

Lines changed: 88 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@
66
import torch.nn as nn
77
import torch_tensorrt
88
from parameterized import param, parameterized
9-
from torch.testing._internal.common_cuda import PLATFORM_SUPPORTS_CUDNN_ATTENTION
9+
from torch.testing._internal.common_cuda import (
10+
PLATFORM_SUPPORTS_CUDNN_ATTENTION,
11+
PLATFORM_SUPPORTS_FLASH_ATTENTION,
12+
)
1013
from torch.testing._internal.common_utils import run_tests
1114
from torch_tensorrt import Input
1215
from torch_tensorrt.dynamo._settings import CompilationSettings
@@ -15,6 +18,7 @@
1518
from torch_tensorrt.dynamo.conversion._ConversionContext import ConversionContext
1619
from torch_tensorrt.dynamo.conversion.aten_ops_converters import (
1720
attention_capability_validator,
21+
scaled_dot_product_attention_validator,
1822
)
1923

2024
from .harness import DispatchTestCase, skip_if_trt_rtx_turing
@@ -643,6 +647,89 @@ def forward(self, query, key, value, mask):
643647
compiled(*inputs), Attention()(*inputs), rtol=1e-2, atol=1e-2
644648
)
645649

650+
@parameterized.expand(
651+
[
652+
param("float32", dtype=torch.float32),
653+
param("float32_head_size_12", dtype=torch.float32, head_size=12),
654+
param(
655+
"bfloat16_five_queries", dtype=torch.bfloat16, query_len=5, head_size=6
656+
),
657+
param("float16", dtype=torch.float16),
658+
param("float16_head_size_32", dtype=torch.float16, head_size=32),
659+
param("efficient", op="efficient", dtype=torch.float32, query_len=5),
660+
param("flash", op="flash", dtype=torch.bfloat16),
661+
# TensorRT would fold the casts and run the attention layer in FP16.
662+
param(
663+
"float32_cast_from_float16",
664+
op="cast",
665+
dtype=torch.float16,
666+
head_size=32,
667+
),
668+
]
669+
)
670+
def test_single_key(self, _, dtype, op="sdpa", query_len=1, head_size=8):
671+
if dtype == torch.bfloat16:
672+
skip_if_trt_rtx_turing(self, "bfloat16")
673+
if op == "flash" and not PLATFORM_SUPPORTS_FLASH_ATTENTION:
674+
self.skipTest("Platform doesn't support flash attention")
675+
676+
class Attention(nn.Module):
677+
def forward(self, query, key, value):
678+
if op == "efficient":
679+
efficient = torch.ops.aten._scaled_dot_product_efficient_attention
680+
return efficient.default(query, key, value, None, False)[0]
681+
if op == "flash":
682+
flash = torch.ops.aten._scaled_dot_product_flash_attention
683+
return flash.default(query, key, value)[0]
684+
if op == "cast":
685+
query, key, value = (t.float() for t in (query, key, value))
686+
return torch.ops.aten.scaled_dot_product_attention.default(
687+
query, key, value, scale=0.125
688+
).half()
689+
return torch.ops.aten.scaled_dot_product_attention.default(
690+
query, key, value
691+
)
692+
693+
# With more heads TensorRT gets some of these shapes right, so one head shows the bug best.
694+
query = torch.randn(1, 1, query_len, head_size, dtype=dtype, device="cuda")
695+
key, value = (
696+
torch.randn(1, 1, 1, head_size, dtype=dtype, device="cuda")
697+
for _ in range(2)
698+
)
699+
inputs = (query, key, value)
700+
compiled = torch_tensorrt.dynamo.compile(
701+
torch.export.export(Attention(), inputs),
702+
arg_inputs=inputs,
703+
min_block_size=1,
704+
)
705+
torch.testing.assert_close(
706+
compiled(*inputs), Attention()(*inputs), rtol=1e-2, atol=1e-2
707+
)
708+
709+
def test_other_short_keys_are_kept(self):
710+
sdpa = torch.ops.aten.scaled_dot_product_attention.default
711+
for dtype, query_len, key_len, head_size in (
712+
(torch.bfloat16, 1, 1, 16),
713+
(torch.bfloat16, 1, 2, 8),
714+
(torch.float16, 2, 1, 64),
715+
(torch.bfloat16, 1, 1, 64),
716+
):
717+
graph = torch.fx.Graph()
718+
query, key, value = (graph.placeholder(n) for n in "qkv")
719+
query.meta["val"] = torch.empty(
720+
1, 2, query_len, head_size, dtype=dtype, device="meta"
721+
)
722+
key.meta["val"] = value.meta["val"] = torch.empty(
723+
1, 2, key_len, head_size, dtype=dtype, device="meta"
724+
)
725+
node = graph.call_function(sdpa, (query, key, value))
726+
with self.subTest(
727+
dtype=dtype, query_len=query_len, key_len=key_len, head_size=head_size
728+
):
729+
self.assertTrue(
730+
scaled_dot_product_attention_validator(node, CompilationSettings())
731+
)
732+
646733
@parameterized.expand(
647734
[("sdpa", 1, 8), ("sdpa", 1, 2048), ("efficient", 6, 4), ("efficient", 1, 2048)]
648735
)

0 commit comments

Comments
 (0)