Skip to content

tensorrt.plugin AOT plugins fail at enqueue when the kernel needs more than 48 KiB of dynamic shared memory #5010

Open

Description

@shoumikhin

Description

A kernel registered with @trtp.aot_impl and launched with KernelLaunchParams.shared_mem above 48 KiB (49152 bytes) builds into an engine without error, but every execute_async_v3 fails:

[TRT] [E] Error Code: 2: In enqueue at /_src/runtime/common/pluginUtilsRuntime.cpp:235
[TRT] [E] [pluginV3Runner.cpp::execute::252] Error Code 2: Internal Error (Assertion pluginUtils::isSuccess(status) failed.)

This matches a CUDA launch that skips the opt-in for large dynamic shared memory. On every recent GPU, a kernel can use more than 48 KiB only after cuFuncSetAttribute(func, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, bytes). The same PTX launched directly with cuLaunchKernel fails with CUDA_ERROR_INVALID_VALUE without that call, and works with it.

This matters for Triton kernels, which the aot_impl docstring uses as its example (launch_params.shared_mem = compiled_kernel.metadata.shared). Pipelined Triton kernels routinely need 64 to 150 KiB. Torch-TensorRT's AOT Triton plugin path (a triton_op wrapped as a TensorRT plugin) hits this as soon as the kernel is tuned for speed.

Environment

TensorRT 11.4.0.106, NVIDIA H100 (sm_90), driver 580.126.09, Linux x86_64, Python 3.12, cuda-python 13.5.0, torch 2.15.0 (only used for device buffers).

Steps to reproduce

repro_aot_plugin_smem.py (below) uses a 25-line PTX kernel that writes into the last 4 bytes of its dynamic shared memory and returns x + dynamic_smem_size.

python repro_aot_plugin_smem.py trt 49152        # works
python repro_aot_plugin_smem.py trt 49168        # fails
python repro_aot_plugin_smem.py cuda 49168       # direct launch, no opt-in: CUDA_ERROR_INVALID_VALUE
python repro_aot_plugin_smem.py cuda-optin 49168 # direct launch with cuFuncSetAttribute: works

Results:

shared_mem   direct, no opt-in        direct, with opt-in   TensorRT AOT plugin
16384        ok                       ok                    ok
49152        ok                       ok                    ok
49168        CUDA_ERROR_INVALID_VALUE ok                    execute_async_v3 False
65536        CUDA_ERROR_INVALID_VALUE ok                    execute_async_v3 False

Expected

The plugin runs with the shared memory it asked for, up to the device's opt-in limit (CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN, for example 227 KiB on H100). If the request is above that limit, a clear error at build time.

Suggested fix

After loading the AOT kernel, call cuFuncSetAttribute(func, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shared_mem) when shared_mem is above 48 KiB, before cuLaunchKernel.

repro_aot_plugin_smem.py
"""TensorRT AOT plugins cannot launch a kernel with more than 48 KiB of dynamic shared memory.

The kernel below writes its input into the last 4 bytes of its dynamic shared memory, reads it
back, and adds the dynamic shared memory size it was launched with. So out = x + shared_mem.

    python repro_aot_plugin_smem.py trt <bytes>     # through a TensorRT AOT plugin (tensorrt.plugin)
    python repro_aot_plugin_smem.py cuda <bytes>    # same PTX launched directly, no opt-in
    python repro_aot_plugin_smem.py cuda-optin <bytes>  # same, after cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE_BYTES)

Requires: tensorrt (with tensorrt.plugin), torch (only for device buffers), cuda-python.
"""
import sys
from typing import Tuple, Union

import torch

PTX = r"""
.version 8.0
.target sm_80
.address_size 64
.extern .shared .align 16 .b8 smem[];
.visible .entry smem_probe(.param .u64 in_ptr, .param .u64 out_ptr)
{
    .reg .b32 %r<4>;
    .reg .b64 %rd<3>;
    .reg .f32 %f<4>;
    ld.param.u64 %rd1, [in_ptr];
    ld.param.u64 %rd2, [out_ptr];
    cvta.to.global.u64 %rd1, %rd1;
    cvta.to.global.u64 %rd2, %rd2;
    mov.u32 %r1, %dynamic_smem_size;
    ld.global.f32 %f1, [%rd1];
    sub.u32 %r2, %r1, 4;
    mov.u32 %r3, smem;
    add.u32 %r3, %r3, %r2;
    st.shared.f32 [%r3], %f1;
    bar.sync 0;
    ld.shared.f32 %f2, [%r3];
    cvt.rn.f32.u32 %f3, %r1;
    add.f32 %f2, %f2, %f3;
    st.global.f32 [%rd2], %f2;
    ret;
}
"""

mode, smem = sys.argv[1], int(sys.argv[2])
stream = torch.cuda.Stream()
x = torch.full((1,), 7.0, device="cuda")
y = torch.zeros(1, device="cuda")

if mode == "trt":
    import tensorrt as trt
    import tensorrt.plugin as trtp

    @trtp.register("repro::smem_probe")
    def _desc(inp: trtp.TensorDesc) -> Tuple[trtp.TensorDesc]:
        return inp.like()

    @trtp.aot_impl("repro::smem_probe")
    def _aot(
        inp: trtp.TensorDesc, outputs: Tuple[trtp.TensorDesc], tactic: int
    ) -> Tuple[Union[str, bytes], Union[str, bytes], trtp.KernelLaunchParams, trtp.SymExprs]:
        params = trtp.KernelLaunchParams(grid_x=1, block_x=1, shared_mem=smem)
        return "smem_probe", PTX, params, trtp.SymIntExprs(0)

    logger = trt.Logger(trt.Logger.WARNING)
    builder = trt.Builder(logger)
    network = builder.create_network(0)
    inp = network.add_input("x", trt.float32, (1,))
    layer = network.add_plugin(trtp.op.repro.smem_probe(inp), aot=True)
    layer.get_output(0).name = "y"
    network.mark_output(layer.get_output(0))
    plan = builder.build_serialized_network(network, builder.create_builder_config())
    assert plan is not None, "engine build failed"
    engine = trt.Runtime(logger).deserialize_cuda_engine(plan)
    context = engine.create_execution_context()
    context.set_tensor_address("x", x.data_ptr())
    context.set_tensor_address("y", y.data_ptr())
    ok = context.execute_async_v3(stream.cuda_stream)
    stream.synchronize()
    print(f"trt shared_mem={smem}: execute_async_v3 returned {ok}, y={y.item()} (expected {7.0 + smem})")
else:
    from cuda.bindings import driver as cu

    torch.cuda.synchronize()  # makes torch's primary context current
    err, module = cu.cuModuleLoadData(PTX.encode() + b"\0")
    assert err == cu.CUresult.CUDA_SUCCESS, err
    err, func = cu.cuModuleGetFunction(module, b"smem_probe")
    assert err == cu.CUresult.CUDA_SUCCESS, err
    if mode == "cuda-optin":
        (err,) = cu.cuFuncSetAttribute(
            func, cu.CUfunction_attribute.CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, smem
        )
        assert err == cu.CUresult.CUDA_SUCCESS, err
    import ctypes

    a, b = ctypes.c_uint64(x.data_ptr()), ctypes.c_uint64(y.data_ptr())
    args = (ctypes.c_void_p * 2)(ctypes.addressof(a), ctypes.addressof(b))
    (err,) = cu.cuLaunchKernel(func, 1, 1, 1, 1, 1, 1, smem, 0, ctypes.addressof(args), 0)
    torch.cuda.synchronize()
    print(f"{mode} shared_mem={smem}: cuLaunchKernel -> {err.name}, y={y.item()} (expected {7.0 + smem})")

Activity

  1. shoumikhin commented on Nov 13, 2026

    @shoumikhin
    ContributorAuthor

    Two more launch features that Triton kernels on newer GPUs need, in the same AOT plugin path:

    1. Tensor memory (sm_100, sm_103, sm_110). Triton compiles tl.dot to tcgen05 instructions on these GPUs, and the kernel reports tmem_size (for example 128 columns). The kernel allocates and frees the tensor memory itself. Torch-TensorRT refuses these kernels today, so plugin kernels fall back to older mma.sync instructions on these GPUs. Could you confirm that TensorRT can run a plugin kernel that allocates tensor memory inside the kernel, next to TensorRT's own kernels on the same SM? If that needs a reservation or a launch attribute, could KernelLaunchParams get one?

    2. Thread block clusters (num_ctas > 1). These need cudaLaunchKernelEx with a cluster attribute. Could KernelLaunchParams take optional cluster dimensions?

    Where we hit it: a grouped GEMM plugin for mixture-of-experts layers. It runs, but only with the older instructions on these GPUs.

    Together, these would let Triton plugin kernels on these GPUs use the same newer instructions they use outside TensorRT, instead of falling back to mma.sync.

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