TensorRT icon indicating copy to clipboard operation
TensorRT copied to clipboard

🐛 [Bug] FP16 Dynamo compile produces incorrect results for batched attention when query originates from an expanded tensor

Open unilin-pietergobin opened this issue 1 month ago • 4 comments

Bug Description

Minimal repro: torch_tensorrt.dynamo.compile() (FP16) produces numerically wrong results for a two-matmul attention-style pattern when the "query" side originates from a batch-broadcast tensor (expand from batch size 1 -> B), even though the intermediate softmax(Q @ K^T) tensor is itself already computed correctly and is NOT broadcast (it varies per batch element because K/V are real, independently-random per-sample tensors).

Expected: TRT output matches eager output (up to ordinary FP16 rounding). Actual: TRT output diverges sharply (cosine similarity ~0.2-0.4) starting exactly at the second matmul (attn_weights @ V), even though everything up to and including the softmax matches eager exactly.

Root cause (as far as we can tell without access to TRT internals): TensorRT appears to propagate a "this tensor originated from a batch-broadcast" tag/lineage through intervening ops (Linear, reshape, permute, matmul, softmax) that should have invalidated it (since mixing in genuinely per-sample K data makes the result vary per batch element), and then mis-applies a broadcast-batched-GEMM optimization at the second matmul, effectively reading a single shared operand instead of a true per-batch one.

Confirms this is specifically about op FUSION / lineage tracking, not a one-off kernel bug:

  • Compiling expand -> clone in complete isolation (no downstream consumer) is correct.
  • Forcing clone out of the TRT engine via torch_executed_ops (so the expand->clone materialization happens in eager PyTorch, at a partition boundary) fixes it.
  • Inserting a .clone() immediately before the second matmul, while staying in a SINGLE TRT engine, does NOT fix it (the builder eliminates the redundant copy and the stale tag survives).
  • Inserting a genuine, non-eliminable elementwise op (x + 0.0) at that same point, in the same single engine, DOES fix it.

To Reproduce

Minimal reproducible sample

import torch
import torch_tensorrt
from torch import nn

DEVICE = "cuda"
B = 16          # batch size
T = 6           # "query" tokens (small, broadcast-origin)
N = 1854        # "key/value" tokens (real per-sample)
C = 768         # embedding dim
HEADS = 12
HEAD_DIM = C // HEADS
SCALE = HEAD_DIM**-0.5


class BroadcastAttention(nn.Module):
    """A minimal two-matmul attention block: a single learned "prototype"
    token, broadcast across the batch dimension, attending over a real
    per-sample batch of keys/values.
    """

    def __init__(self):
        super().__init__()
        self.token = nn.Parameter(torch.randn(T, C, dtype=torch.half))
        self.q = nn.Linear(C, C, dtype=torch.half)
        self.kv = nn.Linear(C, C * 2, dtype=torch.half)

    def forward(self, y: torch.Tensor, b: int) -> torch.Tensor:
        # Broadcast the single learned token across the batch dimension.
        # (`.repeat((b, 1, 1))` decomposes to this same `expand` + `clone`
        # pair under torch.export, so it reproduces identically.)
        x = self.token.unsqueeze(0).expand(b, -1, -1)

        q = self.q(x).reshape(b, T, HEADS, HEAD_DIM).permute(0, 2, 1, 3)
        kv = self.kv(y).reshape(b, N, 2, HEADS, HEAD_DIM).permute(2, 0, 3, 1, 4)
        k, v = kv[0], kv[1]

        attn = (q @ k.transpose(-2, -1)) * SCALE
        attn = attn.softmax(dim=-1)
        # <-- everything up to here matches eager exactly -->
        out = attn @ v  # <-- this matmul is where TRT's output diverges
        return out.transpose(1, 2).reshape(b, T, C)


def cosine_sim(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    return torch.nn.functional.cosine_similarity(
        a.float().flatten(1), b.float().flatten(1), dim=1
    )


def main():
    torch.manual_seed(0)
    model = BroadcastAttention().eval().to(DEVICE)
    y = torch.randn(B, N, C, dtype=torch.half, device=DEVICE)

    with torch.no_grad():
        eager_out = model(y, B)

    with torch.no_grad():
        exp_program = torch.export.export(model, (y, B))
        trt_module = torch_tensorrt.dynamo.compile(
            exp_program,
            [y, B],
            enabled_precisions={torch.float16},
            use_explicit_typing=False,
            min_block_size=1,
        )
        trt_out = trt_module(y, B)

    diff = (eager_out.float() - trt_out.float()).abs()
    cos = cosine_sim(eager_out, trt_out)

    print(f"max abs diff:        {diff.max().item():.6f}")
    print(f"mean abs diff:       {diff.mean().item():.6f}")
    print(f"cosine sim min/mean: {cos.min().item():.6f} / {cos.mean().item():.6f}")
    print()
    print("Expected: max diff ~1e-3, cosine sim ~1.0 (ordinary FP16 noise)")
    print("Actual:   max diff and cosine sim far outside that range -> BUG")


if __name__ == "__main__":
    main()

Expected behavior

Cosine similarity to be in 0.99 range between eager execution and tensorrt compiled model.

Environment

Build information about Torch-TensorRT can be found by turning on debug messages

Tested with: torch 2.11.0+cu130 torch_tensorrt 2.11.0 tensorrt 10.15.1.29 CUDA 13.0 GPU NVIDIA RTX PRO 5000 Blackwell

Observed output on the above configuration: max abs diff: 0.111542 mean abs diff: 0.023823 cosine sim min/mean: 0.097519 / 0.120745 (expected ~1e-3 / ~1.0 for ordinary FP16 rounding noise)

unilin-pietergobin avatar Nov 03 '26 14:11 unilin-pietergobin

@unilin-pietergobin can you try using the setting use_fp32_acc to match pytorch numerics? By default TRT uses fp16 accumulate.

narendasan avatar Nov 06 '26 00:11 narendasan

Hi @narendasan I will give it a go later, to me the difference in cosine similarity felt more like it actually is fusing operations in the wrong order. I managed to get cos similarity up by simply adding a attn = attn + 0.0 right before doing out = attn @ v

unilin-pietergobin avatar Nov 06 '26 12:11 unilin-pietergobin

@narendasan I tested it with the suggested fix, still seeing the same issue. just to be sure I tested it with explicit typing, that also yielded the same issue.

pietergobin avatar Nov 06 '26 15:11 pietergobin

Hi team, I can reproduce this with torch_tensorrt 2.11 on TensorRT 10.15/10.16, and it's a TensorRT bug rather than a Torch-TensorRT one. Because q comes from a parameter, the query branch is constant-folded, and TensorRT 10.x through 11.3 produces wrong results when a constant feeds the matmul → softmax → matmul pattern.

A plain TensorRT network with a constant Q reproduces it without Torch-TensorRT, and it doesn't depend on Q being broadcast, a distinct constant per batch element also fails, while the same Q as a runtime input is fine. That's also why use_fp32_acc has no effect.

It's fixed in TensorRT 11.4, your script gives cosine similarity 0.999999 there. Please upgrade to torch_tensorrt 2.15, which uses TensorRT 11.4. If you have to stay on an older version, your attn + 0.0 workaround before attn @ v is a valid fix.

micwill755 avatar Nov 16 '26 22:11 micwill755