CUDA® Python Interoperability#
2026-09-10
20 min read
Advanced Micro Devices, Inc.
This chapter discusses HIP Python’s CUDA® Python interoperability layer
that is shipped in a separate package with the name hip-python-interop.
In particular, we discuss how to run existing CUDA Python code on AMD GPUs,
and if localized modifications are required, how to detect HIP Python and
how to fall back to the underlying HIP Python Python and Cython modules.
Moreover, a technique named “enum constant hallucination” is presented that
allows HIP Python “invent” enum constants and their non-conflicting value
on-the-fly for enum error types.
Note
All examples in this chapter have been tested with ROCm™ 7.13 on Ubuntu 22.04. The License applies to all examples in this chapter.
Installation#
HIP Python’s CUDA interoperability layer comes in a separate Python 3
package with the name hip-python-interop. Its dependencies are the
rocm-bindings-hip and rocm-bindings-systems packages, each pinned
to the exact same version number. The interop layer forwards CUDA calls
into rocm-bindings-hip; the bundled pynvml shim (see
NVML compatibility shim (pynvml)) is backed by rocm.bindings.amdsmi and the
nvtx shim (see NVTX compatibility shim (nvtx)) by rocm.bindings.roctx,
both from rocm-bindings-systems.
After having identified the correct package for your ROCm™ installation, type:
python3 -m pip install hip-python-interop~=<rocm_version>
or, if you have a HIP Python wheel somewhere in your filesystem, type:
python3 -m pip install <path/to/hip_python_interop>.whl
Note
See HIP Python Versioning for more details on the
hip-python-interop version number.
Basic Usage (Python)#
What will I learn?
How I can use HIP Python’s CUDA Python interoperability modules in my Python code.
After installing hip-python-interop, you can import the individual
modules that you need as shown below:
1from cuda.bindings import driver
2from cuda.bindings import runtime
3from cuda.bindings import nvrtc
Note
cuda.bindings is the package; driver (CUDA Driver API),
runtime (CUDA Runtime API), and nvrtc (NVRTC) are the
modules. Importing them under shorter names (from cuda import
cuda etc., as some older CUDA Python releases used to support)
is not provided by hip-python-interop.
Note
The cuda.bindings modules above mirror the surface CUDA Python
itself exposes under cuda.bindings. A fourth module,
cuFile shim (cuda.bindings.cufile) (a cuFile file-IO shim), is built and
shipped whenever the underlying hipFILE bindings are available. In
addition, the hip-python-interop wheel ships three small
convenience compatibility shims for common CUDA-ecosystem entry
points: NVML compatibility shim (pynvml) (an NVML / pynvml shim),
NVTX compatibility shim (nvtx) (an NVTX / nvtx shim) and
cuda.core compatibility shim (a minimal cuda.core shim).
Python Example#
What will I learn?
How I can run simple CUDA Python applications directly on AMD GPUs via HIP Python.
After installing hip-python-interop (and its rocm-bindings-hip
and rocm-bindings-systems dependencies), you can run the
example below directly
on AMD GPUs. There is nothing else to do. This works because all CUDA
Python functions, types and even enum constants are aliases of HIP
objects.
See
cudaError_t,
cudaStreamCreate,
cudaMemcpyAsync,
cudaMemsetAsync,
cudaStreamSynchronize,
cudaStreamDestroy,
cudaFree
1import random
2
3from cuda.bindings import runtime
4
5
6def cuda_check(call_result):
7 if isinstance(call_result, tuple):
8 err = call_result[0]
9 result = call_result[1:]
10 if len(result) == 1:
11 result = result[0]
12 else:
13 # Single-output funcs (e.g. cudaStreamCreate after the
14 # with-nogil codegen refactor) return the bare error enum,
15 # not a 1-tuple. Treat that as an empty-result call.
16 err = call_result
17 result = ()
18 if (
19 isinstance(err, runtime.cudaError_t)
20 and err != runtime.cudaError_t.cudaSuccess
21 ):
22 raise RuntimeError(str(err))
23 return result
24
25
26# inputs
27n = 100
28x_h = array.array("i", [int(random.random() * 10) for i in range(0, n)])
29num_bytes = x_h.itemsize * len(x_h)
30x_d = cuda_check(runtime.cudaMalloc(num_bytes))
31
32stream = cuda_check(runtime.cudaStreamCreate())
33cuda_check(
34 runtime.cudaMemcpyAsync(
35 x_d,
36 x_h,
37 num_bytes,
38 runtime.cudaMemcpyKind.cudaMemcpyHostToDevice,
39 stream,
40 )
41)
42cuda_check(runtime.cudaMemsetAsync(x_d, 0, num_bytes, stream))
43cuda_check(
44 runtime.cudaMemcpyAsync(
45 x_h,
46 x_d,
47 num_bytes,
48 runtime.cudaMemcpyKind.cudaMemcpyDeviceToHost,
49 stream,
50 )
51)
52cuda_check(runtime.cudaStreamSynchronize(stream))
53cuda_check(runtime.cudaStreamDestroy(stream))
54
55# deallocate device data
56cuda_check(runtime.cudaFree(x_d))
57
58for i, x in enumerate(x_h):
59 if x != 0:
60 raise ValueError(f"expected '0' for element {i}, is: '{x}'")
61print("ok")
What is happening?
See HIP Streams for an explanation of a similar HIP program’s steps.
cuFile shim (cuda.bindings.cufile)#
What will I learn?
That
from cuda.bindings import cufilekeeps working unchanged on AMD GPUs.How the cuFile API maps onto AMD’s hipFILE.
The hip-python-interop wheel provides a cuda.bindings.cufile
module: a compiled interop layer for the CUDA cuFile API, backed by
AMD’s hipFILE via the low-level
rocm.bindings.cyhipfile declarations. Code that already
drives cuda.bindings.cufile — driver_open,
handle_register, buf_register, read / write, the async
and batch APIs — can keep calling it unmodified on AMD hardware,
where it dispatches into libhipfile.
Note
Unlike cuda.bindings.driver / runtime / nvrtc,
which are emitted by the HIP Python code generator, cufile is a
hand-written module. Like the rocm.bindings.hipfile bindings it
builds on, it is optional: it is only compiled and shipped when
the hipFILE bindings (and a loadable libhipfile.so) are present.
Use from cuda.bindings import cufile guarded by a try /
except ImportError if you need to run where hipFILE is absent.
The module mirrors CUDA Python’s cuda.bindings.cufile surface:
snake_case functions that take
intptr_tpointer arguments (device pointers, file handles,hipFileDescr_t*) as plain Python integers, and raisecufile.cuFileErroron a non-success status;read/writereturn the number of bytes transferred and raiseOSErrorfor a POSIX error (raw return-1);the
Descr/IOParams/IOEventsarray helpers that expose the backing C structs and a.ptraddress to hand to the calls;IntEnummirrors of the cuFile enums (OpError,FileHandleType,Status, the config-parameter enums, …) whose member names follow cuda-python and whose values come from hipFILE.
Important
Divergences from cuFile. get_version() returns the version
packed into a single integer (major*1000 + minor*10 + patch),
matching cuFile, even though hipFILE reports the three components
separately. cuFileError additionally carries a cu_err
attribute (the underlying hipError_t for CUDA_DRIVER_ERROR).
See
driver_open,
buf_register,
Descr,
handle_register,
read,
write,
driver_close
1import hashlib
2import os
3import pathlib
4import tempfile
5
6from cuda.bindings import cufile, runtime
7
8
9def cuda_check(call_result):
10 """Unwrap the ``(error, *results)`` tuple returned by cuda.bindings.runtime."""
11 if isinstance(call_result, tuple):
12 err = call_result[0]
13 result = call_result[1:]
14 if len(result) == 1:
15 result = result[0]
16 else:
17 err = call_result
18 result = ()
19 if (
20 isinstance(err, runtime.cudaError_t)
21 and err != runtime.cudaError_t.cudaSuccess
22 ):
23 raise RuntimeError(str(err))
24 return result
25
26
27def _register_handle(fd):
28 """Build a cuFile file descriptor for ``fd`` and register it."""
29 descr = cufile.Descr()
30 descr.type = cufile.FileHandleType.OPAQUE_FD
31 descr.handle.fd = fd
32 # Keep the Descr alive until the handle is registered (handle_register
33 # copies out of it); returning it lets the caller hold the reference.
34 return cufile.handle_register(descr.ptr), descr
35
36
37print(f"cuFile Version: {cufile.get_version()}")
38
39# cuFile issues its reads/writes with O_DIRECT, so the scratch files must live
40# on an O_DIRECT-capable filesystem. Default to the system temp dir and allow
41# an override via HIPFILE_TMPDIR (e.g. point at an ext4 mount if the default
42# temp dir is tmpfs).
43scratch_dir = os.environ.get("HIPFILE_TMPDIR") or None
44
45# 2 MiB, block-aligned so the O_DIRECT transfers are valid.
46size = 2 * 1024 * 1024
47
48with tempfile.TemporaryDirectory(dir=scratch_dir) as tmp_dir:
49 input_path = pathlib.Path(tmp_dir) / "random_2MiB.bin"
50 output_path = pathlib.Path(tmp_dir) / "output.bin"
51
52 # Create the random input up front so the example is fully self-contained.
53 input_path.write_bytes(os.urandom(size))
54
55 print(f"Driver Use Count Before: {cufile.use_count()}")
56
57 # Allocate the device bounce buffer via the cuda-bindings runtime API.
58 dev_ptr = int(cuda_check(runtime.cudaMalloc(size)))
59 print(f"Buffer located at: {dev_ptr} | {hex(dev_ptr)}")
60
61 cufile.driver_open()
62 fd_input = fd_output = None
63 fh_input = fh_output = None
64 buffer_registered = False
65 try:
66 print(f"Driver Use Count After: {cufile.use_count()}")
67
68 cufile.buf_register(dev_ptr, size, 0)
69 buffer_registered = True
70
71 fd_input = os.open(input_path, os.O_RDWR | os.O_DIRECT | os.O_CREAT)
72 fd_output = os.open(
73 output_path, os.O_RDWR | os.O_DIRECT | os.O_CREAT | os.O_TRUNC
74 )
75
76 fh_input, _descr_in = _register_handle(fd_input)
77 fh_output, _descr_out = _register_handle(fd_output)
78
79 print(f"Transferring {size} bytes...")
80 bytes_read = cufile.read(fh_input, dev_ptr, size, 0, 0)
81 print(f"Bytes Read: {bytes_read}")
82 bytes_written = cufile.write(fh_output, dev_ptr, size, 0, 0)
83 print(f"Bytes Written: {bytes_written}")
84 finally:
85 if fh_output is not None:
86 cufile.handle_deregister(fh_output)
87 if fh_input is not None:
88 cufile.handle_deregister(fh_input)
89 if buffer_registered:
90 cufile.buf_deregister(dev_ptr)
91 if fd_output is not None:
92 os.close(fd_output)
93 if fd_input is not None:
94 os.close(fd_input)
95 cufile.driver_close()
96 cuda_check(runtime.cudaFree(dev_ptr))
97
98 with open(input_path, "br") as file_in:
99 hash_in = hashlib.sha256()
100 chunk = file_in.read(1 * 1024 * 1024)
101 while len(chunk) != 0:
102 hash_in.update(chunk)
103 chunk = file_in.read(1 * 1024 * 1024)
104 print(f"Input File Hash: {hash_in.hexdigest()}")
105
106 with open(output_path, "br") as file_out:
107 hash_out = hashlib.sha256()
108 chunk = file_out.read(1 * 1024 * 1024)
109 while len(chunk) != 0:
110 hash_out.update(chunk)
111 chunk = file_out.read(1 * 1024 * 1024)
112 print(f"Output File Hash: {hash_out.hexdigest()}")
113
114 assert hash_in.hexdigest() == hash_out.hexdigest(), "file hashes differ"
115 print("ok")
Note
cuFile issues its transfers with O_DIRECT, which requires an
O_DIRECT-capable filesystem. The example creates its own scratch
files; point HIPFILE_TMPDIR at such a mount (e.g. an ext4 volume)
if your default temp dir is tmpfs.
See also
The full API reference for the module is at
cuda.bindings.cufile. For the underlying
AMD API see the high-level rocm.hipfile
wrappers and the rocm.bindings.hipfile bindings.
NVML compatibility shim (pynvml)#
What will I learn?
That
import pynvmlkeeps working unchanged on AMD GPUs.Which part of the NVML surface the shim implements and how it behaves for concepts that do not exist on ROCm™.
The hip-python-interop wheel installs a top-level pynvml
module: a compatibility shim for the NVML Python API backed by AMD
SMI via the high-level rocm.bindings.amdsmi bindings. Code
that already speaks NVML — for example HIP ports of RAPIDS-style
projects — can keep calling pynvml unmodified on AMD hardware.
Note
This shim is a fresh, MIT-licensed re-implementation of the subset
of the NVML Python surface that HIP consumers commonly use. It is
not a fork of the upstream pynvml / nvidia-ml-py
package. Because it is backed by AMD SMI, the interop wheel pulls in
rocm-bindings-systems (which provides rocm.bindings.amdsmi)
in addition to rocm-bindings-hip.
The implemented surface covers the entry points HIP ports rely on:
Lifecycle:
nvmlInit/nvmlInitWithFlags/nvmlShutdown(reference-counted, mapping toamdsmi_init/amdsmi_shut_down).Device enumeration and handles:
nvmlDeviceGetCount,nvmlDeviceGetHandleByIndex,nvmlDeviceGetHandleByUUID,nvmlDeviceGetIndex.Device queries:
nvmlDeviceGetMemoryInfo,nvmlDeviceGetName,nvmlDeviceGetUUID,nvmlDeviceGetTemperature,nvmlDeviceGetPowerUsage,nvmlDeviceGetUtilizationRates,nvmlDeviceGetComputeRunningProcesses.nvmlDeviceGetCpuAffinity— like NVML, a Linux-only capability; it raisesNVMLError_NotSupportedwhere AMD SMI cannot provide it.NVMLErrorand the per-code subclasses consumers commonly catch (e.g.NVMLError_NotSupported), plus theNVML_*status and selector constants.
Note
ROCm has no Multi-Instance GPU (MIG) concept. The MIG-related
entry points (nvmlDeviceIsMigDeviceHandle,
nvmlDeviceGetMigMode, nvmlDeviceGetMaxMigDeviceCount, …)
are present and degrade gracefully: MIG always reports disabled and
requests for MIG device handles raise NVMLError_NotSupported.
1import pynvml
2
3
4def _gib(num_bytes):
5 return num_bytes / (1024**3)
6
7
8pynvml.nvmlInit()
9try:
10 count = pynvml.nvmlDeviceGetCount()
11 print(f"NVML reports {count} device(s)")
12
13 for index in range(count):
14 handle = pynvml.nvmlDeviceGetHandleByIndex(index)
15
16 name = pynvml.nvmlDeviceGetName(handle)
17 if isinstance(
18 name, bytes
19 ): # upstream pynvml returns bytes on older versions
20 name = name.decode("utf-8", "replace")
21 uuid = pynvml.nvmlDeviceGetUUID(handle)
22 mem = pynvml.nvmlDeviceGetMemoryInfo(handle)
23
24 print(f"device {index}: {name}")
25 print(f" uuid: {uuid}")
26 print(
27 f" memory: {_gib(mem.used):.2f} / {_gib(mem.total):.2f} GiB used"
28 )
29
30 # Telemetry that may be unsupported on some platforms/drivers; NVML
31 # signals that with NVMLError_NotSupported, which we treat as "n/a".
32 try:
33 temp = pynvml.nvmlDeviceGetTemperature(
34 handle, pynvml.NVML_TEMPERATURE_GPU
35 )
36 print(f" temp: {temp} C")
37 except pynvml.NVMLError_NotSupported:
38 print(" temp: n/a")
39
40 try:
41 util = pynvml.nvmlDeviceGetUtilizationRates(handle)
42 print(f" util: gpu {util.gpu}% / mem {util.memory}%")
43 except pynvml.NVMLError_NotSupported:
44 print(" util: n/a")
45
46 try:
47 power_w = pynvml.nvmlDeviceGetPowerUsage(handle) / 1000.0
48 print(f" power: {power_w:.1f} W")
49 except pynvml.NVMLError_NotSupported:
50 print(" power: n/a")
51finally:
52 pynvml.nvmlShutdown()
53
54print("ok")
See also
The full API reference for the shim is at pynvml.
NVTX compatibility shim (nvtx)#
What will I learn?
That
import nvtxkeeps working unchanged on AMD GPUs.Which part of the NVTX surface is faithfully backed by ROCTX and which parts degrade because ROCTX cannot express them.
The hip-python-interop wheel installs a top-level nvtx module:
a compatibility shim for the NVTX Python API backed by ROCTX via the
high-level rocm.bindings.roctx bindings. Code that already
annotates ranges and markers with nvtx — for example HIP ports
of RAPIDS-style projects — can keep calling nvtx unmodified on
AMD hardware. Profile the annotated program with a ROCm-aware tool
(rocprof-compute) instead of Nsight Systems.
Note
This shim is a fresh, MIT-licensed re-implementation of the nvtx
Python surface. It is not a fork of the upstream (Apache-2.0)
nvtx package. Because it is backed by ROCTX, the interop wheel
pulls in rocm-bindings-systems (which provides
rocm.bindings.roctx) in addition to rocm-bindings-hip.
The following surface is faithfully backed by ROCTX:
Instantaneous markers:
nvtx.mark(roctxMarkA).Nested, per-thread ranges:
nvtx.push_range/nvtx.pop_range(roctxRangePushA/roctxRangePop).Process ranges that may cross threads:
nvtx.start_range/nvtx.end_range(roctxRangeStartA/roctxRangeStop).nvtx.annotateas both a decorator and a context manager.nvtx.Profileautomatic function annotation (viasys.setprofile/threading.setprofile).nvtx.enabledand theNVTX_DISABLEenvironment variable.
Important
Limitations. ROCTX is a message-only tracing API: it has no
concept of domains, colors, categories, payloads, registered strings
or counters. The corresponding parts of the nvtx API are accepted
for source compatibility but do not behave as they would on
NVIDIA hardware.
Accepted but silently dropped (only the message reaches ROCTX):
domain/nvtx.get_domain/nvtx.Domain— ROCTX has no domains, so every domain routes to the same global ROCTX calls; the domain name has no effect and cross-domain isolation is lost.color(andnvtx.colors.color_to_hex) — no color channel.category/Domain.get_category_id— no category channel.payload— no payload channel.nvtx.RegisteredString/nvtx.EventAttributesand theDomain.get_registered_string/get_event_attributes/set_event_attributeshelpers — lightweight holders only.
Accepted but complete no-ops (record nothing):
Counters:
nvtx.Counter,nvtx.Int64Counter,nvtx.Float64Counter,nvtx.ExtCounter,Domain.get_counter,sample/sample_no_value/batch_submit, andDomain.get_timestamp.nvtx.CounterSemanticsand the enumsnvtx.CounterValueType,nvtx.CounterInterpolation,nvtx.CounterNoValueReasonandnvtx.TimestampType.nvtx.numpy_dtype.
The counter/semantics surface additionally postdates NVTX release-v3 and is provided only as forward-compatible stubs.
To audit whether your code relies on any of the dropped/no-op features
above, enable the shim’s compatibility mode. By default it stays
silent (drop-in behavior); it can instead emit a warning
(nvtx.NvtxCompatWarning) or raise (nvtx.NvtxCompatError) whenever an
unsupported feature or dropped argument is used. Select it with the
HIP_PYTHON_NVTX_COMPAT environment variable (silent / warn /
error) or at runtime:
import nvtx
nvtx.set_compat_mode("error") # or "warn"; or set HIP_PYTHON_NVTX_COMPAT=error
nvtx.mark("checkpoint", color="red") # raises NvtxCompatError (color is dropped)
The checks fire regardless of whether tracing is enabled, so they also flag non-portable usage in CI that runs without a ROCTX runtime.
1import time
2
3import nvtx
4
5
6# `annotate` works as a decorator. `color`/`domain` are accepted for
7# source compatibility but have no effect on ROCTX (message only).
8@nvtx.annotate("work", color="green", domain="demo")
9def do_work():
10 time.sleep(0.01)
11
12
13def main():
14 print(f"nvtx enabled: {nvtx.enabled()}")
15
16 do_work()
17
18 # `annotate` also works as a context manager.
19 with nvtx.annotate("phase", color="blue"):
20 # An instantaneous marker.
21 nvtx.mark("checkpoint")
22 time.sleep(0.01)
23
24 # Manually nested (per-thread) range.
25 nvtx.push_range("manual")
26 time.sleep(0.01)
27 nvtx.pop_range()
28
29 # Process range (may be started/stopped on different threads).
30 range_id = nvtx.start_range("process")
31 time.sleep(0.01)
32 nvtx.end_range(range_id)
33
34 # Automatic function annotation for a code region.
35 profiler = nvtx.Profile()
36 profiler.enable()
37 do_work()
38 profiler.disable()
39
40 # NOTE: counters have no ROCTX equivalent and are no-ops in this shim.
41 domain = nvtx.get_domain("demo")
42 counter = domain.get_counter("loss", float)
43 counter.sample(0.42) # recorded on NVIDIA; no-op on ROCm
44
45 print("ok")
46
47
48if __name__ == "__main__":
49 main()
See also
The full API reference for the shim is at nvtx.
cuda.core compatibility shim#
What will I learn?
That a minimal
cuda.coreis available on AMD GPUs and what part of its surface is implemented.How to hand streams back and forth between HIP Python and another GPU library through the CUDA stream protocol.
The wheel also provides a minimal cuda.core shim, backed by the
high-level rocm.bindings.hip HIP runtime API. It implements
just enough of the high-level cuda.core surface for HIP ports of
CUDA Python consumers:
Device—device_id,uuid,set_current,sync,create_streamanddefault_stream.Stream— the__cuda_stream__vocabulary type, plushandle,syncandclose.DeviceMemoryResourceandBuffer— stream-ordered allocation from the device’s HIP memory pool.
1from cuda.core import Device, DeviceMemoryResource
2
3dev = Device() # current device; or Device(device_id)
4print(dev.device_id) # HIP device ordinal
5print(dev.uuid) # "GPU-<uuid>" string (via hipDeviceGetUuid)
6
7dev.set_current()
8stream = dev.create_stream() # a non-blocking HIP stream
9
10mr = DeviceMemoryResource(dev.device_id)
11buf = mr.allocate(1024, stream=stream)
12buf.close(stream=stream) # stream-ordered free
13stream.sync()
Streams: interoperating with other libraries#
Device.create_stream accepts any object implementing the CUDA stream
protocol
— a __cuda_stream__ method returning (0, <address>) — which is
how a stream created by RMM, CuPy or Numba is adopted without copying or
recreating it. The wrapper holds a reference to the object it borrowed, so
the underlying stream stays alive, and closing the wrapper releases that
reference rather than destroying the stream. Stream implements the same
protocol in the other direction, so those libraries can consume a HIP
Python stream:
1import rmm.pylibrmm.stream
2from cuda.core import Device
3
4dev = Device()
5dev.set_current()
6
7# RMM -> cuda.core
8cuda_stream = dev.create_stream(rmm.pylibrmm.stream.Stream())
9
10# cuda.core -> RMM
11rmm_stream = rmm.pylibrmm.stream.Stream(cuda_stream)
Because a new stream is associated with whichever device is current, HIP
rather than the shim decides where it lands; create_stream therefore
raises if the Device it was called on is not the current one. Call
Device.set_current first, as the example does.
Device.default_stream returns the NULL stream as a token. HIP has no
equivalent of CUDA Python’s CUDA_PYTHON_CUDA_PER_THREAD_DEFAULT_STREAM
environment variable, so it is always the legacy NULL stream.
Caution
This is not a full port of NVIDIA’s cuda.core /
cuda.core.experimental package; the members listed above are all
that is implemented. Remaining abstractions (Event, Program,
Linker, …) are intentionally out of scope and can be added on
demand. The module’s __version__ names the cuda.core API level
the shim emulates — consumers gate their interoperability paths on it
— and not the HIP Python release it ships in.
See also
The full API reference for the shim is at cuda.core.
Enum Constant Hallucination#
What will I learn?
How I can let HIP Python’s enum error types in the CUDA Python interoperability layer “invent” values for undefined enum constants (that do not conflict with the values of the defined constants).
We use the example below to demonstrate how
you can deal with scenarios where a CUDA Python program, which we want to run
on AMD GPUs, performs an error check that involves enum constants that are
not relevant for HIP programs and/or AMD GPUs. As HIP Python’s routines will
never return these enum constants, it is safe to generate values for them on
the fly. Such behavior can be enabled selectively for CUDA Python
interoperability layer enums — either via the respective environment
variable HIP_PYTHON_{myenumtype}_HALLUCINATE and/or at runtime via the
module variable with the same name in cuda.bindings.driver,
cuda.bindings.runtime, or cuda.bindings.nvrtc.
The example below fails because there are no HIP analogues to the following constants:
cudaError_t.cudaErrorStartupFailurecudaError_t.cudaErrorNotPermittedcudaError_t.cudaErrorSystemNotReadycudaError_t.cudaErrorSystemDriverMismatchcudaError_t.cudaErrorCompatNotSupportedOnDevicecudaError_t.cudaErrorTimeoutcudaError_t.cudaErrorApiFailureBase
However, the example will run successfully if you set the environment
variable HIP_PYTHON_cudaError_t_HALLUCINATE to 1, yes, y, or true
(case does not matter). Alternatively, you could set the module variable
cuda.bindings.runtime.HIP_PYTHON_cudaError_t_HALLUCINATE to True;
see HIP Python-Specific Code Modifications on different ways
to detect HIP Python in order to introduce such a modification to your code.
1from cuda.bindings.runtime import cudaError_t
2
3error_kinds = ( # some of those do not exist in HIP
4 cudaError_t.cudaErrorInitializationError,
5 cudaError_t.cudaErrorInsufficientDriver,
6 cudaError_t.cudaErrorInvalidDeviceFunction,
7 cudaError_t.cudaErrorInvalidDevice,
8 cudaError_t.cudaErrorStartupFailure, # no HIP equivalent
9 cudaError_t.cudaErrorInvalidKernelImage,
10 cudaError_t.cudaErrorAlreadyAcquired,
11 cudaError_t.cudaErrorOperatingSystem,
12 cudaError_t.cudaErrorNotPermitted, # no HIP equivalent
13 cudaError_t.cudaErrorNotSupported,
14 cudaError_t.cudaErrorSystemNotReady, # no HIP equivalent
15 cudaError_t.cudaErrorSystemDriverMismatch, # no HIP equivalent
16 cudaError_t.cudaErrorCompatNotSupportedOnDevice, # no HIP equivalent
17 cudaError_t.cudaErrorDeviceUninitialized,
18 cudaError_t.cudaErrorTimeout, # no HIP equivalent
19 cudaError_t.cudaErrorUnknown,
20 cudaError_t.cudaErrorApiFailureBase, # no HIP equivalent
21)
22
23for err in error_kinds:
24 assert isinstance(err, cudaError_t)
25 assert err != cudaError_t.cudaSuccess
26print("ok")
Caution
Enum constant hallucination should only be used for error return values and not for enum constants that are passed as argument to one of the CUDA Python interoperability layer’s functions.
Basic Usage (Cython)#
What will I learn?
How I can use the CUDA Python interoperability layer’s Cython and Python modules in my code.
You can import the Python objects that you need into your *.pyx file as shown below:
1from cuda.bindings import driver # enum types, enum aliases, fields
2from cuda.bindings import runtime
3from cuda.bindings import nvrtc
4# ...
In the same file, you can also or alternatively cimport the cdef entities
as shown below:
1# The cy*-prefixed modules expose the C declarations and the lazy
2# function loaders that delegate to the underlying HIP/HIPRTC C API.
3from cuda.bindings cimport cydriver
4from cuda.bindings cimport cyruntime
5from cuda.bindings cimport cynvrtc
6# ...
7
8# The non-prefixed modules expose the `cdef class` and `ctypedef`
9# types created per C struct/union/typedef.
10from cuda.bindings cimport driver
11from cuda.bindings cimport runtime
12from cuda.bindings cimport nvrtc
13# ...
Cython Example#
What will I learn?
That I can port CUDA Python Cython code to AMD GPUs with minor modifications.
How I can introduce different compilation paths for HIP Python’s CUDA interoperability layer and CUDA Python.
The example below shows a CUDA Python example that can be
compiled for and run on AMD GPUs. To do so, it is necessary to define the
Cython compile-time flag HIP_PYTHON from within the setup.py
script (see the script below). This will replace the qualified
C++-like enum constant expression
cyruntime.cudaError_t.cudaSuccess by the C-like expression
cyruntime.cudaSuccess (the HIP/HIPRTC Cython enums expose enum
constants directly at module scope, while CUDA Cython enums nest them
inside the enum class).
In the example, the DEF statement and the IF and ELSE statements are
Cython compile time definitions
and conditional statements,
respectively.
1
2cimport cuda.bindings.cyruntime as cyruntime
3
4
5cdef cyruntime.cudaError_t err
6cdef cyruntime.cudaStream_t stream
7DEF num_bytes = 4*100
8cdef char[num_bytes] x_h
9cdef void* x_d
10cdef int x
11
12
13def cuda_check(cyruntime.cudaError_t err):
14 IF HIP_PYTHON: # HIP Python CUDA interop layer Cython interface is used like C API
15 success_status = cyruntime.cudaSuccess
16 ELSE:
17 success_status = cyruntime.cudaError_t.cudaSuccess
18 if err != success_status:
19 raise RuntimeError(f"reason: {err}")
20
21
22IF HIP_PYTHON:
23 print("using HIP Python wrapper for CUDA Python")
24
25cuda_check(cyruntime.cudaStreamCreate(&stream))
26cuda_check(cyruntime.cudaMalloc(&x_d, num_bytes))
27cuda_check(cyruntime.cudaMemcpyAsync(x_d, x_h, num_bytes,
28 cyruntime.cudaMemcpyHostToDevice, stream))
29cuda_check(cyruntime.cudaMemsetAsync(x_d, 0, num_bytes, stream))
30cuda_check(cyruntime.cudaMemcpyAsync(x_h, x_d, num_bytes,
31 cyruntime.cudaMemcpyDeviceToHost, stream))
32cuda_check(cyruntime.cudaStreamSynchronize(stream))
33cuda_check(cyruntime.cudaStreamDestroy(stream))
34
35# deallocate device data
36cuda_check(cyruntime.cudaFree(x_d))
37
38for i in range(0, round(num_bytes/4)):
39 x = (<int*>&x_h[4*i])[0]
40 if x != 0:
41 raise ValueError(f"expected '0' for element {i}, is: '{x}'")
42print("ok")
What is happening?
See HIP Streams for an explanation of a similar HIP Python program’s steps.
The example can be compiled for AMD GPUs via the following
setup.py script,
which specifies compile_time_env=dict(HIP_PYTHON=True) as keyword parameter
of the cythonize call in line
1import os
2
3from Cython.Build import cythonize
4from setuptools import Extension, setup
5
6ROCM_PATH = os.environ.get("ROCM_PATH", "/opt/rocm")
7HIP_PLATFORM = os.environ.get("HIP_PLATFORM", "amd")
8
9if HIP_PLATFORM not in ("amd", "hcc"):
10 raise RuntimeError("Currently only HIP_PLATFORM=amd is supported")
11
12
13def create_extension(name, sources):
14 global ROCM_PATH
15 global HIP_PLATFORM
16 rocm_inc = os.path.join(ROCM_PATH, "include")
17 rocm_lib_dir = os.path.join(ROCM_PATH, "lib")
18 platform = HIP_PLATFORM.upper()
19 cflags = ["-D", f"__HIP_PLATFORM_{platform}__"]
20
21 return Extension(
22 name,
23 sources=sources,
24 include_dirs=[rocm_inc],
25 library_dirs=[rocm_lib_dir],
26 language="c",
27 extra_compile_args=cflags,
28 )
29
30
31setup(
32 ext_modules=cythonize(
33 [
34 create_extension(
35 "cyruntime_cuda_stream", ["cyruntime_cuda_stream.pyx"]
36 ),
37 create_extension(
38 "cyruntime_cuda_stream_with_cuda_bindings",
39 ["cyruntime_cuda_stream_with_cuda_bindings.pyx"],
40 ),
41 ],
42 compiler_directives=dict(language_level=3),
43 compile_time_env=dict(HIP_PYTHON=True),
44 )
45)
For your convenience, you can use the Makefile below
to build a Cython module in-place (via make build) and run the code (by
importing the module via make run).
1PYTHON ?= python3
2
3.PHONY: build run clean
4
5build:
6 $(PYTHON) setup.py build_ext --inplace
7run: build
8 $(PYTHON) -c "import cyruntime_cuda_stream"
9 $(PYTHON) -c "import cyruntime_cuda_stream_with_cuda_bindings"
10clean:
11 rm -rf *.so *.c build/
HIP Python-Specific Code Modifications#
What will I learn?
That I can use HIP objects (via member variables) when
importing the CUDA Python interoperability layer’s Python modules.That I can access HIP enum constants also via their CUDA interoperability layer type.
That I can directly use HIP definitions too when
cimporting the CUDA Python interoperability layer’s Cython modules.
In scenarios where the HIP Python Python or Cython code will need to diverge
from the original CUDA Python code, e.g. due to differences in a signature,
we can directly access the underlying HIP Python Python modules from the
CUDA interoperability layer’s Python modules. Each of
cuda.bindings.driver, cuda.bindings.runtime, and
cuda.bindings.nvrtc exposes the following module-level
attributes when served by HIP Python’s interop layer:
HIP_PYTHON— the literalTrue. Absent when the user is running NVIDIA’s stockcuda-pythonpackage instead.hip_python_mod— a reference to the underlying HIP Python module (rocm.bindings.hipfordriver/runtime,rocm.bindings.hiprtcfornvrtc).hip— same module aship_python_mod, exposed under the short name on thedriverandruntimemodules. Not exposed onnvrtc(which useshiprtcinstead — see below).hiprtc— same module aship_python_mod, exposed under the short name onnvrtc. Not exposed ondriver/runtime.
Use hasattr() (or __dict__ membership) to test for these.
Module-level in does not work — Python modules are not
iterable, so "HIP_PYTHON" in driver raises TypeError.
1from cuda.bindings import driver # or runtime; or nvrtc
2
3# Preferred test:
4if getattr(driver, "HIP_PYTHON", False):
5 # We are running on HIP Python's interop layer.
6 hip = driver.hip # or driver.hip_python_mod (same module)
7 # ... use HIP-only APIs as needed ...
8
9# Equivalent forms:
10if hasattr(driver, "HIP_PYTHON"):
11 ...
12if "HIP_PYTHON" in driver.__dict__:
13 ...
14
15# For `nvrtc`, the underlying module is exposed as `hiprtc` (no
16# `hip` attribute), but `hip_python_mod` works on all three modules:
17from cuda.bindings import nvrtc
18if getattr(nvrtc, "HIP_PYTHON", False):
19 hiprtc = nvrtc.hiprtc # or nvrtc.hip_python_mod (same module)
Moreover, the interoperability layer’s Python enum types also contain all the enum constants of their HIP analogue as shown in the snippet below.
1# [...]
2class CUmemorytype(hip._hipMemoryType__Base,metaclass=_CUmemorytype_EnumMeta):
3 hipMemoryTypeHost = rocm.bindings.cyhip.hipMemoryTypeHost
4 CU_MEMORYTYPE_HOST = rocm.bindings.cyhip.hipMemoryTypeHost
5 cudaMemoryTypeHost = rocm.bindings.cyhip.hipMemoryTypeHost
6 hipMemoryTypeDevice = rocm.bindings.cyhip.hipMemoryTypeDevice
7 CU_MEMORYTYPE_DEVICE = rocm.bindings.cyhip.hipMemoryTypeDevice
8 cudaMemoryTypeDevice = rocm.bindings.cyhip.hipMemoryTypeDevice
9 hipMemoryTypeArray = rocm.bindings.cyhip.hipMemoryTypeArray
10 CU_MEMORYTYPE_ARRAY = rocm.bindings.cyhip.hipMemoryTypeArray
11 hipMemoryTypeUnified = rocm.bindings.cyhip.hipMemoryTypeUnified
12 CU_MEMORYTYPE_UNIFIED = rocm.bindings.cyhip.hipMemoryTypeUnified
13 hipMemoryTypeManaged = rocm.bindings.cyhip.hipMemoryTypeManaged
14 cudaMemoryTypeManaged = rocm.bindings.cyhip.hipMemoryTypeManaged
15# [...]
In the cy-prefixed Cython declaration files
(cuda.bindings.cydriver.pxd, cuda.bindings.cyruntime.pxd, and
cuda.bindings.cynvrtc.pxd), you will further find that the
HIP functions and union/struct types are directly included too:
1# [...]
2from rocm.bindings.cyhip cimport hipDeviceProp_t
3from rocm.bindings.cyhip cimport hipDeviceProp_t as cudaDeviceProp
4# [...]
5from rocm.bindings.cyhip cimport hipMemcpy
6from rocm.bindings.cyhip cimport hipMemcpy as cudaMemcpy
7# [...]
In the Cython declaration files without cy-prefix
(cuda.bindings.driver.pxd, cuda.bindings.runtime.pxd, and
cuda.bindings.nvrtc.pxd), you will discover that the original HIP types
(only those derived from unions and structs) are cimported too and
that the CUDA interoperability layer types are made subclasses of the
respective HIP type; see the example below. This allows
to pass them to the CUDA interoperability layer’s Python functions, i.e., the
aliased HIP Python functions.
1# [...]
2from rocm.bindings.hip cimport hipKernelNodeParams # here
3cdef class CUDA_KERNEL_NODE_PARAMS(hipKernelNodeParams):
4 pass
5cdef class CUDA_KERNEL_NODE_PARAMS_st(hipKernelNodeParams):
6 pass
7cdef class CUDA_KERNEL_NODE_PARAMS_v1(hipKernelNodeParams):
8 pass
9cdef class cudaKernelNodeParams(hipKernelNodeParams):
10 pass
11# [...]