# torch.cuda ```{eval-rst} .. automodule:: torch.cuda ``` ```{eval-rst} .. currentmodule:: torch.cuda ``` ```{eval-rst} .. autosummary:: :toctree: generated :nosignatures: StreamContext can_device_access_peer check_error current_blas_handle current_solver_handle current_device current_stream cudart default_stream device device_count device_memory_used device_of get_arch_list get_device_capability get_device_name get_device_properties get_gencode_flags get_stream_from_external get_sync_debug_mode init ipc_collect is_available is_bf16_supported is_initialized is_tf32_supported memory_usage set_device set_stream set_sync_debug_mode stream synchronize utilization temperature power_draw clock_rate AcceleratorError OutOfMemoryError ``` ## Random Number Generator ```{eval-rst} .. autosummary:: :toctree: generated :nosignatures: get_rng_state get_rng_state_all set_rng_state set_rng_state_all manual_seed manual_seed_all seed seed_all initial_seed ``` ## Communication collectives ```{eval-rst} .. autosummary:: :toctree: generated :nosignatures: comm.broadcast comm.broadcast_coalesced comm.reduce_add comm.reduce_add_coalesced comm.scatter comm.gather ``` ## Streams and events ```{eval-rst} .. autosummary:: :toctree: generated :nosignatures: Stream ExternalStream Event execute_on_streams ``` ### Fork/join execution `torch.cuda.execute_on_streams(streams, fn, *inputs)` calls `fn` with corresponding items from each input sequence on each supplied stream, and returns a list of results in stream order. Each input sequence must have one item per stream. Ordinary streams, green-context streams, and mixtures are supported. Callbacks run sequentially on the host, but their CUDA work can run concurrently. Each stream waits for work already queued on the caller's current stream; subsequent caller-stream work waits for all work queued by the callbacks. This also applies to a single stream and to work queued before a callback raises. On the caller's device, the helper switches directly between streams and restores the caller once. Cross-device execution uses `torch.cuda.stream` to restore per-device stream state. Neither path synchronizes the host. After an exception, remaining callbacks are not invoked. Callbacks must enqueue work on the supplied stream or explicitly join other streams they use. The caller stream is the fork/join point, not every device's current stream. Keep tensors and any owning green contexts alive until their work completes; the usual cross-stream tensor lifetime rules still apply. Callbacks can enter `torch.cuda.use_mem_pool` themselves to choose the allocator used for their results. ## Graphs (beta) ```{eval-rst} .. autosummary:: :toctree: generated :nosignatures: is_current_stream_capturing graph_pool_handle CUDAGraph graph make_graphed_callables export_dot export_graph_data ``` ### CUDA graph lifecycle hooks Register callbacks that fire at each point in any CUDA graph's lifecycle -- capture start, capture end, instantiate, each replay, and destroy -- for example, a profiler observing graph lifecycle without the graph code carrying any consumer knowledge, and including graphs the consumer did not build. Registering a hook is the opt-in and the whole API -- the graph fires them; with none registered they are no-ops. Each has a per-graph counterpart on {class}`torch.cuda.CUDAGraph`. Live in `torch.cuda.graphs`. ```{eval-rst} .. currentmodule:: torch.cuda.graphs .. autosummary:: :toctree: generated :nosignatures: register_graph_capture_start_hook register_graph_capture_end_hook register_graph_instantiate_hook register_graph_replay_start_hook register_graph_replay_end_hook register_graph_destroy_hook .. currentmodule:: torch.cuda ``` ## Graph Kernel Annotations (prototype) `torch.cuda.graph_annotations` annotates the kernels captured in a CUDA graph with user metadata, keyed so the annotations can be joined against the ``graph node id`` field on kernel events in profiler traces. Enable recording per capture with the ``enable_annotations`` argument of {class}`torch.cuda.graph`, then wrap regions of the captured workload in {func}`~torch.cuda.graph_annotations.mark_kernels` scopes. These APIs require the `cuda-bindings` package and a CUDA driver that supports ``cudaGraphNodeGetToolsId`` (CUDA 13.1 or newer, or an equivalent cuda-compat package); recording silently degrades to a no-op otherwise, and is not supported on ROCm. Use {func}`~torch.cuda.graph_annotations.is_available` to check support. The end-to-end workflow: annotate during capture, profile the replay, then merge the annotations into the exported trace and view it in [Perfetto](https://ui.perfetto.dev). ```{note} Keep the graphs alive until all profiles using their annotations have been exported. For asynchronous Cuspy exports, also call `prof.wait_for_exports()` before resetting or destroying the graphs. Stopping the profiler or synchronizing CUDA alone does not guarantee that buffered profiling records have been processed. Resetting or destroying a graph removes its annotations, so pending profiles can lose that metadata. Save any Python launch stacks before graph cleanup as well. ``` During capture: ```python import torch from torch.cuda.graph_annotations import mark_kernels, get_kernel_annotations x = torch.randn(1024, 1024, device="cuda") # Warmup: run the workload once outside capture so lazy initialization # (e.g. cuBLAS handles) does not end up in -- or invalidate -- the capture. y = x @ x.t() z = torch.relu(y) @ x torch.cuda.synchronize() g = torch.cuda.CUDAGraph() with torch.cuda.graph(g, enable_annotations=True): with mark_kernels("attention"): y = x @ x.t() with mark_kernels({"name": "mlp", "layer": 3}): z = torch.relu(y) @ x with torch.profiler.profile() as prof: g.replay() torch.cuda.synchronize() prof.export_chrome_trace("trace.json") ``` Each kernel event in the exported trace carries a ``graph node id`` in its ``args``; the recorded annotations are keyed by the same ids, so merging them into the trace is a dictionary lookup: ```python import json annotations = get_kernel_annotations() with open("trace.json") as f: trace = json.load(f) for event in trace["traceEvents"]: node_id = event.get("args", {}).get("graph node id") for ann in annotations.get(node_id, []): event["args"].update(ann) with open("trace_annotated.json", "w") as f: json.dump(trace, f) ``` Opening ``trace_annotated.json`` in [Perfetto](https://ui.perfetto.dev) (or ``chrome://tracing``) and clicking a kernel from the graph replay now shows the annotation fields -- ``name: attention`` or ``name: mlp``, ``layer: 3`` -- alongside the kernel's grid and block sizes, identifying which region of the captured workload each kernel came from. Because annotations live in a process-global registry keyed by ids that match the profiler's, the pickle of ``dict(get_kernel_annotations())`` can equally be saved next to a trace and joined offline. To capture Python launch stacks as well, set ``annotation_config={"record_py_stacks": True}`` with ``enable_annotations=True``. Recording uses Cuspy's CUPTI node-creation callbacks, even when no profiler session is running. It requires `cupti-python`, CUPTI >= 13.3, and a CUPTI subscription not already held by Kineto, Nsight Systems, or another profiler. Use Cuspy for subsequent GPU profiling in the same process. Disable autograd multithreading during both warmup and capture. Stacks contain user Python frames on the launching thread for kernel, memcpy, memset, batch-memory, event, and host nodes. Framework and generated Inductor frames are omitted by default; C++ autograd nodes do not recover their forward Python stacks. Conditional and child-graph body stacks require ``key_by="source"`` (CUPTI and driver >= 13.4); they are omitted with ``key_by="exec"``. ```python from torch.cuda.graph_annotations import dump_kernel_py_stacks g = torch.cuda.CUDAGraph() with ( torch.autograd.grad_mode.set_multithreading_enabled(False), torch.cuda.graph( g, enable_annotations=True, annotation_config={"record_py_stacks": True} ), ): y = x @ x.t() dump_kernel_py_stacks("graph_stacks.json.gz") ``` Use ``annotation_config["py_stack_filter_paths"]`` to customize filtering: ``None`` keeps the defaults, a list or tuple of directory paths replaces them, and ``[]`` disables frame filtering. For example, ``{"record_py_stacks": True, "py_stack_filter_paths": ["/my_project/wrappers"]}`` excludes only frames in that directory. Paths match on directory boundaries, and relative paths are resolved when capture begins. Read stacks with {func}`~torch.cuda.graph_annotations.get_kernel_py_stacks` or save them beside the trace with {func}`~torch.cuda.graph_annotations.dump_kernel_py_stacks`. The gzip-compressed JSON maps decimal node-id strings to newline-separated ``filename:line:function`` frames, innermost first. With the default ``key_by="exec"``, look up a Cuspy Chrome trace event using ``str((args["graph id"] << 32) | args["graph node id"])``. For consumers reading CUPTI's ``sourceGraphNodeId``, use ``key_by="source"`` and look up that ID directly. Save after instantiation and before resetting or destroying the graph. ```{eval-rst} .. currentmodule:: torch.cuda.graph_annotations ``` ```{eval-rst} .. autosummary:: :toctree: generated :nosignatures: is_available mark_kernels get_kernel_annotations get_kernel_py_stacks dump_kernel_py_stacks clear_kernel_annotations ``` ```{eval-rst} .. currentmodule:: torch.cuda ``` (cuda-memory-management-api)= ```{eval-rst} .. automodule:: torch.cuda.memory ``` ```{eval-rst} .. currentmodule:: torch.cuda.memory ``` ## Memory management ```{eval-rst} .. autosummary:: :toctree: generated :nosignatures: empty_cache get_per_process_memory_fraction list_gpu_processes mem_get_info memory_stats memory_stats_as_nested_dict reset_accumulated_memory_stats host_memory_stats host_memory_stats_as_nested_dict reset_accumulated_host_memory_stats memory_summary memory_snapshot memory_allocated max_memory_allocated reset_max_memory_allocated memory_reserved max_memory_reserved set_per_process_memory_fraction memory_cached max_memory_cached reset_max_memory_cached reset_peak_memory_stats reset_peak_host_memory_stats caching_allocator_alloc caching_allocator_delete get_allocator_backend CUDAPluggableAllocator change_current_allocator MemPool LocalizedAllocator ``` ```{eval-rst} .. autosummary:: :toctree: generated :nosignatures: caching_allocator_disabled caching_allocator_enable ``` ```{eval-rst} .. currentmodule:: torch.cuda ``` ```{eval-rst} .. autoclass:: torch.cuda.use_mem_pool ``` ```{eval-rst} .. currentmodule:: torch.cuda.nccl ``` ```{eval-rst} .. autofunction:: version ``` ```{eval-rst} .. currentmodule:: torch.cuda.profiler .. autosummary:: :toctree: generated :nosignatures: profile start stop ``` ```{eval-rst} .. currentmodule:: torch.cuda ``` ## NVIDIA Tools Extension (NVTX) ```{eval-rst} .. autosummary:: :toctree: generated :nosignatures: nvtx.mark nvtx.range_push nvtx.range_pop nvtx.range nvtx.range_end nvtx.range_start ``` ## Jiterator (beta) ```{eval-rst} .. autosummary:: :toctree: generated :nosignatures: jiterator._create_jit_fn jiterator._create_multi_output_jit_fn ``` ## TunableOp Some operations could be implemented using more than one library or more than one technique. For example, a GEMM could be implemented for CUDA or ROCm using either the cublas/cublasLt libraries or hipblas/hipblasLt libraries, respectively. How does one know which implementation is the fastest and should be chosen? That's what TunableOp provides. Certain operators have been implemented using multiple strategies as Tunable Operators. At runtime, all strategies are profiled and the fastest is selected for all subsequent operations. See the {doc}`documentation ` for information on how to use it. ```{toctree} :hidden: true cuda.tunable ``` ## Stream Sanitizer (prototype) CUDA Sanitizer is a prototype tool for detecting synchronization errors between streams in PyTorch. See the {doc}`documentation ` for information on how to use it. ```{toctree} :hidden: true cuda._sanitizer ``` ## GPUDirect Storage (prototype) The APIs in `torch.cuda.gds` provide thin wrappers around certain cuFile APIs that allow direct memory access transfers between GPU memory and storage, avoiding a bounce buffer in the CPU. See the [cufile api documentation](https://docs.nvidia.com/gpudirect-storage/api-reference-guide/index.html#cufile-io-api) for more details. These APIs can be used with CUDA 12.6 or newer. In order to use these APIs, one must ensure that their system is appropriately configured to use GPUDirect Storage per the [GPUDirect Storage documentation](https://docs.nvidia.com/gpudirect-storage/troubleshooting-guide/contents.html). On ROCm, the same APIs are backed by [hipFile](https://rocm.docs.amd.com/projects/hipFile/en/latest/) rather than cuFile and require ROCm 7.14 or newer. The hipFile entry points and the ROCm system configuration steps, which differ from the CUDA ones, are covered in {ref}`hipFile (GPUDirect Storage)`. See the docs for {class}`~torch.cuda.gds.GdsFile` for an example of how to use these. ```{eval-rst} .. currentmodule:: torch.cuda.gds ``` ```{eval-rst} .. autosummary:: :toctree: generated :nosignatures: is_available gds_register_buffer gds_deregister_buffer GdsFile ``` ## Green Contexts (experimental) `torch.cuda.green_contexts` provides thin wrappers around the CUDA Green Context APIs to enable more general carveout of SM resources for CUDA kernels. These APIs require the `cuda.bindings` package and can be used in PyTorch with CUDA versions greater than or equal to 12.8. Workqueue configuration requires CUDA 13.1 or newer. Install instructions for `cuda.bindings` can be found here: https://nvidia.github.io/cuda-python/ Create streams from the green context and use them like other custom CUDA streams: ```python ctx = GreenContext(...) stream = ctx.Stream() with torch.cuda.stream(stream): # torch operations here are using resources from `ctx` pass ``` Synchronization between green-context streams and other streams is the user's responsibility. Use CUDA events to order work, just as you would for any other custom stream. The `GreenContext.set_context()` and `GreenContext.pop_context()` methods are deprecated compatibility APIs. To create contexts with disjoint SM allocations (CUDA driver and bindings 13.1+), specify all groups in one operation: ```python from torch.cuda.green_contexts import GreenContext, SMPartition a, b = GreenContext.split( num_sms=(24, 40), coscheduled_sm_count=(8, 4), device_id=0 ) print(a.sm_count, b.sm_count) ``` To retain the remainder, use `SMPartition.split`. To subdivide a returned partition or remainder, create a context from it and split the resource queried through its `sm_partition` property. CUDA drivers can reject raw split outputs as already partitioned resources, so the context creation is explicit: ```python sms = SMPartition.from_device(device_id=0) (first,), rest = sms.split(num_sms=4, coscheduled_sm_count=2) rest_ctx = GreenContext(sm_partition=rest) (second,), rest = rest_ctx.sm_partition.split(num_sms=4, coscheduled_sm_count=2) ctx = GreenContext(sm_partition=second, workqueue_scope="balanced") ``` Each split partitions its input resource. Its children and remainder are mutually disjoint, but overlap the parent. Results of separate splits on the same or overlapping input resources may overlap. CUDA evaluates new constraints when subdividing a resource; the remainder does not inherit the earlier split's alignment. Partitioning does not reserve SMs against other contexts or guarantee concurrent execution. Each split option accepts a scalar or a sequence. All sequences must have the same nonzero length; scalars are broadcast to that length. With scalars only, one group is created. The default `num_sms=0` discovers the largest group satisfying its constraints. Groups are evaluated in order, so an early discovery group can exhaust the SMs needed by later groups. A group with both `num_sms=0` and `backfill=True` consumes all remaining SMs, so it must be the last group. Otherwise, specify a positive SM count. CUDA validates hardware constraints without PyTorch rounding the requested sizes. CUDA permits kernels to use additional SMs in some configurations involving MPS or dynamic parallelism; see the [CUDA green-context documentation](https://docs.nvidia.com/cuda/cuda-driver-api/cuda_driver_api/group__CUDA__GREEN__CONTEXTS.html). `GreenContext.sm_count` reports the actual allocation, including for contexts created through the existing `num_sms` constructor. Independent constructor calls do not guarantee disjoint SMs. A context's `sm_partition` property returns a resource that can be subdivided and keeps its originating context alive. Locality domains describe hardware topology. With CUDA driver and bindings 13.4+, add locality constraints when splitting a resource: ```python from torch.cuda.green_contexts import get_num_locality_domains n = get_num_locality_domains(device_id=0) contexts = GreenContext.split( coscheduled_sm_count=2, locality_domain_ids=tuple(range(n)), device_id=0, ) ``` Here, the default zero SM count is broadcast to each locality domain and discovers its available SMs. Some device SMs may be outside all locality domains and remain unassigned. A domain can contain multiple partitions; its ID can also constrain subdivision through an existing context's queried SM resource, as shown above. Use `None` for a group with no locality constraint. Workqueue settings can be combined with either kind of split. `backfill=True` permits CUDA to fill a group with SMs outside its co-scheduling or locality constraints. It preserves the separation between sibling partitions. The `locality_domain_id` property on partitions and contexts reads CUDA's reported metadata and returns `None` if CUDA does not specify a domain. `get_num_locality_domains` returns `1` when the required software is unavailable. With CUDA driver and bindings 13.4+, it queries CUDA directly; invalid devices and failed queries raise. Supplying an explicit device index initializes only the driver, without initializing PyTorch CUDA state or creating a primary context. Driver initialization can still prevent CUDA use in subsequently forked children. `is_localization_supported` returns false for unsupported software or devices with at most one domain. Before driver initialization, it attempts a best-effort NVML capability check using `CUDA_VISIBLE_DEVICES`. If NVML cannot determine support, it raises; initialize CUDA explicitly before querying again if needed. After driver initialization, the query always uses CUDA and query errors propagate. The predicate does not initialize the driver or a context, so calling it does not poison subsequent forks. Actual splitting and context creation always use CUDA, independently of this capability check. The pre-initialization NVML result does not predict a later attachment to an MPS server; this dynamic flow is not supported by the NVML check. Query again after attachment instead of reusing the earlier result. An already attached MPS client has initialized CUDA, so the query uses CUDA's actual device topology rather than NVML. The support result itself is not cached. ### Fork/join execution with green contexts Use `torch.cuda.execute_on_streams` with green-context streams to localize the execution of each callback's CUDA work: ```python from torch.cuda.green_contexts import GreenContext contexts = GreenContext.split(num_sms=(24, 24), device_id=0) streams = [ctx.Stream() for ctx in contexts] inputs = [torch.randn(1024, device="cuda:0") for _ in streams] def compute(value: torch.Tensor) -> torch.Tensor: return value * 2 with torch.cuda.device(0): outputs = torch.cuda.execute_on_streams(streams, compute, inputs) result = outputs[0] + outputs[1] torch.cuda.current_stream().synchronize() ``` ### Localized allocations With CUDA driver and cuda.bindings 13.4+, `LocalizedAllocator` allocates physical memory on a specified locality domain. Use it with the existing `MemPool` API to cache and suballocate that memory. Construction initializes CUDA so validation uses the actual CUDA-visible topology. Allocation does not localize execution; use a green-context stream separately when compute localization is also desired. ```python allocator = torch.cuda.LocalizedAllocator(locality_domain_id=0, device="cuda:0") with torch.cuda.device(allocator.device_id): pool = torch.cuda.MemPool(allocator=allocator.allocator()) with torch.cuda.use_mem_pool(pool, device="cuda:0"): # x is allocated on locality domain 0 # the randn kernel runs non-localized x = torch.randn(1024, device="cuda:0") ``` Use the allocator only on its owning device; cross-device access is not supported. Callback owners are retained for the process lifetime, so tensors can outlive the Python allocator and pool objects. One owner and primary-context reference per device/domain are deliberately retained through interpreter shutdown. Reclaiming physical memory waits for the allocation stream. Cleanup failures are logged, not raised; memory still in use after a failed stream wait is left for process exit to reclaim. During interpreter shutdown, callbacks skip CUDA cleanup entirely. ```{warning} Concurrent allocator activity is unsupported. Other threads must not allocate, free, or query allocator state (including `MemPool.use_count()`) concurrently with this allocator. The ctypes callbacks acquire the GIL while holding the native allocator mutex; an allocator-state query can acquire these locks in the opposite order and deadlock. ``` #### Fork/join execution with localized outputs On GPUs with at least two locality domains, one can pair each green-context stream with a memory pool for the same domain, along with `execute_on_streams` to return localized outputs in stream order. ```python from torch.cuda.green_contexts import GreenContext def compute(value: torch.Tensor, pool: torch.cuda.MemPool) -> torch.Tensor: with torch.cuda.use_mem_pool(pool, device="cuda:0"): return value * 2 with torch.cuda.device(0): domains = (0, 1) contexts = GreenContext.split(locality_domain_ids=domains, device_id=0) streams = [ctx.Stream() for ctx in contexts] allocators = [torch.cuda.LocalizedAllocator(d, device="cuda:0") for d in domains] pools = [] for allocator in allocators: with torch.cuda.device(allocator.device_id): pools.append(torch.cuda.MemPool(allocator=allocator.allocator())) # non-localized inputs inputs = [torch.randn(1024, device="cuda:0") for _ in streams] # localized outputs: callback `compute` uses local pool for its allocations outputs = torch.cuda.execute_on_streams(streams, compute, inputs, pools) torch.cuda.current_stream().synchronize() ``` Keep the contexts, pools, and tensors alive until their GPU work completes. ```{eval-rst} .. currentmodule:: torch.cuda.green_contexts ``` ```{eval-rst} .. autosummary:: :toctree: generated :nosignatures: GreenContext SMPartition get_num_locality_domains is_localization_supported ``` % This module needs to be documented. Adding here in the meantime % for tracking purposes ```{eval-rst} .. py:module:: torch.cuda.comm ``` ```{eval-rst} .. py:module:: torch.cuda.gds ``` ```{eval-rst} .. py:module:: torch.cuda.graph_annotations ``` ```{eval-rst} .. py:module:: torch.cuda.green_contexts ``` ```{eval-rst} .. py:module:: torch.cuda.jiterator ``` ```{eval-rst} .. py:module:: torch.cuda.nccl .. autofunction:: torch.cuda.nccl.is_available ``` ```{eval-rst} .. automodule:: torch.cuda.nvtx ``` ```{eval-rst} .. currentmodule:: torch.cuda.nvtx ``` ```{eval-rst} .. py:module:: torch.cuda.profiler ``` ```{eval-rst} .. py:module:: torch.cuda.sparse ``` ```{eval-rst} .. toctree:: :hidden: cuda.aliases.md ```