Skip to content

Dynamic sequence length: attention and split fail to build in 2.15 when the length is a symbol #5037

In progress

Description

@shoumikhin

What is wrong

We export a transformer whose text length is a dynamic dimension (torch.export.Dim). torch.export traces it. Torch-TensorRT 2.15 cannot build it. Two small patterns fail:

  1. Attention where K is scaled by a table and V is not. K is multiplied by a table that is sliced from a dynamic-length tensor to a static size. TensorRT cannot prove the broadcast dimension that comes out equals V's, so the attention layer rejects K and V: Key and Value must have the same shape (from attentionInputLayer.cpp), reported as Could not get tensor shape.
  2. A fixed-size slice at a symbolic offset, then a split. x.narrow(1, n, 12).split([8, 4], 1) with n symbolic fails in the converter: AssertionError: Can't chunk on dynamic shape dimension! The split axis has a static size of 12, so it can be chunked.

What this blocks

The LeRobot exports in pytorch/executorch#24353 use a fixed, padded text length, so none of them fails because of this.
It costs speed: every call runs attention over the padding.
A fix lets one engine handle every text length and skip the padding.

Repro

import torch, torch.nn.functional as F, torch_tensorrt
from torch.export import Dim

dev = "cuda"

class KVLength(torch.nn.Module):
    def forward(self, x, ids):
        table = torch.cat([torch.zeros(4, device=dev), ids.float() + 7, torch.ones(8, device=dev)])[None, :, None]
        table = table[:, : x.shape[1]]
        for _ in range(2):
            q = (x * table).transpose(0, 1)[None]
            k = (x * table).transpose(0, 1)[None]
            v = x.transpose(0, 1)[None]
            x = x + F.scaled_dot_product_attention(q, k, v)[0].transpose(0, 1)
        return x

class SplitAfterNarrow(torch.nn.Module):
    def forward(self, x):
        a, b = x.narrow(1, x.shape[1] - 12, 12).split([8, 4], dim=1)
        return a.sum() + b.sum()

n = Dim("n", min=2, max=28)
cases = {
    "kv_length": (KVLength(), lambda m: (torch.randn(m + 12, 1, 16, device=dev), torch.arange(1, m + 1, device=dev)),
                  ({0: n + 12}, {0: n})),
    "split_after_narrow": (SplitAfterNarrow(), lambda m: (torch.randn(1, m + 12, 4, device=dev),),
                           ({1: Dim("s", min=14, max=40)},)),
}
for name, (module, make, dyn) in cases.items():
    try:
        ep = torch.export.export(module, make(20), dynamic_shapes=dyn, strict=False)
        trt = torch_tensorrt.dynamo.compile(ep, arg_inputs=make(20), min_block_size=1)
        for m in (20, 5):
            trt(*make(m))
        print(name, "OK")
    except Exception as e:
        print(name, "FAILS:", type(e).__name__, str(e)[:200])

Actual

ERROR:torch_tensorrt [TensorRT Conversion Context]:ITensor::getDimensions: Error Code 3: API Usage Error ((Unnamed Layer* 61) [AttentionInput]: Key and Value must have the same shape In validate at /_src/optimizer/api/layers/attentionInputLayer.cpp:171)
kv_length FAILS: RuntimeError Could not get tensor shape.
While executing %select : [num_users=1] = call_function[target=torch.ops.aten.select.int](args = (%scaled_dot_product_attention, 0, 0), kwargs = {})
split_after_narrow FAILS: AssertionError Can't chunk on dynamic shape dimension!
While executing %split_with_sizes : [num_users=2] = call_function[target=torch.ops.aten.split_with_sizes.default](args = (%slice_1, [8, 4], 1), kwargs = {})

Expected

Both build and match PyTorch at lengths 20 and 5.

Versions

torch 2.15.0 (CUDA 13.2), Torch-TensorRT 2.15.0, TensorRT 11.4.0.106, H100, driver 580.126.09.

Related: #3347 (same assertion, split along a dynamic axis).

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

Metadata

Metadata

Assignees

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