Repository navigation
Description
Is your feature request related to a problem? Please describe.
Many LLMs use grouped-query attention (GQA): several query heads share one key/value head. In PyTorch this is scaled_dot_product_attention(..., enable_gqa=True), with key and value holding fewer heads than query.
Torch-TensorRT passes these tensors to TensorRT's attention layer as they are. TensorRT then copies the keys and values to all query heads before its attention kernel, on every call. During decoding the query is 1 token, but the keys and values are the whole KV cache, so each step copies the full cache many times over. With 32 query heads and 2 KV heads, that is 16 copies of the cache per layer per token.
Measured with repro_gqa.py below (one decode step, 32 query heads, 2 KV heads, head size 128, a 16384-slot bf16 cache with 4096 valid positions):
enable_gqa=True 0.480 ms per call, max abs diff vs PyTorch 0.0005
query heads folded into rows 0.229 ms per call, max abs diff vs PyTorch 0.0005
In a profile of a 30B model with this head layout (52 layers), the copy kernels before the attention kernel took 9.6 ms of a 59.7 ms bf16 decode step on an A100 (about 16%), and about 1.2 ms per layer on a Jetson Thor.
Describe the solution you'd like
At decode (a short query), fold each group's query heads into query rows before the attention layer:
# q: [B, Hq, L, D], k/v: [B, Hkv, S, D], G = Hq // Hkv
out = sdpa(q.reshape(B, Hkv, G * L, D), k, v, mask_broadcast_to_rows)
out = out.reshape(B, Hq, L, D)This gives the same result and reads the cache once per KV head. It needs care in two places:
- The mask has to be expanded or broadcast to the new rows, and a causal mask has to be built per original row, not per folded row.
- For long queries (prefill), folding multiplies the query rows by G, and TensorRT's attention scratch memory grows with it. In a full-model test, folding at every length added about 18 GiB of GPU memory at 512-token prefill chunks. So the fold should apply only when the query is short (for example 1 or 2 tokens), or only in a decode optimization profile.
A native GQA path in TensorRT's attention layer that reads shared KV heads without copying would solve this without the fold.
Describe alternatives you've considered
- Rewriting the model to fold the heads itself. This works (same answers) but pays the prefill memory cost above, because the model cannot tell decode and prefill apart in one exported graph.
fold_shared_kv_attentionhandles a single shared KV head with static shapes anddecompose_attention=True, not several KV heads with a dynamic query length.- fix(dynamo): avoid TensorRT attention bugs with a masked one-row query or a single key #5074 folds the heads this way, but only for a one-row query with a mask over long keys, where it decomposes the attention to fix a wrong result.
repro_gqa.py
# One decode step of grouped-query attention (32 query heads, 2 key/value heads, 16384 cached keys, bf16).
# With enable_gqa=True, TensorRT copies the cached keys and values to all 32 query heads on every call.
# Folding each group's 16 query heads into 16 query rows gives the same result without the copy.
import time
import torch, torch.nn.functional as F, tensorrt as trt, torch_tensorrt
B, HQ, HKV, D, S = 1, 32, 2, 128, 16384
G = HQ // HKV
class GQA(torch.nn.Module):
def forward(self, q, k, v, mask):
return F.scaled_dot_product_attention(q, k, v, attn_mask=mask, enable_gqa=True)
class Folded(torch.nn.Module):
def forward(self, q, k, v, mask):
out = F.scaled_dot_product_attention(q.reshape(B, HKV, G, D), k, v, attn_mask=mask)
return out.reshape(B, HQ, 1, D)
torch.manual_seed(0)
dt = torch.bfloat16
q = torch.randn(B, HQ, 1, D, device="cuda", dtype=dt)
k = torch.randn(B, HKV, S, D, device="cuda", dtype=dt)
v = torch.randn(B, HKV, S, D, device="cuda", dtype=dt)
mask = torch.zeros(1, 1, 1, S, device="cuda", dtype=torch.bool)
mask[..., :4096] = True # 4096 valid positions in a 16384-slot cache
args = (q, k, v, mask)
def ms(gm):
for _ in range(20): gm(*args)
torch.cuda.synchronize(); t = time.perf_counter()
for _ in range(500): gm(*args)
torch.cuda.synchronize(); return (time.perf_counter() - t) / 500 * 1e3
print("torch_tensorrt", torch_tensorrt.__version__, "tensorrt", trt.__version__, torch.cuda.get_device_name())
ref = GQA()(*args)
for name, mod in (("enable_gqa=True", GQA()), ("query heads folded into rows", Folded())):
gm = torch_tensorrt.dynamo.compile(torch.export.export(mod, args), inputs=list(args), min_block_size=1,
use_explicit_typing=True, use_python_runtime=True)
out = gm(*args)
err = (out.float() - ref.float()).abs().max().item()
print(f"{name:30s} {ms(gm):.3f} ms per call, max abs diff vs PyTorch {err:.4f}")Environment
- Torch-TensorRT: main at 13658aa (Python files) on the 2.15.0+cu132 package
- TensorRT 11.4.0.106, PyTorch 2.15, CUDA 13.2, Linux x86_64, NVIDIA A100 80GB
Activity