Skip to content

TensorRT masked attention silently ignores the mask in float16 with a single query and 513+ keys #5011

Open

Description

@shoumikhin

What happens

An IAttention layer (add_attention_v2) with a mask gives wrong results when all of these hold:

  • the data type is float16
  • the query length is 1 (decode step, cross-attention from one token)
  • the key length is large enough that TensorRT picks a _gemv_mha_v2 kernel (key length 513 and above in my runs;
    512 and below picks _gemv_mha_v1 and is correct)

The output then matches attention computed WITHOUT the mask, to float16 precision. The mask is not
applied at all. Both a bool mask and an additive float mask (0 / -inf) are affected.

The same network is correct in bfloat16 and float32 (both use _gemv_mha_v1), and correct in float16
with 2 or more queries (_gemm_mha_v2). Input scale does not matter (randn x 0.1, x 1, x 3 all fail
the same way), and odd or even key length does not matter.

Reproduction

repro_fp16_q1_mask.py (below): one add_attention_v2 layer in a strongly typed network,
shape (1, 16, Q, 64) x (1, 16, 3473, 64), a mask hiding about half of the keys, compared with a float32
PyTorch reference computed with and without the mask. PyTorch is only used for buffers and the reference.

Output on H100 (sm_90), TensorRT 11.4.0.106:

TensorRT 11.4.0.106 NVIDIA H100
fp16 Q=1 bool  err_vs_masked=0.65714 err_vs_unmasked=0.00029 kernel=_gemv_mha_v2_0xb2e3b9827
fp16 Q=1 float err_vs_masked=0.65714 err_vs_unmasked=0.00029 kernel=_gemv_mha_v2_0xb89442969
bf16 Q=1 bool  err_vs_masked=0.00512 err_vs_unmasked=0.92433 kernel=_gemv_mha_v1_0xbf58b9ded
bf16 Q=1 float err_vs_masked=0.00512 err_vs_unmasked=0.92433 kernel=_gemv_mha_v1_0xbf58b9ded
fp32 Q=1 bool  err_vs_masked=0.00000 err_vs_unmasked=0.92447 kernel=_gemv_mha_v1_0xc30ad9f7e
fp32 Q=1 float err_vs_masked=0.00000 err_vs_unmasked=0.92447 kernel=_gemv_mha_v1_0xc30ad9f7e
fp16 Q=2 bool  err_vs_masked=0.00247 err_vs_unmasked=0.98547 kernel=_gemm_mha_v2_0x078186ff2
fp16 Q=2 float err_vs_masked=0.00247 err_vs_unmasked=0.98547 kernel=_gemm_mha_v2_0x078186ff2

err_vs_unmasked near 3e-4 for float16 Q=1 means the result is exactly unmasked attention.

Setting decomposable = True does not help (TensorRT still picks _gemv_mha_v2), and batch 2 fails the
same way.

A smaller, separate difference: with one query and a fully masked row, _gemv_mha_v1 (bfloat16, or float16
with short keys) returns NaN, _gemm_mha_v2 (2+ queries) returns 0, and _gemv_mha_v2 returns the
unmasked average.

Impact

Any model that runs masked attention with a single query in float16 silently gets wrong numbers, with
no warning: for example a decoder step with padding masks, or cross-attention from one token to a
long padded context. The same happens through Torch-TensorRT when compiling
F.scaled_dot_product_attention(q, k, v, attn_mask=mask) in float16.

Environment

  • TensorRT 11.4.0.106 (Python wheel), CUDA 13.2 wheels, driver 580
  • GPU: NVIDIA H100 (sm_90)
  • Not tested on other GPUs yet.

Expected

The masked result (error against the masked float32 reference around 1e-3, as bfloat16 gives), or a
fallback to a kernel that supports the mask.

repro_fp16_q1_mask.py
"""IAttention with one query in float16 ignores its mask (TensorRT 11.4).

One add_attention_v2 layer, strongly typed network, shape (1, 16, Q, 64) x (1, 16, KV, 64), with a bool or
float mask that hides about half of the keys. The output is compared with a float32 reference computed with
the mask and without it. Torch is used only for buffers and the reference.

Expected: error vs the masked reference is small (about 1e-3) for every row.
Actual on H100: float16 with Q=1 matches the UNMASKED reference instead; bfloat16 and float32 are correct,
and float16 with Q=2 is correct.
"""
import json, math
import tensorrt as trt
import torch

H, D, KV = 16, 64, 3473
logger = trt.Logger(trt.Logger.ERROR)


def check(dtype, Q, mask_kind):
    tdt, trt_dt = {"fp16": (torch.float16, trt.DataType.HALF), "bf16": (torch.bfloat16, trt.DataType.BF16),
                   "fp32": (torch.float32, trt.DataType.FLOAT)}[dtype]
    torch.manual_seed(0)
    mask = torch.rand(1, 1, Q, KV) < 0.5
    mask[..., 0] = True
    builder = trt.Builder(logger)
    net = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED))
    q = net.add_input("q", trt_dt, (1, H, Q, D))
    k = net.add_input("k", trt_dt, (1, H, KV, D))
    v = net.add_input("v", trt_dt, (1, H, KV, D))
    scale = torch.full((1, 1, 1, 1), 1.0 / math.sqrt(D), dtype=tdt)
    sq = net.add_elementwise(q, net.add_constant(scale.shape, trt.Weights(trt_dt, scale.data_ptr(), 1)).get_output(0),
                             trt.ElementWiseOperation.PROD).get_output(0)
    attn = net.add_attention_v2(sq, k, v, trt.AttentionNormalizationOp.SOFTMAX, trt.CausalMaskKind.NONE)
    if mask_kind == "bool":
        mw = mask.numpy()
        attn.mask = net.add_constant(mw.shape, trt.Weights(mw)).get_output(0)
    else:
        mw = torch.where(mask, 0.0, float("-inf")).to(tdt).contiguous()
        attn.mask = net.add_constant(tuple(mw.shape), trt.Weights(trt_dt, mw.data_ptr(), mw.numel())).get_output(0)
    out = attn.get_output(0)
    out.name = "out"
    net.mark_output(out)
    cfg = builder.create_builder_config()
    cfg.profiling_verbosity = trt.ProfilingVerbosity.DETAILED
    engine = trt.Runtime(logger).deserialize_cuda_engine(builder.build_serialized_network(net, cfg))
    info = json.loads(engine.create_engine_inspector().get_engine_information(trt.LayerInformationFormat.JSON))
    kernels = [l["TacticName"] for l in info["Layers"] if "mha" in l.get("TacticName", "")]
    ctx = engine.create_execution_context()
    qt, kt, vt = (torch.randn(1, H, n, D, device="cuda").to(tdt) for n in (Q, KV, KV))
    ot = torch.empty(1, H, Q, D, device="cuda", dtype=tdt)
    for name, t in (("q", qt), ("k", kt), ("v", vt), ("out", ot)):
        ctx.set_tensor_address(name, t.data_ptr())
    ctx.execute_async_v3(torch.cuda.current_stream().cuda_stream)
    torch.cuda.synchronize()
    sdpa = torch.nn.functional.scaled_dot_product_attention
    masked = sdpa(qt.float(), kt.float(), vt.float(), attn_mask=mask.cuda())
    unmasked = sdpa(qt.float(), kt.float(), vt.float())
    err = lambda r: ((ot.float() - r).norm() / r.norm()).item()
    print(f"{dtype} Q={Q} {mask_kind:5s} err_vs_masked={err(masked):.5f} err_vs_unmasked={err(unmasked):.5f} "
          f"kernel={kernels[0][:24] if kernels else '?'}")


print("TensorRT", trt.__version__, torch.cuda.get_device_name())
for dtype in ("fp16", "bf16", "fp32"):
    for mask_kind in ("bool", "float"):
        check(dtype, 1, mask_kind)
for mask_kind in ("bool", "float"):
    check("fp16", 2, mask_kind)

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