Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

Destroying an IExecutionContext invalidates a CUDA stream capture running on another thread in the same context (TensorRT 11.5.0.63) #4971

Backlog

Description

@minamikik

Description

When one thread destroys an IExecutionContext while another thread of the same process is capturing a CUDA
Graph on its own non-blocking stream in the same CUDA context (the primary context), the other thread's capture
is invalidated. The capturing thread then gets false from IExecutionContext::enqueueV3 (with a TensorRT
"Cuda Driver" error) and cudaErrorStreamCaptureInvalidated (901) from cudaStreamEndCapture. The two execution
contexts belong to two different engines and share no stream, event or memory.

The invalidation itself follows the CUDA documentation for context-wide synchronization during a capture,
even in cudaStreamCaptureModeThreadLocal. The problem is that the TensorRT documentation presents one
execution context per thread as the supported way to run inference concurrently, and does not say that
destroying an execution context synchronizes the whole context. An application that captures inference on
one thread while another thread releases an unrelated execution context therefore loses the capture without
any hint in the documentation.

We would like one of the following:

  1. Limit the synchronization in IExecutionContext destruction to the streams and events that this execution
    context used, so that destruction does not affect captures on other streams.
  2. If the context-wide synchronization is required, document it in the IExecutionContext destructor /
    thread-safety section, together with the consequence for stream captures on other threads.

In an earlier investigation with CUPTI (TensorRT 11.4.0.106 and 11.2.1.2, same symptom), the call stack showed
cuCtxSynchronize called from libnvinfer.so.11 during the execution context destruction, returning
CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED (900). We did not collect a CUPTI trace for the runs reported below.

Environment

TensorRT Version: 11.5.0.63 (also reproduced with 11.4.0.106 and 11.2.1.2, installed from PyPI)

NVIDIA GPU: RTX A6000

NVIDIA Driver Version: 621.14 (Windows host driver used by WSL2; CUDA driver API 13050)

CUDA Version: runtime 13.2 (cuda-python / cuda-bindings 13.2.0)

CUDNN Version: not used

Operating System: Ubuntu 26.04.1 LTS on WSL2 (kernel 6.18.58.1-microsoft-standard-WSL2), Windows host

Python Version (if applicable): 3.12.16

Tensorflow Version (if applicable): not used

PyTorch Version (if applicable): not used

Baremetal or Container (if so, version): WSL2, no container

Relevant Files

Model link: no model file is needed. The script below builds two small FP32 networks (one elementwise SUM layer each) with the TensorRT network definition API.

Steps To Reproduce

Commands or scripts:

Dependencies: pip install tensorrt==11.5.0.63 cuda-python==13.2.0 with one GPU visible; this installs the CUDA 13 TensorRT wheels. Each invocation performs one trial in a new process and prints one JSON line.

python trt_destroy_during_capture.py --allocation STATIC --destroy during
python trt_destroy_during_capture.py --allocation USER_MANAGED --destroy during
python trt_destroy_during_capture.py --allocation STATIC --destroy after      # control
python trt_destroy_during_capture.py --allocation USER_MANAGED --destroy after  # control
trt_destroy_during_capture.py
#!/usr/bin/env python3
"""Destroy one TensorRT execution context during another thread's graph capture.

Dependencies: tensorrt (CUDA 13 variant) and cuda-python, with their dependencies.
Example:
  python trt_destroy_during_capture.py --allocation STATIC --destroy during
  python trt_destroy_during_capture.py --allocation USER_MANAGED --destroy after

Each invocation performs one trial and prints one JSON result to stdout.
TensorRT error messages also go to stderr. No model file or plugin is needed.
"""

import argparse
import gc
import importlib.metadata
import json
import math
import platform
import sys
import threading
import traceback
import weakref


def run(args):
    import tensorrt as trt
    from cuda.bindings import driver as drv
    from cuda.bindings import runtime as rt

    result = {
        "tensorrt": trt.__version__,
        "cuda_python": importlib.metadata.version("cuda-python"),
        "cuda_bindings": importlib.metadata.version("cuda-bindings"),
        "python": platform.python_version(),
        "kernel": platform.release(),
        "allocation": args.allocation,
        "destroy": args.destroy,
        "capture_mode": args.mode,
        "begin_capture": None,
        "enqueue_v3": None,
        "end_capture": None,
        "errors": [],
        "trt_errors": [],
        "order": [],
    }

    class Logger(trt.ILogger):
        def __init__(self):
            trt.ILogger.__init__(self)

        def log(self, severity, message):
            if severity <= trt.ILogger.Severity.ERROR:
                entry = {"severity": str(severity), "message": message}
                result["trt_errors"].append(entry)
                print(f"[TensorRT][{severity}] {message}", file=sys.stderr, flush=True)

    def checked(response):
        status, *values = response
        if int(status) != 0:
            raise RuntimeError(f"CUDA call failed: {status}")
        return values[0] if len(values) == 1 else values

    checked(rt.cudaSetDevice(0))
    checked(rt.cudaFree(0))
    primary = checked(drv.cuCtxGetCurrent())
    result["cuda_driver_api"] = checked(drv.cuDriverGetVersion())
    result["cuda_runtime_api"] = checked(rt.cudaRuntimeGetVersion())
    logger = Logger()
    runtime = trt.Runtime(logger)

    def build_engine(name):
        builder = trt.Builder(logger)
        builder.max_threads = args.builder_threads
        network = builder.create_network()
        network.name = name
        tensor = network.add_input("x", trt.float32, (1, 16, 16, 16))
        layer = network.add_elementwise(tensor, tensor, trt.ElementWiseOperation.SUM)
        layer.get_output(0).name = "y"
        network.mark_output(layer.get_output(0))
        config = builder.create_builder_config()
        config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, 64 << 20)
        config.max_aux_streams = 0
        serialized = builder.build_serialized_network(network, config)
        if serialized is None:
            raise RuntimeError("Engine build failed")
        engine = runtime.deserialize_cuda_engine(serialized)
        if engine is None:
            raise RuntimeError("Engine deserialization failed")
        return engine

    engine_a = build_engine("capture_engine")
    engine_b = build_engine("destroy_engine")
    gc.collect()
    strategy = getattr(trt.ExecutionContextAllocationStrategy, args.allocation)
    b_ready = threading.Event()
    capture_open = threading.Event()
    capture_ended = threading.Event()
    destroyed = threading.Event()
    aborted = threading.Event()

    def wait(event):
        if not event.wait(args.wait_timeout):
            raise TimeoutError("Thread rendezvous timed out")
        if aborted.is_set():
            raise RuntimeError("The other thread failed")

    def select_context(label):
        checked(rt.cudaSetDevice(0))
        current = checked(drv.cuCtxGetCurrent())
        result[f"cuda_context_{label}"] = int(current)
        if int(current) != int(primary):
            raise RuntimeError("Threads did not select the same primary CUDA context")

    def prepare(engine):
        context = engine.create_execution_context(strategy)
        if context is None:
            raise RuntimeError("Execution context creation failed")
        buffers = []
        required = int(engine.device_memory_size_v2)
        if args.allocation == "USER_MANAGED":
            size = max(256, required)
            memory = checked(rt.cudaMalloc(size))
            buffers.append(memory)
            context.set_device_memory(int(memory), size)
        for i in range(engine.num_io_tensors):
            name = engine.get_tensor_name(i)
            if engine.get_tensor_dtype(name) != trt.float32:
                raise RuntimeError("The example expects float32 tensors")
            size = math.prod(engine.get_tensor_shape(name)) * 4
            memory = checked(rt.cudaMalloc(size))
            buffers.append(memory)
            checked(rt.cudaMemset(memory, 0, size))
            if not context.set_tensor_address(name, int(memory)):
                raise RuntimeError("Setting tensor address failed")
        stream = checked(rt.cudaStreamCreateWithFlags(rt.cudaStreamNonBlocking))
        if not context.execute_async_v3(int(stream)):
            raise RuntimeError("Warmup enqueue failed")
        checked(rt.cudaStreamSynchronize(stream))
        return context, buffers, stream, required

    def fail(label):
        result["errors"].append(f"thread {label}: {traceback.format_exc()}")
        aborted.set()
        for event in (b_ready, capture_open, capture_ended, destroyed):
            event.set()

    def thread_a():
        try:
            select_context("a")
            context, buffers, stream, required = prepare(engine_a)
            result["required_device_memory_a"] = required
            wait(b_ready)
            mode = getattr(rt.cudaStreamCaptureMode, f"cudaStreamCaptureMode{args.mode}")
            status, = rt.cudaStreamBeginCapture(stream, mode)
            result["begin_capture"] = int(status)
            checked((status,))
            result["order"].append("begin_capture")
            capture_open.set()
            if args.destroy == "during":
                wait(destroyed)
            status, state = rt.cudaStreamIsCapturing(stream)
            result["capture_query"] = int(status)
            result["capture_status_before_enqueue"] = int(state)
            result["enqueue_v3"] = bool(context.execute_async_v3(int(stream)))
            result["last_cuda_error_after_enqueue"] = int(rt.cudaGetLastError()[0])
            status, graph = rt.cudaStreamEndCapture(stream)
            result["end_capture"] = int(status)
            result["order"].append("end_capture")
            capture_ended.set()
            wait(destroyed)
            if int(status) == 0:
                checked(rt.cudaGraphDestroy(graph))
            del context
            for memory in buffers:
                checked(rt.cudaFree(memory))
            checked(rt.cudaStreamDestroy(stream))
        except Exception:
            fail("A")

    def thread_b():
        try:
            select_context("b")
            context, buffers, stream, required = prepare(engine_b)
            result["required_device_memory_b"] = required
            reference = weakref.ref(context)
            b_ready.set()
            wait(capture_open if args.destroy == "during" else capture_ended)
            result["b_python_refcount_before_del"] = sys.getrefcount(context) - 1
            if result["b_python_refcount_before_del"] != 1:
                raise RuntimeError("An extra Python reference keeps context B alive")
            result["order"].append("destroy_b_begin")
            # TensorRT frees the C++ object when the final Python reference dies.
            # __exit__ is a deprecated no-op; calling __del__ manually risks a double free.
            del context
            gc.collect()
            result["b_python_reference_gone"] = reference() is None
            if not result["b_python_reference_gone"]:
                raise RuntimeError("Execution context B is still referenced")
            result["order"].append("destroy_b_end")
            destroyed.set()
            # cudaFree / stream destruction can synchronize too. Keep them OUTSIDE
            # A's capture, so only the execution-context destructor overlaps it.
            wait(capture_ended)
            for memory in buffers:
                checked(rt.cudaFree(memory))
            checked(rt.cudaStreamDestroy(stream))
        except Exception:
            fail("B")

    a = threading.Thread(target=thread_a, name="capture", daemon=True)
    b = threading.Thread(target=thread_b, name="destroy", daemon=True)
    b.start()
    a.start()
    a.join(3 * args.wait_timeout)
    b.join(3 * args.wait_timeout)
    if a.is_alive() or b.is_alive():
        raise TimeoutError("Worker thread did not finish")
    del engine_b, engine_a, runtime
    gc.collect()
    result["capture_invalidated"] = result["end_capture"] == 901
    result["trial_complete"] = not result["errors"] and result["end_capture"] is not None
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--allocation", choices=("STATIC", "USER_MANAGED"), default="STATIC")
    parser.add_argument("--destroy", choices=("during", "after"), default="during")
    parser.add_argument("--mode", choices=("ThreadLocal", "Global"), default="ThreadLocal")
    parser.add_argument("--builder-threads", type=int, default=4)
    parser.add_argument("--wait-timeout", type=float, default=30)
    args = parser.parse_args()
    try:
        result = run(args)
    except Exception:
        result = {"trial_complete": False, "error": traceback.format_exc()}
    print(json.dumps(result, sort_keys=True), flush=True)
    return 0 if result["trial_complete"] else 2


if __name__ == "__main__":
    sys.exit(main())

Thread A creates an execution context of engine 1 and calls cudaStreamBeginCapture (ThreadLocal mode) on its
own non-blocking stream. While the capture is open, thread B drops the last Python reference to an execution
context of engine 2, which destroys it. After the destruction returns, thread A calls enqueueV3 and
cudaStreamEndCapture. The threads are ordered with threading.Event, not with sleeps. Thread B frees its own
buffers and stream only after thread A's capture has ended, so only the execution context destruction overlaps
the capture.

Result (10 processes per row, RTX A6000, driver 621.14):

TensorRT Allocation Destroy B during A's capture Destroy B after A's capture (control)
11.5.0.63 STATIC 10/10 invalidated 0/10
11.5.0.63 USER_MANAGED 10/10 invalidated 0/10
11.4.0.106 STATIC 10/10 invalidated 0/10
11.4.0.106 USER_MANAGED 10/10 invalidated 0/10
11.2.1.2 STATIC 10/10 invalidated 0/10
11.2.1.2 USER_MANAGED 10/10 invalidated 0/10

"Invalidated" means enqueueV3 returned false and cudaStreamEndCapture returned 901. In the control rows
enqueueV3 returned true and cudaStreamEndCapture returned 0. TensorRT logged an error only in the invalidated
runs, for example with 11.5.0.63:

[TensorRT][Severity.ERROR] IExecutionContext::enqueueV3: Error Code 1: Cuda Driver (In getCudaGreenContext at /_src/runtime/common/cudaDriverHelpers.cpp:269)

Have you tried the latest release?: Yes. 11.5.0.63 was the latest release on PyPI when we ran the test, and it reproduces.

Can this model run on other frameworks?: Not applicable. The issue is about the execution context lifetime, not a model.

Activity

  1. added
    Module:Documentation
    Module:Runtime
    on Nov 30, 2026
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

    Module:DocumentationModule:Runtime

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions