|
| 1 | +# Copyright (c) 2024-2025, NVIDIA CORPORATION & AFFILIATES. ALL RIGHTS RESERVED. |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +# ################################################################################ |
| 6 | +# |
| 7 | +# This demo aims to illustrate two takeaways: |
| 8 | +# |
| 9 | +# 1. The similarity between CPU and GPU JIT-compilation with C++ sources |
| 10 | +# 2. How to use StridedMemoryView to interface with foreign C/C++ functions |
| 11 | +# |
| 12 | +# To facilitate this demo, we use cffi (https://cffi.readthedocs.io/) for the CPU |
| 13 | +# path, which can be easily installed from pip or conda following their instructions. |
| 14 | +# We also use NumPy/CuPy as the CPU/GPU array container. |
| 15 | +# |
| 16 | +# ################################################################################ |
| 17 | + |
| 18 | +import importlib |
| 19 | +import shutil |
| 20 | +import string |
| 21 | +import sys |
| 22 | +import tempfile |
| 23 | + |
| 24 | +try: |
| 25 | + from cffi import FFI |
| 26 | +except ImportError: |
| 27 | + print("cffi is not installed, the CPU example will be skipped", file=sys.stderr) |
| 28 | + FFI = None |
| 29 | +import numpy as np |
| 30 | + |
| 31 | +from cuda.core.experimental.utils import StridedMemoryView, args_viewable_as_strided_memory |
| 32 | + |
| 33 | +# ################################################################################ |
| 34 | +# |
| 35 | +# Usually this entire code block is in a separate file, built as a Python extension |
| 36 | +# module that can be imported by users at run time. For illustrative purposes we |
| 37 | +# use JIT compilation to make this demo self-contained. |
| 38 | +# |
| 39 | +# Here we assume an in-place operation, equivalent to the following NumPy code: |
| 40 | +# |
| 41 | +# >>> arr = ... |
| 42 | +# >>> assert arr.dtype == np.int32 |
| 43 | +# >>> assert arr.ndim == 1 |
| 44 | +# >>> arr += np.arange(arr.size, dtype=arr.dtype) |
| 45 | +# |
| 46 | +# is implemented for both CPU and GPU at low-level, with the following C function |
| 47 | +# signature: |
| 48 | +func_name = "inplace_plus_arange_N" |
| 49 | +func_sig = f"void {func_name}(int* data, size_t N)" |
| 50 | + |
| 51 | + |
| 52 | +# Now we are prepared to run the code from the user's perspective! |
| 53 | +# |
| 54 | +# ################################################################################ |
| 55 | + |
| 56 | + |
| 57 | +# Below, as a user we want to perform the said in-place operation on a CPU |
| 58 | +# or GPU, by calling the corresponding function implemented "elsewhere" |
| 59 | +# (in the body of run function). |
| 60 | + |
| 61 | + |
| 62 | +# We assume the 0-th argument supports either DLPack or CUDA Array Interface (both |
| 63 | +# of which are supported by StridedMemoryView). |
| 64 | +@args_viewable_as_strided_memory((0,)) |
| 65 | +def my_func(arr): |
| 66 | + global cpu_func |
| 67 | + global cpu_prog |
| 68 | + # Create a memory view over arr (assumed to be a 1D array of int32). The stream |
| 69 | + # ordering is taken care of, so that arr can be safely accessed on our work |
| 70 | + # stream (ordered after a data stream on which arr is potentially prepared). |
| 71 | + view = arr.view(-1) |
| 72 | + assert isinstance(view, StridedMemoryView) |
| 73 | + assert len(view.shape) == 1 |
| 74 | + assert view.dtype == np.int32 |
| 75 | + assert not view.is_device_accessible |
| 76 | + |
| 77 | + size = view.shape[0] |
| 78 | + # DLPack also supports host arrays. We want to know if the array data is |
| 79 | + # accessible from the GPU, and dispatch to the right routine accordingly. |
| 80 | + cpu_func(cpu_prog.cast("int*", view.ptr), size) |
| 81 | + |
| 82 | + |
| 83 | +def run(): |
| 84 | + global my_func |
| 85 | + if not FFI: |
| 86 | + return |
| 87 | + # Here is a concrete (very naive!) implementation on CPU: |
| 88 | + cpu_code = string.Template(r""" |
| 89 | + extern "C" |
| 90 | + $func_sig { |
| 91 | + for (size_t i = 0; i < N; i++) { |
| 92 | + data[i] += i; |
| 93 | + } |
| 94 | + } |
| 95 | + """).substitute(func_sig=func_sig) |
| 96 | + # This is cffi's way of JIT compiling & loading a CPU function. cffi builds an |
| 97 | + # extension module that has the Python binding to the underlying C function. |
| 98 | + # For more details, please refer to cffi's documentation. |
| 99 | + cpu_prog = FFI() |
| 100 | + cpu_prog.cdef(f"{func_sig};") |
| 101 | + cpu_prog.set_source( |
| 102 | + "_cpu_obj", |
| 103 | + cpu_code, |
| 104 | + source_extension=".cpp", |
| 105 | + extra_compile_args=["-std=c++11"], |
| 106 | + ) |
| 107 | + temp_dir = tempfile.mkdtemp() |
| 108 | + saved_sys_path = sys.path.copy() |
| 109 | + try: |
| 110 | + cpu_prog.compile(tmpdir=temp_dir) |
| 111 | + |
| 112 | + sys.path.append(temp_dir) |
| 113 | + cpu_func = getattr(importlib.import_module("_cpu_obj.lib"), func_name) |
| 114 | + |
| 115 | + # Create input array on CPU |
| 116 | + arr_cpu = np.zeros(1024, dtype=np.int32) |
| 117 | + print(f"before: {arr_cpu[:10]=}") |
| 118 | + |
| 119 | + # Run the workload |
| 120 | + my_func(arr_cpu) |
| 121 | + |
| 122 | + # Check the result |
| 123 | + print(f"after: {arr_cpu[:10]=}") |
| 124 | + assert np.allclose(arr_cpu, np.arange(1024, dtype=np.int32)) |
| 125 | + finally: |
| 126 | + sys.path = saved_sys_path |
| 127 | + # to allow FFI module to unload, we delete references to |
| 128 | + # to cpu_func |
| 129 | + del cpu_func, my_func |
| 130 | + # clean up temp directory |
| 131 | + shutil.rmtree(temp_dir) |
| 132 | + |
| 133 | + |
| 134 | +if __name__ == "__main__": |
| 135 | + run() |
0 commit comments