AOT tensorrt.plugin reloads plugin PTX via cuModuleLoadData on every enqueue in dynamic-shape engines

Description

When an AOT Python plugin (defined via @tensorrt.plugin.aot_impl) is used in a dynamic-shape engine, TensorRT appears to reload the plugin’s PTX module on every inference, rather than loading it once and caching it. The issue does not happen in a static shaped engine.

Environment

TensorRT Version: 10.12.0.36
GPU Type: L4
Nvidia Driver Version: 570.211.01
CUDA Version: 12.6
CUDNN Version: 9.5.1
Operating System + Version: Linux-6.8.0-1052-aws-x86_64-with-glibc2.39
Python Version (if applicable): 3.10.7
TensorFlow Version (if applicable): N/A
PyTorch Version (if applicable): 2.6.0
Baremetal or Container (if container which image + tag): Container

Relevant Files

"""Repro: a TensorRT AOT (tensorrt.plugin) engine reloads each plugin's PTX via cuModuleLoadData on
every onShapeChange -- i.e. once per plugin layer per enqueue in a DYNAMIC-shape engine (a static
engine loads once; a C++ IPluginV3 never reloads). Builds 3 `affine` layers = (x+1)*2+2 and runs
N enqueues. 

Profile:
    nsys profile --trace=cuda -o /tmp/r python scriptname.py
    nsys stats --report cuda_api_sum /tmp/r.nsys-rep | grep cuModuleLoadData   

When setting DYNAMIC=1, the number of cuModuleLoadDatas is expected to be 3*N
When setting DYNAMIC=0, the number of cuModueLoadDatas is expected to be 3

Env Vars to set: 
NVCC (nvcc path),
N_ITERS (default 200), 
DYNAMIC (default 1; 0 => static shapes).
"""

import os
import platform
import struct
import subprocess
import tempfile
from typing import Tuple, Union

import tensorrt as trt
import tensorrt.plugin as trtp
import torch
from onnx import TensorProto, helper


def _env_report() -> None:
    def _sh(cmd):
        try:
            return subprocess.run(cmd, capture_output=True, text=True, check=True).stdout.strip()
        except Exception:  # noqa: BLE001
            return ""

    smi = _sh(["nvidia-smi", "--query-gpu=name,driver_version", "--format=csv,noheader"])
    gpu, driver = ((smi.split(", ") + ["", ""])[:2]) if smi else ("", "")
    cudnn = torch.backends.cudnn.version()
    cudnn = f"{cudnn // 10000}.{(cudnn % 10000) // 100}.{cudnn % 100}" if cudnn else "N/A"
    try:
        import tensorflow as tf  # noqa: PLC0415

        tfv = tf.__version__
    except Exception:  # noqa: BLE001
        tfv = "N/A"
    container = "Container" if os.path.exists("/.dockerenv") else "Baremetal"
    print(
        f"**TensorRT Version**: {trt.__version__}\n"
        f"**GPU Type**: {gpu.removeprefix('NVIDIA ')}\n"
        f"**Nvidia Driver Version**: {driver}\n"
        f"**CUDA Version**: {torch.version.cuda}\n"
        f"**CUDNN Version**: {cudnn}\n"
        f"**Operating System + Version**: {platform.platform()}\n"
        f"**Python Version (if applicable)**: {platform.python_version()}\n"
        f"**TensorFlow Version (if applicable)**: {tfv}\n"
        f"**PyTorch Version (if applicable)**: {torch.__version__}\n"
        f"**Baremetal or Container (if container which image + tag)**: {container}"
    )

_ID, _BLK = "repro::affine", 256
_CU = ('extern "C" __global__ void affine(const float* x, int n, int ab, int bb, float* y) {'
       ' int i = blockIdx.x*blockDim.x + threadIdx.x;'
       ' if (i < n) y[i] = __int_as_float(ab)*x[i] + __int_as_float(bb); }')
_bits = lambda v: struct.unpack("<i", struct.pack("<f", v))[0]  # noqa: E731


def _ptx() -> str:
    with tempfile.TemporaryDirectory() as d:
        cu, p = os.path.join(d, "a.cu"), os.path.join(d, "a.ptx")
        open(cu, "w").write(_CU)
        subprocess.run([os.environ.get("NVCC", "nvcc"), "--ptx", "-arch=compute_86", cu, "-o", p], check=True)
        return open(p).read()


_PTX = _ptx()


@trtp.register(_ID)
def _(x: trtp.TensorDesc, a: float, b: float) -> trtp.TensorDesc:
    return trtp.TensorDesc(shape_expr=x.shape_expr, dtype=x.dtype)


@trtp.aot_impl(_ID)
def _(x: trtp.TensorDesc, a: float, b: float, outputs, tactic) -> Tuple[Union[str, bytes], Union[str, bytes], trtp.KernelLaunchParams, trtp.SymIntExprs]:
    lp = trtp.KernelLaunchParams()
    lp.grid_x, lp.block_x, lp.shared_mem = trtp.cdiv(x.shape_expr[0], _BLK), _BLK, 0
    ea = trtp.SymIntExprs(3)
    ea[0], ea[1], ea[2] = trtp.SymInt32(x.shape_expr[0]), trtp.SymInt32(_bits(a)), trtp.SymInt32(_bits(b))
    return "affine", _PTX, lp, ea


def _engine(nmax: int, dyn: bool) -> bytes:
    dim = [-1] if dyn else [nmax]
    io = ([helper.make_tensor_value_info("X", TensorProto.FLOAT, dim)],
          [helper.make_tensor_value_info("Y", TensorProto.FLOAT, dim)])
    nodes = [helper.make_node("affine", [i], [o], domain="repro", a=a, b=b)
             for i, o, a, b in [("X", "h1", 1.0, 1.0), ("h1", "h2", 2.0, 0.0), ("h2", "Y", 1.0, 2.0)]]
    model = helper.make_model(helper.make_graph(nodes, "g", *io),
                              opset_imports=[helper.make_opsetid("", 17), helper.make_opsetid("repro", 1)])
    lg = trt.Logger(trt.Logger.WARNING)
    b = trt.Builder(lg)
    net = b.create_network((1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED))
                           | (1 << int(trt.NetworkDefinitionCreationFlag.PREFER_AOT_PYTHON_PLUGINS)))
    assert trt.OnnxParser(net, lg).parse(model.SerializeToString())
    cfg = b.create_builder_config()
    if dyn:
        prof = b.create_optimization_profile()
        prof.set_shape("X", (1,), (nmax // 2,), (nmax,))
        cfg.add_optimization_profile(prof)
    return bytes(b.build_serialized_network(net, cfg))


def main():
    n, niter, dyn = 1 << 16, int(os.environ.get("N_ITERS", "200")), os.environ.get("DYNAMIC", "1") == "1"
    _env_report()
    print(f"[REPRO] 3 affine layers = (x+1)*2+2 | N_ITERS={niter} dynamic={dyn}")

    ctx = trt.Runtime(trt.Logger(trt.Logger.WARNING)).deserialize_cuda_engine(_engine(n, dyn)).create_execution_context()
    x, y = torch.arange(n, device="cuda", dtype=torch.float32), torch.empty(n, device="cuda", dtype=torch.float32)
    ctx.set_tensor_address("X", x.data_ptr())
    ctx.set_tensor_address("Y", y.data_ptr())
    stream, sizes = torch.cuda.current_stream().cuda_stream, ([n, n // 2] if dyn else [n])
    for i in range(niter):
        if dyn:
            ctx.set_input_shape("X", (sizes[i % len(sizes)],))
        assert ctx.execute_async_v3(stream)
    torch.cuda.synchronize()
    print(f"[REPRO] output == 2x+4: {torch.allclose(y, x * 2 + 4)}")


if __name__ == "__main__":
    main()
![Screenshot 2026-07-13 at 11.25.40 AM|690x117](upload://nyJWNub21Slrc0mB00Z6mMNUIHI.png)

Steps To Reproduce

Set the following environment variables and run the python script with nsys:

  • NVCC, path to nvcc used to create the PTX for the kernel
  • N_ITERS (default 200), how many iterations to profile enqueue for
  • DYNAMIC (default 1; 0 => static shapes), whether or not to create a dynamic shape engine

Hi @wxu5 ,Thanks for posting a runnable repro. The nsys counts and your two controls narrow this to the AOT Python plugin path: the dynamic run produces 3*N calls to cuModuleLoadData, while the static engine and your C++ IPluginV3 stay at three.

Those controls isolate the observed behavior to the AOT Python case. The current repro still combines two actions: it calls set_input_shape and then enqueues on every iteration. The trace therefore does not separate “reload after a shape change” from “reload on every enqueue in a dynamic engine.”

1. Run the missing control

Keep the dynamic profile, set one shape before the loop, then enqueue repeatedly:

ctx.set_input_shape("X", (n,))
for _ in range(niter):
    assert ctx.execute_async_v3(stream)

If this stays at three loads, the reload is tied to shape changes. If it remains at 3*N, it is happening on every enqueue for a dynamic engine.

2. Reuse one context per recurring shape

If the first control stays at three loads and your serving shapes come from a small fixed set, keep one initialized execution context per shape and stop calling set_input_shape in the steady-state path. Please validate the load count with the first control before adopting this.

3. Use the controls that already avoid the reload

For a bounded shape set, static engines avoid the behavior in your trace. Your C++ IPluginV3 control also avoids it. Both cost more engineering or deployment complexity, but they are the two paths your repro has already shown to work.

Could you run the first control and share whether it reports three loads or 3*N? I will take the repro and that result to the plugin owners, then post the status here once it is logged.

Thanks, Atharva

confirmed its related to shape changes