Basic Usage and Examples#
2026-08-31
60 min read
Advanced Micro Devices, Inc.
This chapter explains how to use HIP Python’s main interfaces. The usage of the CUDA® interoperability layer is discussed in a separate chapter. We first aim to give an introduction to the Python API of HIP Python by means of basic examples before discussing the Cython API in the last sections of this chapter.
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.
Basic Usage (Python)#
What will I learn?
How to use HIP Python modules in your Python code.
After installing the HIP Python package hip-python, you can import the individual
modules that you need as shown below:
1from hip import hip
2from hip import hiprtc
3# ...
And you are ready to go!
Note
The from hip import hip (and friends) imports continue to
work — they are served by the hip-python package, which
provides the hip.* namespace as an alias of the
rocm.bindings.* modules. New code should prefer
from rocm.bindings import hip (or
import rocm.bindings.hip as hip) directly: the modern style
is more explicit about which package supplies the symbol and
matches the per-package layout used throughout the rest of the
documentation. The CUDA interop layer similarly prefers
from cuda.bindings import driver, runtime, nvrtc.
1from rocm.bindings import hip
2from rocm.bindings import hiprtc
3# or
4import rocm.bindings.hip as hip
5import rocm.bindings.hiprtc as hiprtc
Both styles are supported and not deprecated; the
rocm.bindings.* style is more explicit about which package
supplies the symbol and matches the modern per-package layout
used by every example in this guide.
Obtaining Device Properties#
What will I learn?
How I can obtain device attributes/properties via
hipGetDeviceProperties.How I can obtain device attributes/properties via
hipDeviceGetAttribute.
Obtaining device properties such as the architecture or the number of compute units is important for many applications.
Via hipGetDeviceProperties#
A number of device properties can be obtained via the
hipDeviceProp_t object. The example below obtains it as the return
value of the hipGetDeviceProperties call (line 21); the second
argument (0) is the device number.
Running the example below will print out the
values of all queried device properties before the program eventually prints
"ok" and quits.
Note
The hip_check routine in the snippet unpacks the result tuple – HIP Python
routines always return a tuple, then checks the therein contained error code
(first argument), and finally returns the rest of the tuple – either as
single value or tuple sans error code. Such error check routines will be used
throughout this and the following sections.
1from rocm.bindings import hip
2
3
4def hip_check(call_result):
5 if isinstance(call_result, tuple):
6 err = call_result[0]
7 result = call_result[1:]
8 if len(result) == 1:
9 result = result[0]
10 else:
11 # Single-output functions (e.g. hipMemcpy after the with-nogil
12 # codegen refactor) return the bare hipError_t enum, not a
13 # 1-tuple. Treat that as an empty-result call.
14 err = call_result
15 result = ()
16 if isinstance(err, hip.hipError_t) and err != hip.hipError_t.hipSuccess:
17 raise RuntimeError(str(err))
18 return result
19
20
21props = hip_check(hip.hipGetDeviceProperties(0))
22
23for attrib in sorted(props.PROPERTIES()):
24 print(f"props.{attrib}={getattr(props,attrib)}")
25print("ok")
Via hipDeviceGetAttribute#
You can also obtain some of the properties that appeared in the
previous example plus a number of additional
properties via the hipDeviceGetAttribute routine as shown in the
example below (line 32). The property to query
is passed as first argument, as an enum constant of type
hipDeviceAttribute_t, and the device number as second argument.
The attribute is an integer, which the routine returns next to the status
code; there is no caller-supplied ctypes.c_int to pass in.
Running this example will print out the values of all queried device
attributes before the program prints "ok" and quits.
1from rocm.bindings import hip
2
3
4def hip_check(call_result):
5 if isinstance(call_result, tuple):
6 err = call_result[0]
7 result = call_result[1:]
8 if len(result) == 1:
9 result = result[0]
10 else:
11 # Single-output functions (e.g. hipMemcpy after the with-nogil
12 # codegen refactor) return the bare hipError_t enum, not a
13 # 1-tuple. Treat that as an empty-result call.
14 err = call_result
15 result = ()
16 if isinstance(err, hip.hipError_t) and err != hip.hipError_t.hipSuccess:
17 raise RuntimeError(str(err))
18 return result
19
20
21device_num = 0
22
23for attrib in (
24 hip.hipDeviceAttribute_t.hipDeviceAttributeMaxBlockDimX,
25 hip.hipDeviceAttribute_t.hipDeviceAttributeMaxBlockDimY,
26 hip.hipDeviceAttribute_t.hipDeviceAttributeMaxBlockDimZ,
27 hip.hipDeviceAttribute_t.hipDeviceAttributeMaxGridDimX,
28 hip.hipDeviceAttribute_t.hipDeviceAttributeMaxGridDimY,
29 hip.hipDeviceAttribute_t.hipDeviceAttributeMaxGridDimZ,
30 hip.hipDeviceAttribute_t.hipDeviceAttributeWarpSize,
31):
32 value = hip_check(hip.hipDeviceGetAttribute(attrib, device_num))
33 print(f"{attrib.name}: {value}")
34print("ok")
HIP Streams#
What will I learn?
How I can use HIP Python’s
hipStream_tobjects and the associated HIP Python routines.That I can directly pass Python 3
arrayobjects to HIP runtime routines such ashipMemcpyandhipMemcpyAsync.
An important concept in HIP are streams. They allow to overlap host and device work as well as device computations with data movement to or from that same device.
The below example showcases how to use HIP Python’s
hipStream_t objects and the associated HIP Python routines. The
example further demonstrates that you can pass Python 3 array.array
types directly to HIP Python interfaces that expect an host buffer. One
example of such interfaces is hipMemcpyAsync (lines 23 and 29).
1import random
2
3from rocm.bindings import hip
4
5
6def hip_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 functions (e.g. hipMemcpy after the with-nogil
14 # codegen refactor) return the bare hipError_t enum, not a
15 # 1-tuple. Treat that as an empty-result call.
16 err = call_result
17 result = ()
18 if isinstance(err, hip.hipError_t) and err != hip.hipError_t.hipSuccess:
19 raise RuntimeError(str(err))
20 return result
21
22
23# inputs
24n = 100
25x_h = array.array("i", [int(random.random() * 10) for i in range(0, n)])
26num_bytes = x_h.itemsize * len(x_h)
27x_d = hip_check(hip.hipMalloc(num_bytes))
28
29stream = hip_check(hip.hipStreamCreate())
30hip_check(
31 hip.hipMemcpyAsync(
32 x_d, x_h, num_bytes, hip.hipMemcpyKind.hipMemcpyHostToDevice, stream
33 )
34)
35hip_check(hip.hipMemsetAsync(x_d, 0, num_bytes, stream))
36hip_check(
37 hip.hipMemcpyAsync(
38 x_h, x_d, num_bytes, hip.hipMemcpyKind.hipMemcpyDeviceToHost, stream
39 )
40)
41hip_check(hip.hipStreamSynchronize(stream))
42hip_check(hip.hipStreamDestroy(stream))
43
44# deallocate device data
45hip_check(hip.hipFree(x_d))
46
47for i, x in enumerate(x_h):
48 if x != 0:
49 raise ValueError(f"expected '0' for element {i}, is: '{x}'")
50print("ok")
What is happening?
A host buffer is filled with random numbers (line 18) before it is asynchronously copied to the device (line 23), where a asynchronous
hipMemsetAsync(same stream) resets all bytes to0(line 28).An asynchronous memcpy (same stream) is then issued to copy the device data back to the host (line 29). All operations within the stream are executed in order.
As the
~Asyncoperations are non-blocking, the host waits viahipStreamSynchronizeuntil operations in the stream have been completed (line 34) before destroying the stream (line 35).Eventually the program deallocates device data via
hipFreeand checks if all bytes in the host buffer are now set to0. If so, it quits with an “ok”.
Launching Kernels#
What will I learn?
How I can compile a HIP C++ kernel at runtime via
hiprtcCompileProgram.How I can launch kernels via
hipModuleLaunchKernel.
HIP Python does not provide the necessary infrastructure to express device code
in native Python. However, you can compile and launch kernels from within
Python code via the just-in-time (JIT) compilation interface provided by HIP
Python module hiprtc together with the kernel launch routines
provided by HIP Python module hip. The
example below demonstrates how to do so.
1from rocm.bindings import hip, hiprtc
2
3
4def hip_check(call_result):
5 if isinstance(call_result, tuple):
6 err = call_result[0]
7 result = call_result[1:]
8 if len(result) == 1:
9 result = result[0]
10 else:
11 # Single-output funcs (e.g. hipMemcpy after the with-nogil
12 # codegen refactor) return the bare hipError_t enum, not a
13 # 1-tuple. Treat that as an empty-result call.
14 err = call_result
15 result = ()
16 if isinstance(err, hip.hipError_t) and err != hip.hipError_t.hipSuccess:
17 raise RuntimeError(str(err))
18 elif (
19 isinstance(err, hiprtc.hiprtcResult)
20 and err != hiprtc.hiprtcResult.HIPRTC_SUCCESS
21 ):
22 raise RuntimeError(str(err))
23 return result
24
25
26source = """\
27extern "C" __global__ void print_tid() {
28 printf("tid: %d\\n", (int) threadIdx.x);
29}
30"""
31
32prog = hip_check(hiprtc.hiprtcCreateProgram(source, "print_tid", 0, [], []))
33
34props = hip_check(hip.hipGetDeviceProperties(0))
35arch = props.gcnArchName
36
37print(f"Compiling kernel for {arch}")
38
39cflags = ["--offload-arch=" + arch]
40(err,) = hiprtc.hiprtcCompileProgram(prog, len(cflags), cflags)
41if err != hiprtc.hiprtcResult.HIPRTC_SUCCESS:
42 log_size = hip_check(hiprtc.hiprtcGetProgramLogSize(prog))
43 log = bytearray(log_size)
44 hip_check(hiprtc.hiprtcGetProgramLog(prog, log))
45 raise RuntimeError(log.decode())
46code_size = hip_check(hiprtc.hiprtcGetCodeSize(prog))
47code = bytearray(code_size)
48hip_check(hiprtc.hiprtcGetCode(prog, code))
49module = hip_check(hip.hipModuleLoadData(code))
50kernel = hip_check(hip.hipModuleGetFunction(module, "print_tid"))
51#
52hip_check(
53 hip.hipModuleLaunchKernel(
54 kernel,
55 *(1, 1, 1), # grid
56 *(32, 1, 1), # block
57 sharedMemBytes=0,
58 stream=None,
59 kernelParams=None,
60 extra=None,
61 )
62)
63
64hip_check(hip.hipDeviceSynchronize())
65hip_check(hip.hipModuleUnload(module))
66hip_check(hiprtc.hiprtcDestroyProgram(prog.createRef()))
67
68print("ok")
What is happening?
In the example, the kernel
print_tiddefined within the stringsourcesimply prints the block-local thread ID (threadIDx.x) for every thread running the kernel (lines 27-30).A program
progis then created in line 32 viahiprtcCreateProgram, where we passsourceas first argument, we further give the program a name, specify zero headers and include names (last three arguments). String arguments like these accept a plainstr; see CStr.Next we query the architecture name via
hipGetDeviceProperties(more details: Obtaining Device Properties) and use it in lines 39-40, where we specify compile flags (cflags) and compileprogviahiprtcCompileProgram. In case of a failure, we obtain the program log and raise it asRuntimeError.In case of success, we query the code size via
hiprtcGetCodeSize, create a buffer with that information, and then copy the code into this buffer viahiprtcGetCode. Afterwards, we load the code asmoduleviahipModuleLoadDataand then obtain our device kernel with name"print_tid"from it viahipModuleGetFunction.This object is then passed as first argument to the
hipModuleLaunchKernelroutine, followed by the usual grid and block dimension triples, the size of the required shared memory, and stream to use (Nonemeans the null stream). The latter two arguments,kernelParamsandextra, can be used for passing kernel arguments. We will take a look how to pass kernel arguments viaextrain the next section.After the kernel launch, the host waits on completion via
hipDeviceSynchronizeand then unloads the code module again viahipModuleUnloadbefore quitting with an"ok".
Kernels with Arguments#
What will I learn?
How I can pass arguments to hipModuleLaunchKernel.
One of the difficulties that programmers face when attempting to launch
kernels via hipModuleLaunchKernel is passing arguments to the
kernels. When using the extra argument, the kernel arguments must be aligned
in a certain way. In C/C++ programs, one can simply put all arguments into a
struct and let the compiler take care of the argument alignment. Similarly,
one could create a ctypes.Structure in python to do the same.
However, we do not want to oblige HIP Python users with creating such glue
code. Instead, users can directly pass a list or tuple of
arguments to the hipModuleLaunchKernel. The entries of these
objects must either be of type DeviceArray (or can be converted to
DeviceArray) or one of the ctypes types.
The former are typically the result of a hipMalloc call (or
similar memory allocation routines). Please also see Adapter Types
for details on what other types can be converted to DeviceArray.
The ctypes types are typically used to convert a scalar of the
python bool, int, and float scalar types to a
fixed precision.
The below example demonstrates the usage of
hipModuleLaunchKernel by means of a simple kernel, which scales a
vector by a factor. Here, we pass multiple arguments that require different
alignments to the aforementioned routine in lines 95-102. We insert some
additional unused* arguments into the extra tuple to stress the
argument buffer allocator. Note the ctypes object construction for
scalars and the direct passing of the device array x_d. Compare the argument
list with the signature of the kernel defined in line 31. The example also
introduces HIP Python’s dim3 struct (default value per dimension
is 1), which can be unpacked just like a tuple or list.
1import ctypes
2import math
3import random
4
5from rocm.bindings import hip, hiprtc
6
7
8def hip_check(call_result):
9 if isinstance(call_result, tuple):
10 err = call_result[0]
11 result = call_result[1:]
12 if len(result) == 1:
13 result = result[0]
14 else:
15 # Single-output funcs (e.g. hipMemcpy after the with-nogil
16 # codegen refactor) return the bare hipError_t enum, not a
17 # 1-tuple. Treat that as an empty-result call.
18 err = call_result
19 result = ()
20 if isinstance(err, hip.hipError_t) and err != hip.hipError_t.hipSuccess:
21 raise RuntimeError(str(err))
22 elif (
23 isinstance(err, hiprtc.hiprtcResult)
24 and err != hiprtc.hiprtcResult.HIPRTC_SUCCESS
25 ):
26 raise RuntimeError(str(err))
27 return result
28
29
30source = """\
31extern "C" __global__ void scale_vector(float factor, int n, short unused1, int unused2, float unused3, float *x) {
32 int tid = threadIdx.x + blockIdx.x * blockDim.x;
33 if ( tid == 0 ) {
34 printf("tid: %d, factor: %f, x*: %lu, n: %lu, unused1: %d, unused2: %d, unused3: %f\\n",tid,factor,x,n,(int) unused1,unused2,unused3);
35 }
36 if (tid < n) {
37 x[tid] *= factor;
38 }
39}
40"""
41
42prog = hip_check(hiprtc.hiprtcCreateProgram(source, "scale_vector", 0, [], []))
43
44props = hip_check(hip.hipGetDeviceProperties(0))
45arch = props.gcnArchName
46
47print(f"Compiling kernel for {arch}")
48
49cflags = ["--offload-arch=" + arch]
50(err,) = hiprtc.hiprtcCompileProgram(prog, len(cflags), cflags)
51if err != hiprtc.hiprtcResult.HIPRTC_SUCCESS:
52 log_size = hip_check(hiprtc.hiprtcGetProgramLogSize(prog))
53 log = bytearray(log_size)
54 hip_check(hiprtc.hiprtcGetProgramLog(prog, log))
55 raise RuntimeError(log.decode())
56code_size = hip_check(hiprtc.hiprtcGetCodeSize(prog))
57code = bytearray(code_size)
58hip_check(hiprtc.hiprtcGetCode(prog, code))
59module = hip_check(hip.hipModuleLoadData(code))
60kernel = hip_check(hip.hipModuleGetFunction(module, "scale_vector"))
61
62# kernel launch
63
64# - inputs
65n = 100
66x_h = array.array("f", [random.random() for i in range(0, n)])
67num_bytes = x_h.itemsize * len(x_h)
68x_d = hip_check(hip.hipMalloc(num_bytes))
69print(f"{hex(int(x_d))=}")
70
71# - upload host data
72hip_check(
73 hip.hipMemcpy(x_d, x_h, num_bytes, hip.hipMemcpyKind.hipMemcpyHostToDevice)
74)
75
76factor = 1.23
77
78# - expected result
79x_expected = [a * factor for a in x_h]
80
81block = hip.dim3(x=32)
82grid = hip.dim3(math.ceil(n / block.x))
83
84# - launch
85hip_check(
86 hip.hipModuleLaunchKernel(
87 kernel,
88 *grid,
89 *block,
90 sharedMemBytes=0,
91 stream=None,
92 kernelParams=None,
93 extra=(
94 ctypes.c_float(factor), # 4 bytes
95 ctypes.c_int(n), # 8 bytes
96 ctypes.c_short(5), # unused1, 10 bytes
97 ctypes.c_int(2), # unused2, 16 bytes (+2 padding bytes)
98 ctypes.c_float(5.6), # unused3 20 bytes
99 x_d, # 32 bytes (+4 padding bytes)
100 ),
101 )
102)
103
104# copy result back
105hip_check(
106 hip.hipMemcpy(x_h, x_d, num_bytes, hip.hipMemcpyKind.hipMemcpyDeviceToHost)
107)
108
109for i, x_h_i in enumerate(x_h):
110 if not math.isclose(x_h_i, x_expected[i], rel_tol=1e-6):
111 raise RuntimeError(
112 f"values do not match, {x_h[i]=} vs. {x_expected[i]=}, {i=}"
113 )
114
115hip_check(hip.hipFree(x_d))
116
117hip_check(hip.hipModuleUnload(module))
118hip_check(hiprtc.hiprtcDestroyProgram(prog.createRef()))
119
120print("ok")
What is happening?
See the previous section Launching Kernels for a textual description of the main steps.
hipBLAS and NumPy Interoperability#
What will I learn?
How I can use HIP Python’s
hipblasmodule.That I can pass
numpyarrays to HIP runtime routines such ashipMemcpyandhipMemcpyAsync.
This example demonstrates how to initialize and use HIP
Python’s hipblas module. Furthermore, it shows that you can simply
pass numpy arrays to HIP runtime routines such as
hipMemcpy and hipMemcpyAsync. This works because some
of HIP Python’s interfaces support automatic conversion from various different
types — in particular such types that implement the
Python buffer protocol.
The numpy arrays implement the Python buffer protocol and
thus can be directly passed to those interfaces.
1import ctypes
2
3import numpy as np
4from rocm.bindings import hip, hipblas
5
6
7def hip_check(call_result):
8 if isinstance(call_result, tuple):
9 err = call_result[0]
10 result = call_result[1:]
11 if len(result) == 1:
12 result = result[0]
13 else:
14 # Single-output funcs (e.g. hipMemcpy after the with-nogil
15 # codegen refactor) return the bare hipError_t enum, not a
16 # 1-tuple. Treat that as an empty-result call.
17 err = call_result
18 result = ()
19 if isinstance(err, hip.hipError_t) and err != hip.hipError_t.hipSuccess:
20 raise RuntimeError(str(err))
21 elif (
22 isinstance(err, hipblas.hipblasStatus_t)
23 and err != hipblas.hipblasStatus_t.HIPBLAS_STATUS_SUCCESS
24 ):
25 raise RuntimeError(str(err))
26 return result
27
28
29num_elements = 100
30
31# input data on host
32alpha = ctypes.c_float(2)
33x_h = np.random.rand(num_elements).astype(dtype=np.float32)
34y_h = np.random.rand(num_elements).astype(dtype=np.float32)
35
36# expected result
37y_expected = alpha * x_h + y_h
38
39# device vectors
40num_bytes = num_elements * np.dtype(np.float32).itemsize
41x_d = hip_check(hip.hipMalloc(num_bytes))
42y_d = hip_check(hip.hipMalloc(num_bytes))
43
44# copy input data to device
45hip_check(
46 hip.hipMemcpy(x_d, x_h, num_bytes, hip.hipMemcpyKind.hipMemcpyHostToDevice)
47)
48hip_check(
49 hip.hipMemcpy(y_d, y_h, num_bytes, hip.hipMemcpyKind.hipMemcpyHostToDevice)
50)
51
52# call hipblasSaxpy + initialization & destruction of handle
53handle = hip_check(hipblas.hipblasCreate())
54hip_check(
55 hipblas.hipblasSaxpy(
56 handle, num_elements, ctypes.addressof(alpha), x_d, 1, y_d, 1
57 )
58)
59hip_check(hipblas.hipblasDestroy(handle))
60
61# copy result (stored in y_d) back to host (store in y_h)
62hip_check(
63 hip.hipMemcpy(y_h, y_d, num_bytes, hip.hipMemcpyKind.hipMemcpyDeviceToHost)
64)
65
66# compare to expected result
67if np.allclose(y_expected, y_h):
68 print("ok")
69else:
70 print("FAILED")
71# print(f"{y_h=}")
72# print(f"{y_expected=}")
73
74# clean up
75hip_check(hip.hipFree(x_d))
76hip_check(hip.hipFree(y_d))
What is happening?
We initialize two
float32-typednumpyarraysx_handy_hon the host and fill them with random data (lines 34-35).We compute the expected result on the host via
numpyarray operations (line 38).We allocate device analogues for
x_handy_h(lines 42-43) and copy the host data over (lines 46-51). Note that we can directly pass thenumpyarraysx_handy_htohipMemcpy.Before being able to call one of the compute routines of
hipblas, it’s necessary to create ahipblashandle viahipblasCreatethat will be passed to everyhipblasroutine as first argument (line 54).In lines 55-59 follows the call to
hipblasSaxpy, where we pass the handle as first argument and the address of hostctypes.c_floatvariablealphaas third argument.In line 60 the handle is destroyed via
hipblasDestroybecause it is not needed anymore.The device data is downloaded in lines 63-65, where we pass
numpyarrayy_has destination array.We compare the expected host result with the downloaded device result (lines 68-71) and print
"ok"if all is fine.
Linear Algebra with hipSOLVER#
What will I learn?
How I can create a
hipsolverhandle viahipsolverCreate.How I can query the workspace size and compute an LU factorization on the GPU via
hipsolverDgetrf_bufferSizeandhipsolverDgetrf.
This example computes the LU factorization of a
small dense matrix on the GPU using HIP Python’s hipsolver
module. Like LAPACK, hipSOLVER expects column-major matrices, so the
input is a Fortran-ordered numpy array that we pass directly to
hipMemcpy. The factorization computes \(PA = LU\); the
example reconstructs \(LU\) on the host with numpy and checks
it against the row-pivoted input, printing "ok" on success.
Note that hipsolverDgetrf_bufferSize returns the required
workspace size (lwork, in bytes) directly as a second return value
next to the status — HIP Python models such callee-written scalar output
pointers as return values rather than as caller-supplied buffers.
1import numpy as np
2from rocm.bindings import hip, hipsolver
3
4
5def hip_check(call_result):
6 if isinstance(call_result, tuple):
7 err = call_result[0]
8 result = call_result[1:]
9 if len(result) == 1:
10 result = result[0]
11 else:
12 err = call_result
13 result = ()
14 if isinstance(err, hip.hipError_t) and err != hip.hipError_t.hipSuccess:
15 raise RuntimeError(str(err))
16 elif (
17 isinstance(err, hipsolver.hipsolverStatus_t)
18 and err != hipsolver.hipsolverStatus_t.HIPSOLVER_STATUS_SUCCESS
19 ):
20 raise RuntimeError(str(err))
21 return result
22
23
24# input matrix on the host, column-major (Fortran order); same values as
25# the upstream C sample.
26m = n = lda = 3
27A = np.asfortranarray(
28 np.array(
29 [[12.0, -51.0, 4.0], [6.0, 167.0, -68.0], [-4.0, 24.0, -41.0]],
30 dtype=np.float64,
31 )
32)
33A_orig = A.copy()
34size_piv = min(m, n)
35
36# allocate device memory: factored matrix, pivot indices and the info flag.
37dA = hip_check(hip.hipMalloc(A.nbytes))
38dIpiv = hip_check(hip.hipMalloc(size_piv * np.dtype(np.int32).itemsize))
39dInfo = hip_check(hip.hipMalloc(np.dtype(np.int32).itemsize))
40
41# copy the input matrix to the device.
42hip_check(
43 hip.hipMemcpy(dA, A, A.nbytes, hip.hipMemcpyKind.hipMemcpyHostToDevice)
44)
45
46# create the solver handle and query + allocate the workspace. `lwork` (the
47# workspace size in bytes) is returned by the buffer-size query.
48handle = hip_check(hipsolver.hipsolverCreate())
49lwork = hip_check(hipsolver.hipsolverDgetrf_bufferSize(handle, m, n, dA, lda))
50dWork = hip_check(hip.hipMalloc(lwork))
51
52# compute the LU factorization in place on the GPU.
53hip_check(
54 hipsolver.hipsolverDgetrf(
55 handle, m, n, dA, lda, dWork, lwork, dIpiv, dInfo
56 )
57)
58
59# copy the factored matrix, pivots and info flag back to the host.
60LU = np.zeros((m, n), dtype=np.float64, order="F")
61ipiv = np.zeros(size_piv, dtype=np.int32)
62info = np.zeros(1, dtype=np.int32)
63hip_check(
64 hip.hipMemcpy(LU, dA, LU.nbytes, hip.hipMemcpyKind.hipMemcpyDeviceToHost)
65)
66hip_check(
67 hip.hipMemcpy(
68 ipiv, dIpiv, ipiv.nbytes, hip.hipMemcpyKind.hipMemcpyDeviceToHost
69 )
70)
71hip_check(
72 hip.hipMemcpy(
73 info, dInfo, info.nbytes, hip.hipMemcpyKind.hipMemcpyDeviceToHost
74 )
75)
76
77# verify: getrf stores unit-lower L (below the diagonal) and upper U (on and
78# above it) in the factored matrix, with PA == L @ U. Rebuild L and U and
79# replay the LAPACK 1-based row pivots on a copy of the original A to form PA.
80L = np.tril(LU, -1) + np.eye(m, n)
81U = np.triu(LU)
82PA = A_orig.copy()
83for i in range(size_piv):
84 p = int(ipiv[i]) - 1 # ipiv is 1-based (LAPACK convention)
85 if p != i:
86 PA[[i, p], :] = PA[[p, i], :]
87
88if info[0] == 0 and np.allclose(PA, L @ U):
89 print("ok")
90else:
91 print("FAILED")
92# print(f"{LU=}")
93# print(f"{ipiv=}")
94
95# clean up
96hip_check(hip.hipFree(dA))
97hip_check(hip.hipFree(dIpiv))
98hip_check(hip.hipFree(dInfo))
99hip_check(hip.hipFree(dWork))
100hip_check(hipsolver.hipsolverDestroy(handle))
What is happening?
We build the input matrix
Aas a Fortran-ordered (column-major)float64numpyarray and keep a copyA_origfor the later check (lines 26-33).We allocate device memory for the factored matrix
dA, the pivot indicesdIpivand the info flagdInfo(lines 37-39), then copy the input matrix over — passing thenumpyarray directly tohipMemcpy(lines 42-44).We create a
hipsolverhandle viahipsolverCreate(line 48) and query the workspace size viahipsolverDgetrf_bufferSize(line 49). The sizelworkis returned by the call, so we allocate the workspacedWorkfrom it (line 50).In lines 53-57 we compute the LU factorization in place with
hipsolverDgetrf, passing the handle, the matrix, the workspace and its size, and the pivot / info outputs.We download the factored matrix, the pivots and the info flag back to the host (lines 60-75).
We rebuild the unit-lower
Land upperUfactors, replay the LAPACK 1-based row pivots on a copy of the original matrix to formPA, and print"ok"if \(PA = LU\) holds (lines 80-91).Finally we free the device buffers and destroy the handle via
hipsolverDestroy.
HIP Python Device Arrays#
What will I learn?
How I can change the shape and datatype of HIP Python’s
DeviceArrayobjects.How I can obtain subarrays from HIP Python’s
DeviceArrayobjects — which are again of that type — via array subscript.
This example demonstrates how to
configure the shape and data typ of a
DeviceArray returned by hipMalloc (and related
routines). It further shows how to retrieve single elements / contiguous
subarrays with respect to the specified type and shape information.
1import ctypes
2
3import numpy as np
4from rocm.bindings import hip, hipblas
5
6verbose = False
7
8
9def hip_check(call_result):
10 if isinstance(call_result, tuple):
11 err = call_result[0]
12 result = call_result[1:]
13 if len(result) == 1:
14 result = result[0]
15 else:
16 # Single-output funcs (e.g. hipMemcpy after the with-nogil
17 # codegen refactor) return the bare hipError_t enum, not a
18 # 1-tuple. Treat that as an empty-result call.
19 err = call_result
20 result = ()
21 if isinstance(err, hip.hipError_t) and err != hip.hipError_t.hipSuccess:
22 raise RuntimeError(str(err))
23 elif (
24 isinstance(err, hipblas.hipblasStatus_t)
25 and err != hipblas.hipblasStatus_t.HIPBLAS_STATUS_SUCCESS
26 ):
27 raise RuntimeError(str(err))
28 return result
29
30
31# init host array and fill with ones
32shape = (3, 20) # shape[1]: inner dim
33x_h = np.ones(shape, dtype="float32")
34num_bytes = x_h.size * x_h.itemsize
35
36# init device array and upload host data
37x_d = hip_check(hip.hipMalloc(num_bytes)).configure(
38 typestr="float32", shape=shape
39)
40hip_check(
41 hip.hipMemcpy(x_d, x_h, num_bytes, hip.hipMemcpyKind.hipMemcpyHostToDevice)
42)
43
44# scale device array entries by row index using hipblasSscal
45handle = hip_check(hipblas.hipblasCreate())
46for r in range(0, shape[0]):
47 row = x_d[r, :] # extract subarray
48 row_len = row.size
49 alpha = ctypes.c_float(r)
50 hip_check(
51 hipblas.hipblasSscal(handle, row_len, ctypes.addressof(alpha), row, 1)
52 )
53 hip_check(hip.hipDeviceSynchronize())
54hip_check(hipblas.hipblasDestroy(handle))
55
56# copy device data back to host
57hip_check(
58 hip.hipMemcpy(x_h, x_d, num_bytes, hip.hipMemcpyKind.hipMemcpyDeviceToHost)
59)
60
61# deallocate device data
62hip_check(hip.hipFree(x_d))
63
64for r in range(0, shape[0]):
65 row_rounded = [round(el) for el in x_h[r, :]]
66 for c, e in enumerate(row_rounded):
67 if e != r:
68 raise ValueError(f"expected '{r}' for element ({r},{c}), is '{e}")
69 if verbose:
70 print("\t".join((str(i) for i in row_rounded)) + "\n")
71print("ok")
What is happening?
A two-dimensional row-major array of size
(3,20)is created on the host. All elements are initialized to1(lines 32-33).A device array with the same number of bytes is created on the device, then reconfigured to have
float32type and the shape of the host array viaconfigure(lines 37-39).The host data is copied to the device array (lines 40-42).
Within a loop over the row indices (index:
r):A pointer to row with index
ris created via array subscript (line 47). This yieldsrow.rowis passed to ahipblasSscalcall that writes indexrto all elements of the row (lines 50-52).
Data is copied back from the device to the host array (lines 57-59).
The device data is deallocated via
hipFree(line 62).Finally, a check is performed on the host if the row values equal the respective row index (lines 64-68). The program quits with
"ok"if all went well.
Note
Please also see Adapter Types for more details on the capabilities
of type DeviceArray and the
CUDA Array interface
that it implements.
Monte Carlo with hipRAND#
What will I learn?
How I can create an
hiprandrandom number generator viahiprandCreateGenerator.How I can generate uniformly-distributed random numbers via
hiprandGenerateUniformDouble.
This example uses hiprand to estimate
\(\pi\) by means of the Monte-Carlo method.
Background
The unit square has the area \(1^2\), while the unit circle has the area \(\pi\,(\frac{1}{2})^2\). Therefore, the ratio between the latter and the former area is \(\frac{\pi}{4}\). Using the Monte-Carlo method, we randomly choose \(N\) \((x,y)\)-coordinates in the unit square. We then estimate the ratio of areas as the ratio between the number of samples located within the unit circle and the total number of samples \(N\). The accuracy of the approach increases with \(N\).
Note
This example was derived from a similar example in the
rocRAND repository on Github.
See this repository for another higher-level interface to hipran and rocrand
(ctypes-based, no Cython interfaces).
1from rocm.bindings import hip, hiprand
2
3
4def hip_check(call_result):
5 if isinstance(call_result, tuple):
6 err = call_result[0]
7 result = call_result[1:]
8 if len(result) == 1:
9 result = result[0]
10 else:
11 # Single-output funcs (e.g. hipMemcpy after the with-nogil
12 # codegen refactor) return the bare hipError_t enum, not a
13 # 1-tuple. Treat that as an empty-result call.
14 err = call_result
15 result = ()
16 if (
17 isinstance(err, hiprand.hiprandStatus)
18 and err != hiprand.hiprandStatus.HIPRAND_STATUS_SUCCESS
19 ):
20 raise RuntimeError(str(err))
21 if isinstance(err, hip.hipError_t) and err != hip.hipError_t.hipSuccess:
22 raise RuntimeError(str(err))
23 return result
24
25
26print("Estimating Pi via the Monte Carlo method:\n")
27
28
29def calculate_pi(n):
30 """Calculate Pi for the given number of samples."""
31 xy = np.empty(shape=(2, n)) # host array, default type is float64
32 gen = hip_check(
33 hiprand.hiprandCreateGenerator(
34 hiprand.hiprandRngType.HIPRAND_RNG_PSEUDO_DEFAULT
35 )
36 )
37 xy_d = hip_check(
38 hip.hipMalloc(xy.size * xy.itemsize)
39 ) # create same size device array
40 hip_check(
41 hiprand.hiprandGenerateUniformDouble(gen, xy_d, xy.size)
42 ) # generate device random numbers
43 hip_check(
44 hip.hipMemcpy(
45 xy,
46 xy_d,
47 xy.size * xy.itemsize,
48 hip.hipMemcpyKind.hipMemcpyDeviceToHost,
49 )
50 ) # copy to host
51 hip_check(hip.hipFree(xy_d)) # free device array
52 hip_check(hiprand.hiprandDestroyGenerator(gen))
53
54 inside = xy[0] ** 2 + xy[1] ** 2 <= 1.0
55 in_xy = xy[:, inside]
56 estimate = 4 * in_xy[0, :].size / n
57 return estimate
58
59
60print("#samples\testimate\trelative error")
61n = 100
62imax = 5
63for i in range(1, imax):
64 n *= 10
65 estimate = calculate_pi(n)
66 print(f"{n:12}\t{estimate:1.9f}\t{abs(estimate-math.pi)/math.pi:1.9f}")
67print("ok")
What is happening?
Within a loop that per iteration multiplies the problem size n by 10
(lines 64-65), we call a function calculate_pi with n as argument, in which:
We first create a two-dimensional host array
xyof typedoublewithnelements (line 31).We then create a
hiprandCreateGeneratorgenerator of typeHIPRAND_RNG_PSEUDO_DEFAULT(lines 32-36).We create a device array
xy_dthat stores the same number of bytes asxy(lines 37-39).We fill
xy_dwith random data viahiprandGenerateUniformDouble(lines 40-42).We then copy to
xyfromxy_dand freexy_d(lines 43-51) and destroy the generator (line 52).We use
numpyarray operations to count the number of random-generated \(x-y\)-coordinates within the unit circle (lines 54-55).Finally, we compute the ratio estimate for the given
nand return it (lines 56-57).
A simple complex FFT with hipFFT#
What will I learn?
How I can create an
hipfft1D plan viahipfftPlan1d.How I can run a complex in-place forward FFT via
hipfftExecZ2Z.
This example demonstrates the usage of HIP Python’s
hipfft library.
We perform a double-complex-to-double-complex in-place forward FFT of a constant time signal \(f(t) = 1-1j\) of which we have \(N\) samples. The resulting FFT coefficients are all zero — aside from the first one, which has the value \(N-Nj\).
1import numpy as np
2from rocm.bindings import hip, hipfft
3
4
5def hip_check(call_result):
6 if isinstance(call_result, tuple):
7 err = call_result[0]
8 result = call_result[1:]
9 if len(result) == 1:
10 result = result[0]
11 else:
12 # Single-output funcs (e.g. hipMemcpy after the with-nogil
13 # codegen refactor) return the bare hipError_t enum, not a
14 # 1-tuple. Treat that as an empty-result call.
15 err = call_result
16 result = ()
17 if isinstance(err, hip.hipError_t) and err != hip.hipError_t.hipSuccess:
18 raise RuntimeError(str(err))
19 if (
20 isinstance(err, hipfft.hipfftResult)
21 and err != hipfft.hipfftResult.HIPFFT_SUCCESS
22 ):
23 raise RuntimeError(str(err))
24 return result
25
26
27# initial data
28N = 100
29hx = np.zeros(N, dtype=np.cdouble)
30hx[:] = 1 - 1j
31
32# copy to device
33dx = hip_check(hip.hipMalloc(hx.size * hx.itemsize))
34hip_check(
35 hip.hipMemcpy(dx, hx, dx.size, hip.hipMemcpyKind.hipMemcpyHostToDevice)
36)
37
38# create plan
39plan = hip_check(hipfft.hipfftPlan1d(N, hipfft.hipfftType.HIPFFT_Z2Z, 1))
40
41# execute plan
42hip_check(
43 hipfft.hipfftExecZ2Z(
44 plan, idata=dx, odata=dx, direction=hipfft.HIPFFT_FORWARD
45 )
46)
47hip_check(hip.hipDeviceSynchronize())
48
49# copy to host and free device data
50hip_check(
51 hip.hipMemcpy(hx, dx, dx.size, hip.hipMemcpyKind.hipMemcpyDeviceToHost)
52)
53hip_check(hip.hipFree(dx))
54
55if not np.isclose(hx[0].real, N) or not np.isclose(hx[0].imag, -N):
56 raise RuntimeError("element 0 must be '{N}-j{N}'.")
57for i in range(1, N):
58 if not np.isclose(abs(hx[i]), 0):
59 raise RuntimeError(f"element {i} must be '0'")
60
61hip_check(hipfft.hipfftDestroy(plan))
62print("ok")
What is happening?
We start with creating the initial data in lines 28-30, where we use
numpyfor convenience.We then create a device array of the same size and copy the device data over (lines 33-36).
We create a plan in line 39, where we specify the number of samples
Nand the the type of the FFT as double-complex-to-double-complex,HIPFFT_Z2Z.Afterwards, we execute the FFT in-place (
idata=dxandodata=dx) and specify that we run an forward FFT,HIPFFT_FORWARD(lines 42-46).The host then waits for completion of all activity on the device before copying data back to the host and freeing the device array (lines 47-53).
Finally, we check if the result is as expected and print
"ok"if that’s the case (lines 55 onward).
A multi-GPU broadcast with RCCL#
What will I learn?
How I can create a multi-GPU communicator via
ncclCommInitAll.How I can destroy a communicator again via
ncclCommDestroy.How I can open and close a communication group via
ncclGroupStartandncclGroupEnd, respectively.How I can perform a broadcast via
ncclBcast.
This example implements a single-node multi-GPU broadcast of a small array from one GPU’s device buffer to that of the other ones.
1import numpy as np
2from rocm.bindings import hip, rccl
3
4
5def hip_check(call_result):
6 if isinstance(call_result, tuple):
7 err = call_result[0]
8 result = call_result[1:]
9 if len(result) == 1:
10 result = result[0]
11 else:
12 # Single-output funcs (e.g. hipMemcpy after the with-nogil
13 # codegen refactor) return the bare hipError_t enum, not a
14 # 1-tuple. Treat that as an empty-result call.
15 err = call_result
16 result = ()
17 if isinstance(err, hip.hipError_t) and err != hip.hipError_t.hipSuccess:
18 raise RuntimeError(str(err))
19 if (
20 isinstance(err, rccl.ncclResult_t)
21 and err != rccl.ncclResult_t.ncclSuccess
22 ):
23 raise RuntimeError(str(err))
24 return result
25
26
27# init the communicators
28num_gpus = hip_check(hip.hipGetDeviceCount())
29comms = np.empty(
30 num_gpus, dtype="uint64"
31) # size of pointer type, such as ncclComm
32devlist = np.array(range(0, num_gpus), dtype="int32")
33hip_check(rccl.ncclCommInitAll(comms, num_gpus, devlist))
34
35# init data on the devices
36N = 4
37ones = np.ones(N, dtype="int32")
38zeros = np.zeros(ones.size, dtype="int32")
39dxlist = []
40for dev in devlist:
41 hip_check(hip.hipSetDevice(dev))
42 dx = hip_check(hip.hipMalloc(ones.size * ones.itemsize)) # items are bytes
43 dxlist.append(dx)
44 hx = ones if dev == 0 else zeros
45 hip_check(
46 hip.hipMemcpy(dx, hx, dx.size, hip.hipMemcpyKind.hipMemcpyHostToDevice)
47 )
48
49# perform a broadcast
50hip_check(rccl.ncclGroupStart())
51for dev in devlist:
52 hip_check(hip.hipSetDevice(dev))
53 hip_check(
54 rccl.ncclBcast(
55 dxlist[dev],
56 N,
57 rccl.ncclDataType_t.ncclInt32,
58 0,
59 int(comms[dev]),
60 None,
61 )
62 )
63 # conversion to Python int is required to not let the numpy datatype to be interpreted as single-element Py_buffer
64hip_check(rccl.ncclGroupEnd())
65
66# download and check the output; confirm all entries are one
67hx = np.empty(N, dtype="int32")
68for dev in devlist:
69 dx = dxlist[dev]
70 hx[:] = 0
71 hip_check(
72 hip.hipMemcpy(hx, dx, dx.size, hip.hipMemcpyKind.hipMemcpyDeviceToHost)
73 )
74 for i, item in enumerate(hx):
75 if item != 1:
76 raise RuntimeError(f"failed for element {i}")
77
78# clean up
79for dx in dxlist:
80 hip_check(hip.hipFree(dx))
81for comm in comms:
82 hip_check(rccl.ncclCommDestroy(int(comm)))
83 # conversion to Python int is required to not let the numpy datatype to be interpreted as single-element Py_buffer
84
85print("ok")
What is happening?
In line 28, we use the device count
num_gpus(viahipGetDeviceCount) to create an array of pointers (same size asunsigned long,dtype="uint64"). This array namedcommsis intended to store a pointer to each device’s communicator.We then create an array of device identifiers (line 32).
We pass both arrays to
ncclCommInitAllas first and last argument, respectively (line 33). The second element is the device count. The aforementioned routine initializes all communicators and writes their address to thecommsarray.In lines 37-47, we create an array
dxon each device of sizeNthat is initialized with zeros on all devices except device0. The latter’s array is filled with ones.We start a communication group in line 50, and then call
ncclBcastper device in lines 53-62. The first argument of the call is per-devicedx, the second the size ofdx. Then follows thencclDataType_t, the root (device0), then the communicator (int(comms[dev])) and finally the stream (None). Castingcomms[dev]tointis required as the result is otherwise interpreted as single-elementPy_bufferby HIP Python’sncclBcastinstead of as an address.In line 64, we close the communication group again.
We download all data to the host per device and check if the elements are set to
1(lines 67-76). Otherwise, a runtime error is emitted.Finally, we clean up by deallocating all device memory (lines 78-79) and destroying the per-device communicators via
ncclCommDestroy(lines 81-83). Note that here again thecommmust be converted tointbefore passing it to the HIP Python routine.
Note
Please also see Adapter Types for more details on automatic type conversions supported by HIP Python’s datatypes.
Copying a File through GPU Memory with hipFile#
What will I learn?
How I can use the high-level
rocm.hipfilewrapper classesDriver,Buffer, andFileHandleas context managers.How I can read a file directly into device memory and write it back out via
FileHandle.read/FileHandle.write.
hipFile (Accelerated I/O Storage) moves data directly between storage and
GPU memory. HIP Python ships two layers for it: the auto-generated
low-level rocm.bindings.hipfile bindings and the high-level,
Pythonic rocm.hipfile wrapper. The example below uses the high-level wrapper to copy a file through a device
buffer and then verifies the round-trip by comparing SHA256 hashes.
Note
hipFile requires the libhipfile.so shared library, which may not be
part of a standard ROCm™ installation (see the note in
the installation chapter). It also issues its
transfers with O_DIRECT, so the scratch files must live on an
O_DIRECT-capable filesystem; set the HIPFILE_TMPDIR environment
variable to such a mount (e.g. an ext4 mount) if the default temp
directory is a tmpfs.
1import hashlib
2import os
3import pathlib
4import tempfile
5
6from rocm.bindings.hip import hipFree, hipMalloc
7from rocm.hipfile import (
8 Buffer,
9 Driver,
10 FileHandle,
11 FileHandleType,
12 get_version,
13)
14
15hipfile_version = get_version()
16print(f"hipFile Version: {hipfile_version}")
17
18# hipFile issues its reads/writes with O_DIRECT, so the scratch files must
19# live on an O_DIRECT-capable filesystem. Default to the system temp dir and
20# allow an override via HIPFILE_TMPDIR (e.g. point at an ext4 mount if the
21# default temp dir is tmpfs).
22scratch_dir = os.environ.get("HIPFILE_TMPDIR") or None
23
24# 2 MiB, block-aligned so the O_DIRECT transfers are valid.
25size = 2 * 1024 * 1024
26
27with tempfile.TemporaryDirectory(dir=scratch_dir) as tmp_dir:
28 input_path = pathlib.Path(tmp_dir) / "random_2MiB.bin"
29 output_path = pathlib.Path(tmp_dir) / "output.bin"
30
31 # Create the random input up front instead of relying on a pre-existing
32 # file, so the example is fully self-contained.
33 input_path.write_bytes(os.urandom(size))
34
35 print(f"Driver Use Count Before: {Driver.use_count()}")
36
37 # rocm.bindings.hip.hipMalloc returns (err, DeviceArray). Unpack the
38 # error-tuple shape the auto-generated wrapper uses, then take the
39 # device pointer from the array's __int__.
40 err, dev_array = hipMalloc(size)
41 assert int(err) == 0, f"hipMalloc failed: {err}"
42 buffer_ptr = int(dev_array)
43 print(f"Buffer located at: {buffer_ptr} | {hex(buffer_ptr)}")
44
45 with Driver() as hipfile_driver:
46 print(f"Driver Use Count After: {hipfile_driver.use_count()}")
47 with Buffer(buffer_ptr, size, 0) as registered_buffer:
48 with FileHandle(
49 input_path,
50 os.O_RDWR | os.O_DIRECT | os.O_CREAT,
51 handle_type=FileHandleType.OPAQUE_FD,
52 ) as fh_input:
53 with FileHandle(
54 output_path,
55 os.O_RDWR | os.O_DIRECT | os.O_CREAT | os.O_TRUNC,
56 ) as fh_output:
57 print(f"Transferring {size} bytes...")
58 bytes_read = fh_input.read(registered_buffer, size, 0, 0)
59 print(f"Bytes Read: {bytes_read}")
60 bytes_written = fh_output.write(
61 registered_buffer, size, 0, 0
62 )
63 print(f"Bytes Written: {bytes_written}")
64
65 # hipFree returns only an error; the wrapper hands it back as a 1-tuple.
66 (free_err,) = hipFree(dev_array)
67 assert int(free_err) == 0, f"hipFree failed: {free_err}"
68
69 with open(input_path, "br") as file_in:
70 hash_in = hashlib.sha256()
71 chunk = file_in.read(1 * 1024 * 1024)
72 while len(chunk) != 0:
73 hash_in.update(chunk)
74 chunk = file_in.read(1 * 1024 * 1024)
75 print(f"Input File Hash: {hash_in.hexdigest()}")
76
77 with open(output_path, "br") as file_out:
78 hash_out = hashlib.sha256()
79 chunk = file_out.read(1 * 1024 * 1024)
80 while len(chunk) != 0:
81 hash_out.update(chunk)
82 chunk = file_out.read(1 * 1024 * 1024)
83 print(f"Output File Hash: {hash_out.hexdigest()}")
What is happening?
We query the hipFile version via
get_version(line 16) and create a 2 MiB random input file in a temporary directory (line 34). The size is block-aligned so theO_DIRECTtransfers are valid.We allocate a device buffer via
hipMallocand take its address from the returnedDeviceArray(line 41).We open the hipFile
Driver(line 46) and register the device buffer as aBuffer(line 48), both as context managers so they are deregistered/closed automatically on scope exit.We register the input and output files as
FileHandlecontext managers (lines 49-57).FileHandleType.OPAQUE_FDselects the POSIX file-descriptor handle type (the default).We read the input file into the device buffer via
FileHandle.read(line 59) and write it back out to the output file viaFileHandle.write(line 61).After the
withblocks tear down the handles, buffer, and driver, we free the device memory viahipFreeand compare the SHA256 hashes of the input and output files.
Note
For a version that drives the auto-generated rocm.bindings.hipfile
functions directly — showing the raw (retval, errno, hip_drv_err)
result tuples and the manual driver/buffer/handle lifecycle that the
high-level classes encapsulate — see
examples/0_Basic_Usage/hipfile_copy_lowlevel.py.
Basic Usage (Cython)#
What will I learn?
How I can use HIP Python’s Cython modules in my Cython code.
How to compile my Cython code that uses HIP Python’s Cython modules.
In this section, we show how to use HIP Python’s Cython modules and how to compile projects that use them.
Cython Recap#
Note
This section expects that the user has at least some basic knowledge about the programming language Cython. If you are unfamiliar with the language, we refer to the Cython tutorials and the Language Basics page.
Cython modules are often split into a *.pxd and a *.pyx file, which are a
Cython module’s declaration and implementation part respectively. While the
former files are to some degree comparable to header files in C/C++, the
latter can be compared to sources files. The declaration part may only contain
cdef fields, variables, and function prototypes while the implementation
part may contain the implementation of those entities as well as Python
fields, variables, and functions.
The implementation part is the interface between the C/C++ and the Python
world. Here, you can import Python code via Python’s import statements,
you can C-import cdef declarations from other Cython declaration files
(*.pxd) via cimport statements, and you can include C/C++ declarations
from C/C++ header files as cdef declarations.
To build a Python module from a Cython module, the implementation part must be
first “cythonized”, i.e. converted into a C/C++ file and then compiled with a
compiler. It is recommended to use the compiler that was used for compiling
the used python interpreter. Most people don’t do this manually but instead
prefer to use the build infrastructure provided by setuptools. They
then write a setup.py script that contains the code that performs the
aforementioned two tasks.
Cython modules in HIP Python#
Per Python module rocm.bindings.hip,
rocm.bindings.hiprtc, …, HIP Python ships an additional
cy-prefixed rocm.bindings.cy<pkg_name> module.
The module without the
cprefix is compiled into the interface for HIP Python’s Python users. However, allcdefdeclarations therein can also becimported by Cython users (typicallycdef classdeclarations) and all Python objects therein can beimported by Cython users too (typically enum and function objects).The module with the
cyprefix builds the bridge to the underlying HIP C library by including C definitions from the corresponding header files. This code is located in the declaration part. This part further declares runtime function loader prototypes. The definition of these function loaders in the implementation part first try to load the underlying C library and then if successful, try to load the function symbol from that shared object.
Note
The lazy-loading of functions at runtime can, under some circumstances, allow to use a HIP Python version that covers a superset or only a subset of the functions available within the respective library of a ROCm™ installation.
Using the Cython API#
You can import the Python objects that you need as shown below:
1from rocm.bindings import hip # enum types, enum aliases, fields
2from rocm.bindings import hiprtc
3# ...
In the same file, you can also or alternatively cimport the cdef
entities as shown below:
1from rocm.bindings cimport cyhip # direct access to C interfaces and lazy function loaders
2from rocm.bindings cimport cyhiprtc
3# ...
4
5from rocm.bindings cimport hip # access to `cdef class` and `ctypedef` types
6 # that have been created per C struct/union/typedef
7from rocm.bindings cimport hiprtc
8# ...
Compiling a Cython module#
After having written your own mymodule.pyx file that uses HIP Python’s
Cython API, you can compile the result using a setup.py script as
shown below. In the setup.py script, we only assume that
HIP or HIPRTC is used. Therefore, only amdhip64 is put into the rocm_libs
list. It is further important to specify the HIP Platform as the header files
from which we include the C interfaces will be included at compile time by the
underlying C/C++ compiler. The compilation path must include all these
interfaces.
1import os, sys
2
3mymodule = "mymodule"
4
5# We only assume HIP/HIPRTC is used, so only `amdhip64` is linked.
6rocm_libs = ["amdhip64"]
7
8from setuptools import Extension, setup
9from Cython.Build import cythonize
10
11ROCM_PATH=os.environ.get("ROCM_PATH", "/opt/rocm")
12HIP_PLATFORM = os.environ.get("HIP_PLATFORM", "amd")
13
14if HIP_PLATFORM not in ("amd", "hcc"):
15 raise RuntimeError("Currently only HIP_PLATFORM=amd is supported")
16
17def create_extension(name, sources):
18 global ROCM_PATH
19 global HIP_PLATFORM
20 rocm_inc = os.path.join(ROCM_PATH,"include")
21 rocm_lib_dir = os.path.join(ROCM_PATH,"lib")
22 platform = HIP_PLATFORM.upper()
23 cflags = ["-D", f"__HIP_PLATFORM_{platform}__"]
24
25 return Extension(
26 name,
27 sources=sources,
28 include_dirs=[rocm_inc],
29 library_dirs=[rocm_lib_dir],
30 libraries=rocm_libs,
31 language="c",
32 extra_compile_args=cflags,
33 )
34
35setup(
36 ext_modules = cythonize(
37 [create_extension(mymodule, [f"{mymodule}.pyx"]),],
38 compiler_directives=dict(language_level=3),
39 compile_time_env=dict(HIP_PYTHON=True),
40 )
41)