Skip to content

fix(dynamo): avoid TensorRT attention bugs with a masked one-row query or a single key - #5074

Draft
shoumikhin wants to merge 3 commits into
pytorch:mainfrom
shoumikhin:single-query-mask-decompose
Draft

shoumikhin wants to merge 3 commits into
pytorch:mainfrom
shoumikhin:single-query-mask-decompose

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

What is wrong today

TensorRT 11.4 (also 11.2 and 11.3 for the first) silently gets these attention cases wrong:

  • A one-row query with a mask. With the query length fixed at 1, a head size that is a multiple of 8 and a long key, the mask is dropped. So decode over a fixed size KV cache reads unwritten slots. FP16 is wrong from 513 keys, BF16 from 57344 (8192 with hardware_compatible=True).
  • A single key. With key length 1 and a head size of 2 to 8 (2 to 15 in FP32), the output is off or holds inf, except for a one-row query with head size 8 and at least 4 heads (batch times heads). With query and key length 1, FP16 does not build at head size 32 or 64 with fewer than 4 heads.

What this change does

decompose_unsupported_attention gives such an attention more query rows:

  • Grouped-query attention, no causal mask, static head counts: query heads sharing a key head become its rows.
  • Otherwise: the row is repeated and the first output row kept.

This runs only on affected versions, for keys past the limit (BF16 keeps a margin).

The validators decline exactly the failing single-key shapes, on every version, and judge float64 as FP32 with truncate_double=True. The pass decomposes a declined scaled_dot_product_attention, efficient or cuDNN attention in FP32 (float64 stays float64), so FP16 scores cannot overflow and a hidden key gives zeros. Declined flash attention, efficient or cuDNN attention that reads other outputs or has a bias and a causal mask, and attention read by as_strided, run in PyTorch.

An FP32 attention cast from 16-bit inputs, which TensorRT runs as a 16-bit layer, is decomposed in FP32 in both cases.

Cost

A rewritten masked decode attention is 4x to 7x slower (A100, FP16).

Not covered (wrong before too): an optimization profile that alone fixes the query length at 1, and cast FP32 efficient attention with a bias and a causal mask.

Tests

  • Engine tests: masked one-row attention per op, dtype, key limit, hardware_compatible, FP32 cast and dynamic key; single-key attention with FP16 overflow, a hidden key, and a bias.
  • Lowering and validator tests: limits, versions, shapes kept and declined, float64, an as_strided reader. Both files pass on an A100 with TensorRT 11.4. Each new test fails without its fix (except head size 100, which passes on the base branch too).

@meta-cla meta-cla Bot added the cla signed label Nov 18, 2026
@github-actions github-actions Bot added component: tests Issues re: Tests component: lowering Issues re: The lowering / preprocessing passes component: core Issues re: The core compiler component: api [Python] Issues re: Python API component: dynamo Issues relating to the `torch.compile` or `torch._dynamo.export` paths labels Nov 18, 2026
@github-actions
github-actions Bot requested a review from zewenli98 November 18, 2026 19:27
@shoumikhin
shoumikhin force-pushed the single-query-mask-decompose branch from 6e588d2 to 3e6e9cd Compare November 18, 2026 19:27
@shoumikhin
shoumikhin force-pushed the single-query-mask-decompose branch 3 times, most recently from f806fba to 2e570df Compare November 23, 2026 20:40
@shoumikhin
shoumikhin marked this pull request as draft November 23, 2026 21:54
@shoumikhin
shoumikhin force-pushed the single-query-mask-decompose branch from 2e570df to f2a0c63 Compare November 25, 2026 06:11
@shoumikhin shoumikhin changed the title fix(lowering): attention with a one-row query ignores its mask fix(dynamo): avoid TensorRT attention bugs with a masked one-row query or a single key Nov 25, 2026
@github-actions github-actions Bot added the component: conversion Issues re: Conversion stage label Nov 25, 2026
@shoumikhin
shoumikhin force-pushed the single-query-mask-decompose branch 2 times, most recently from 9cd07c4 to 5cca30d Compare November 25, 2026 23:14
TensorRT's attention layer drops the mask when the query length is fixed at 1
and the key is long. The output is attention over every key, as if no mask were
set. A causal mask is dropped the same way. TensorRT 11.2, 11.3 and 11.4 all
drop it. With 11.4 the output is wrong in FP16 from 513 keys and in BF16 from
57344 keys, the same on an A100, a Jetson Thor and a Jetson Orin. A query with 2
or more rows is masked correctly. TensorRT-RTX 1.7 masks correctly.

This is the shape of a decode step over a fixed size KV cache, so such a step
attends to the cache slots that are not written yet.

decompose_unsupported_attention now gives such an attention more query rows
before it reaches the attention layer, on the TensorRT versions above. This
covers scaled_dot_product_attention and the efficient and cuDNN attention ops:

- With grouped-query attention and no causal mask, the query heads that share
  a key head become the query rows of one attention per key head. A mask with
  one entry per query head is regrouped the same way. Each key and value head
  is still read once.
- Otherwise the query row is repeated and the first output row is kept.

The result is copied to the memory order the original attention returns, so
a reader of its strides, such as as_strided after a transposed query, gets the
same values where PyTorch runs the graph.

The attention layer, its scaling and its handling of the mask stay as they
were. Only 16-bit attention with a mask or a causal mask, a query length fixed
at 1 and a key that can be longer than 512 (FP16) or 32768 (BF16) is changed.
Shorter keys, a query length that is not fixed (masked correctly when it runs
at 1), fused FP8 attention and FP32 attention (apart from the case below) are
not. Not covered: an engine with several optimization profiles of which one
fixes the query length at 1 (the pass sees one dynamic query length), and an
FP32 efficient attention cast from 16-bit inputs that has both a bias and a
causal mask (the decomposition takes only one of them; it was wrong before
too).

The FP16 limit is sharp: 512 keys were right and 513 wrong for every head size
from 32 to 256, head count and batch measured. BF16 keys from 32769 to 55296
were still correct. They are changed too, as a margin. In the shapes measured
that made them faster (40000 keys, 32 query heads: 1.58 ms -> 0.27 ms with 8
key heads, 1.63 ms -> 0.91 ms with 32), but the FP32 case below is about 1.4x
slower there. Shorter keys are left alone, because more query rows were slower
there: up to 1.2x in FP16, and up to 1.4x in BF16 at 4096 keys.

An FP32 attention whose inputs are cast from FP16 or BF16 can be run by TensorRT
as a 16-bit layer again, so it drops the mask too. More query rows would sit
between the casts and the layer, so such an attention is decomposed in FP32
instead, as the pass already does where that layer fails to build. Where
PyTorch runs the FP32 decomposition, it now also works when a dynamic key is
empty. Export takes a dynamic key to be longer than 1, so amax was traced in
and failed on zero keys where PyTorch returns zeros. For a dynamic key it now
checks with any. A compiled engine never sees zero keys, because its profile
starts at 1.

The correct result costs more than the wrong one, because the mask is now
applied. Measured on an A100 in FP16, head size 64, with CUDA graph replay:

- 32 query heads, 2 key heads, 16384 keys: 0.06 ms -> 0.42 ms per attention.
- 32 heads, 4096 keys: 0.03 ms -> 0.24 ms, about 7x.

Other timing methods gave smaller ratios, down to about 4x.

Decomposing the attention into matmuls and softmax was 1.2x to 2.9x faster in
the shapes measured. It is not used for 16-bit attention because in FP16 it can
overflow, while the attention layer keeps its own scaling.

Each new test fails when the part of this change it covers is removed. A
version table test pins which TensorRT versions the version check accepts.
test_single_query_mask and the causal
cases also check the rewritten graph against the original op, since run_test
uses that graph as its reference. test_single_query_mask_compiled compiles BF16,
the FP32 cast case and a dynamic key length with torch_tensorrt.dynamo.compile.

Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>
…re_compatible

TensorRT 11.4 drops the mask of a one-row query only when the head size is a
multiple of 8. Other head sizes are already masked correctly, and TensorRT
cannot build them with 2 query rows or with grouped heads folded into rows, so
the rewrite made models with head sizes such as 12, 20, 36, 44, 52 or 100 fail
to compile. The rewrite now runs only for head sizes that are a multiple of 8.

With hardware_compatible=True, TensorRT 11.4 drops the mask of a one-row BF16
query from 8192 keys (7680 keys were still correct, on an A100 and an H100),
while the pass acted only above 32768. The key limits now depend on
hardware_compatible, with a BF16 limit of 4096 there. The FP16 edge is the same.

test_single_query_mask_compiled adds head size 100, BF16 and FP16 with
hardware_compatible, and the FP32 efficient attention cast from FP16, and
passes a non-default scale to the rewritten attention. The lowering test checks
the key just past and right at each limit. Each case fails without its fix.
Head size 100 also passes on the base branch, where there is no rewrite: it
guards the head size check. Comments now say why the other outputs block the
rewrite, when grouped heads are folded, and which ops need the expanded bias.

Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>
…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 far off (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, for every query length and head count, with one
exception: a one-row query with a head size of 8 is right with 4 or more heads
in all (batch times heads). Separately, an FP16 attention whose query and key
both have length 1 does not build with a head size of 32 or 64 and fewer than 4
heads in all. 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 exactly these shapes when the key length
is known to be 1. A float64 attention counts as FP32 with truncate_double,
because TensorRT then runs it in FP32. The pass decomposes a declined
scaled_dot_product_attention, efficient or cuDNN attention into matmuls and
softmax in FP32, and casts the result back. A float64 one stays in float64.
In FP16 the product of the query and the one key can overflow, and in 16 bits
the softmax of a hidden key is NaN, where PyTorch gives the value and zeros.
FP32 avoids both. Decomposing also keeps efficient attention with a bias in
TensorRT. Left to PyTorch, its kernel rejects a bias that comes out of an
engine with unaligned strides, and with require_full_compilation=True the
model would no longer compile. Efficient and cuDNN attention whose other
outputs are read, or that has both a bias and is_causal, cannot be decomposed
and is left to PyTorch, as is declined flash attention. An attention whose
output as_strided or another reader of its memory reads is left to PyTorch too,
because the decomposition does not keep the memory order of the op's output.
For those, a shape that gave wrong values now raises an error with
require_full_compilation=True, and an efficient attention with such a bias can
fail when called. An FP32 attention cast from FP16 inputs, which TensorRT runs
as an FP16 layer, is decomposed in FP32 for the FP16 shapes. They are declined
on every TensorRT version, like the shared bfloat16 query case, because the
result is correct either way. Other shapes keep the attention layer.

test_single_key compiles these shapes and compares with PyTorch, including a
query and key whose product overflows FP16, a hidden key, and efficient and
cuDNN attention with a bias under require_full_compilation=True. Each case
fails without this change. test_short_keys_validator checks that the validator
keeps nearby shapes, a head size of 8 with 4 heads in all and an FP32 head size
of 16, and declines an FP32 head size of 15 and FP16 one-row queries with fewer
than 4 heads in all. Two lowering tests check that a float64 attention is
decomposed in float64 with truncate_double, and that an attention read by
as_strided is kept.

Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>
@shoumikhin
shoumikhin force-pushed the single-query-mask-decompose branch from 5cca30d to 93968a2 Compare November 26, 2026 08:24

This branch has not been deployed

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

Labels

cla signed component: api [Python] Issues re: Python API component: conversion Issues re: Conversion stage component: core Issues re: The core compiler component: dynamo Issues relating to the `torch.compile` or `torch._dynamo.export` paths component: lowering Issues re: The lowering / preprocessing passes component: tests Issues re: Tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant