torch.cuda
.. automodule:: torch.cuda
.. currentmodule:: torch.cuda
.. 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
.. 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
.. autosummary::
:toctree: generated
:nosignatures:
comm.broadcast
comm.broadcast_coalesced
comm.reduce_add
comm.reduce_add_coalesced
comm.scatter
comm.gather
Streams and events
.. 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)
.. 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.
{func}torch.cuda.graphs.rewrite_small_memsets returns a ready-made capture-end hook. It
replaces small memset nodes -- what zero_() on a small dense tensor records -- with
fill-kernel nodes, which can replay faster inside a graph of kernels. It is opt-in: register
it on the graphs, or globally in the application, that were measured to benefit.
.. 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
rewrite_small_memsets
.. 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.
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:
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:
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
(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, a CUDA >= 13.5 build, CUPTI >= 13.5,
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".
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.
.. currentmodule:: torch.cuda.graph_annotations
.. autosummary::
:toctree: generated
:nosignatures:
is_available
mark_kernels
get_kernel_annotations
get_kernel_py_stacks
dump_kernel_py_stacks
clear_kernel_annotations
.. currentmodule:: torch.cuda
(cuda-memory-management-api)=
.. automodule:: torch.cuda.memory
.. currentmodule:: torch.cuda.memory
Memory management
.. 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
HostMemPool
LocalizedAllocator
.. autosummary::
:toctree: generated
:nosignatures:
caching_allocator_disabled
caching_allocator_enable
.. currentmodule:: torch.cuda
.. autoclass:: torch.cuda.use_mem_pool
.. currentmodule:: torch.cuda.nccl
.. autofunction:: version
.. currentmodule:: torch.cuda.profiler
.. autosummary::
:toctree: generated
:nosignatures:
profile
start
stop
.. currentmodule:: torch.cuda
NVIDIA Tools Extension (NVTX)
.. autosummary::
:toctree: generated
:nosignatures:
nvtx.mark
nvtx.range_push
nvtx.range_pop
nvtx.range
nvtx.range_end
nvtx.range_start
Jiterator (beta)
.. 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 <cuda.tunable> for information on how to use it.
: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 <cuda._sanitizer> for information on how to use it.
: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
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.
On ROCm, the same APIs are backed by hipFile
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)<rocm-gds>.
See the docs for {class}~torch.cuda.gds.GdsFile for an example of how to use these.
{meth}~torch.cuda.gds.GdsFile.load_storage and {meth}~torch.cuda.gds.GdsFile.save_storage
first wait for the work already enqueued on the current stream, then block the host until the
transfer completes. {meth}~torch.cuda.gds.GdsFile.load_storage_async
and {meth}~torch.cuda.gds.GdsFile.save_storage_async are instead enqueued on the current stream
and return without waiting, and follow the usual {ref}stream semantics<cuda-stream-semantics>.
All four raise an error during CUDA graph capture.
.. currentmodule:: torch.cuda.gds
.. autosummary::
:toctree: generated
:nosignatures:
is_available
gds_register_buffer
gds_deregister_buffer
GdsFile
Green Contexts (experimental)
{class}~torch.cuda.green_contexts.GreenContext supports SM partitioning,
workqueue configuration, or both for CUDA execution. Green contexts require
CUDA user-mode driver and cuda.bindings 12.8+;
splitting and workqueue configuration require 13.1+, locality domains and
localized allocations require 13.4+, and supplemental locality-domain SMs require
13.5+. These are runtime requirements, not requirements to rebuild PyTorch.
See the cuda.bindings installation instructions.
The loaded CUDA user-mode driver must also provide the required APIs; upgrading
the bindings alone does not upgrade it. If the system's user-mode driver is too
old, install the corresponding cuda-compat package for a supported GPU/kernel-driver
combination and prepend its library directory to LD_LIBRARY_PATH before
starting Python. For 13.5 functionality, use cuda-compat-13-5 and bindings 13.5+:
python -m pip install 'cuda-bindings>=13.5,<14'
LD_LIBRARY_PATH=/path/to/cuda-13.5/compat${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} python your_program.py
Replace the path with the installed or extracted compat library directory. No compat override is needed when the system-installed user-mode driver already supports the required APIs.
Partitioning and execution
Create disjoint groups in one operation, then run work on their streams:
from torch.cuda.green_contexts import GreenContext
a, b = GreenContext.split(num_sms=(8, 16), coscheduled_sm_count=2, device_id=0)
stream = a.Stream()
with torch.cuda.stream(stream):
x = torch.ones(32, device="cuda:0")
stream.synchronize()
Use CUDA events to order work across streams, as with other custom streams.
Partitioning does not reserve SMs against other contexts or guarantee concurrent
execution. Use {meth}~torch.cuda.green_contexts.SMPartition.split to retain the
remainder or manage partitions directly; its API documentation describes
subdivision, co-scheduling constraints, discovery, and backfill.
Locality domains
On multi-domain GPUs, select groups by locality domain. With user-mode driver and
bindings 13.5+, include_supplemental_sms=True also selects eligible domain-owned SMs
beyond the nominal count. Per-domain group sizes can therefore be uneven:
from torch.cuda.green_contexts import get_num_locality_domains
contexts = GreenContext.split(
locality_domain_ids=tuple(range(get_num_locality_domains(0))),
coscheduled_sm_count=2,
include_supplemental_sms=True,
device_id=0,
)
Use {func}~torch.cuda.green_contexts.is_localization_supported to check
capability and {func}~torch.cuda.green_contexts.get_num_sms_per_locality_domain
for the nominal SM count; each context's sm_count reports its actual allocation.
See the API docs for per-group options, query initialization/fork behavior, and
locality guarantees when using backfill.
Green-context streams also work with
{func}~torch.cuda.execute_on_streams for fork/join execution.
Localized allocations
On multi-domain GPUs, {class}~torch.cuda.LocalizedAllocator selects physical
memory from a locality domain. Pair it with a {class}~torch.cuda.MemPool to
cache allocations:
with torch.cuda.device(0):
allocator = torch.cuda.LocalizedAllocator(0, device="cuda:0")
pool = torch.cuda.MemPool(allocator=allocator.allocator())
with torch.cuda.use_mem_pool(pool, device="cuda:0"):
x = torch.ones(1024, device="cuda:0")
Allocation locality does not localize execution; use a green-context stream when both are needed. Use the allocator only on its owning device, and keep contexts, pools, and tensors alive until their GPU work completes. The allocator API docs cover ownership and cleanup behavior.
.. currentmodule:: torch.cuda.green_contexts
.. autosummary::
:toctree: generated
:nosignatures:
GreenContext
SMPartition
get_num_locality_domains
get_num_sms_per_locality_domain
is_localization_supported
% This module needs to be documented. Adding here in the meantime
% for tracking purposes
.. py:module:: torch.cuda.comm
.. py:module:: torch.cuda.gds
.. py:module:: torch.cuda.graph_annotations
.. py:module:: torch.cuda.green_contexts
.. py:module:: torch.cuda.jiterator
.. py:module:: torch.cuda.nccl
.. autofunction:: torch.cuda.nccl.is_available
.. automodule:: torch.cuda.nvtx
.. currentmodule:: torch.cuda.nvtx
.. py:module:: torch.cuda.profiler
.. py:module:: torch.cuda.sparse
.. toctree::
:hidden:
cuda.aliases.md