All notable changes to the cunumpy library are documented here.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
xp.algorithms.hilbert_encode(*cells, levels=...): Hilbert keys of integer cells in 2D and 3D (Skilling's construction, on NumPy or CuPy): consecutive keys are neighbouring cells, and the cells of every quadtree or octree node are a contiguous range.- A kernel call whose NumPy arrays are not all C-contiguous (a column slice of marker
storage) runs the next host implementation, Pyccel where it builds, instead of the C
version, which takes C-contiguous arrays only and raised
TypeError. - C host kernels: a kernel folder may hold
<name>_c.cnext to the Pyccel version (the same arguments; arrays as pointer and shape).CCache(inKernelPackage.c_cache) compiles it with a generated CPython wrapper and keeps the build; the implementation"c"comes before"pyccel", and a failed build falls back to it. For loops the compiler must vectorise. cunumpy.threads:configure_threads(every BLAS at one thread, a warning when the ranks of a node run more OpenMP threads than it has cores),blas_threads,limit_blas_threads,restore_blas_threads,thread_reportandpython -m cunumpy.threads; spinning BLAS threads slowed the OpenMP kernels run after a BLAS call. Needsthreadpoolctl>=3.7.PyccelCachetakes extra C compiler flags from<PREFIX>_FLAGS(flags_env,flags()), passed topyccel compile --flagsand part of the build key, e.g.-march=nativefor the machine at hand. None by default.- CUDA kernels written in Python:
xp.kernels.CupyJitKernel(cupyx.jit) andxp.kernels.NumbaCudaKernel(numba-cuda), launched like aCudaKernel(n_threads,grid,block,shared_mem,stream, launch size from the first array). Device arrays only (NumPy arrays raise instead of being copied),CudaArgumentsflattened, the number of arguments checked; numba-cuda launches on CuPy's current stream. AKerneltakes them ascupy_jit_kernel=andnumba_cuda_kernel=, and kernel folders as<name>_cupy_jit.pyand<name>_numba_cuda.py(imported at the first device call). On the device a call runs the first of"cuda_c","cupy_jit","numba_cuda"that loads;set_device_kernel_implementationtakes these names (DEVICE_IMPLEMENTATIONS) besides"cuda"(any of them, no host fallback).assert_kernels_agreecompares every device implementation with the host kernel (implementations=to choose). The fake CuPy emulatescupyx.jiton the CPU, and numba's simulator (NUMBA_ENABLE_CUDASIM=1,kernel_testing.numba_simulator_active()) runs numba-cuda kernels on fake CuPy arrays, so both kinds are tested without a GPU. - A CUDA C kernel in a kernel folder may also be named
<name>_cuda_c.cu. - A docs page, "Shared kernel blocks": where blocks shared between the kernels of several
packages live, how each backend uses them, and the rules (no locals in
@inlinePyccel blocks under OpenMP, nomin/max,-0.0for a zero term, tests of fused kernels against the plain path; the hand-written versions of a block checked against its Pyccel source run in Python). - Pyccel kernels can import functions from other modules, also of other packages
(
from other_pkg.kernels.boris_pyccel import boris_rotate):PyccelCachebuilds those modules with the kernel (copied under flat names, imports rewritten, so Pyccel also inlines their@inlinefunctions, which it does only from top-level modules), keeps only the kernel's extension (it contains their code), and puts their sources into the build key, so editing one rebuilds the kernel.PyccelCache.dependencies(module)lists them in build order.
CudaKernel.from_file(path)without a name works with any file name: it takes the file name minus_cuda_c.cu,_cuda.cuor.cuif the file defines that kernel, else the file's only__global__function, and raises listing the kernels otherwise.suffix=(now None by default) still requires that suffix and strips it.- The CUDA C implementation of a
Kernelis called"cuda_c"inKernel.implementationsandKernel.selected(device=True)(was"cuda");"cuda"remains the setting that requires any device implementation.Kernel.has_cuda,KernelCatalog.with_cudaandparity_casescount Python device kernels too, and thereprof aKernellists its device implementations. Kernel.from_folder(andKernelPackage.from_folder,KernelCatalog.from_package) no longer imports the host kernel module (<name>_pyccel.py) when it builds the kernel, only when its"python"or"pyccel"implementation is first used. A host module that cannot be imported, e.g. a Pyccel source that importspyccel.stdlib.internal.openmpin a Python without Pyccel (Pyodide), now leaves the kernel on its NumPy or numba version instead of failing the import of the package. The parameter names andoutputs="annotations"come from the newHostImplementations.reference: the Python version, else the NumPy or numba one.
- Faster hot paths for particle codes: host segment sums with
np.add.reduceat(sorted keys) andnp.bincount(unsorted), up to 10x faster for three components; deterministic CUDA segment sums for sorted keys;sort_by_key(..., out=...);Kernel.resolve(*args)andPyccelKernel.resolve(*args), the plain host function of a call for tight loops (0.1 µs instead of 1.2-2 µs per call);CudaKernel.bind(...), aBoundLaunchfor repeated launches; and CUDA graphs (capture_graph). - The interop adapters convert nested containers and scalar objectives.
- The
scope_profiler.opt_in_tagsentry point. cunumpy.interop.julia(extracunumpy[julia], juliacall):to_julia/from_juliabetween NumPy arrays and JuliaArrays that share memory. Julia is column-major, so a C-ordered array arrives with its dimensions reversed and an F-ordered one with the same dimensions;from_julia(order="C" | "F")picks the order back. Host arrays only; CuPy to CUDA.jl is planned.copy=None | True | Falseon every interop conversion (as in the array API):Falseraises when the conversion cannot share memory,Truealways copies.supports_float64(device)in the JAX, PyTorch and MLX adapters andcunumpy.interop.jax.enable_x64().
- Interop conversions never change a dtype without being asked: float64 into JAX without
jax_enable_x64, onto an Apple GPU in PyTorch (MPS) or into MLX for the GPU raises aTypeErrorwith advice instead of becoming float32. MLX keeps float64 fordevice=mlx.core.cpu. - The transfer profiler tells interop conversions apart: a conversion that shares memory records
nothing, one between host and device records
to_host/to_device, and one within a memorydevice_copy(before, every conversion was adevice_copy). from_frameworkcopies between host and device explicitly (a recorded transfer, an error undercopy=False) instead of falling back toasarraysilently, and a framework that cannot take an array's device raises aValueErrornaming the device.from_jaxraises a clearTypeErrorfor traced values (insidejax.jit,grad,vmap).to_mlx(device=...)names the device the array is meant for (MLX arrays have no device); before, it passeddevicetomlx.core.array, which does not take it.
- The fake
cupy.randomno longer answers dunder names (__file__, ...) with a wrapped NumPy function, which broke module introspection: importing astropy after cunumpy failed underCUNUMPY_FAKE_CUPY.
PyccelCacheimports a new build once in a subprocess before it stores it: a build the interpreter cannot import, or one that crashes it (an extension linked tolibpythonin a Python that has it built in, such as uv's CPython 3.12 on macOS), is aRuntimeErrorand is not stored, instead of a segmentation fault in every process that loads it.- The
PyccelCachekey includes the NumPy version, so environments that share an interpreter but not NumPy no longer share builds.
xp.kernels.KernelPackage(name): thePyccelCacheand theKernel.from_folderoptions shared by the kernel folders of one package (host_suffix="_pyccel",dispatch="arrays",block_size=256,n_threads_from="last_axis"), withfrom_folder(package, **overrides)andmetal_kernel(...)(float32MetalKernels with zeroed outputs), so packages no longer keep their own copies of these settings.xp.kernels.source_roots(*packages): the source roots of installed packages, forinclude_dirsof a CUDA kernel that includes another package's header.xp.cuda.shared_memory_fits(num_values, itemsize=8): whether a per-block buffer fitsDEFAULT_SHARED_MEMORY_PER_BLOCK.- scope-profiler regions around the coarse operations (
Kernelcalls ascunumpy.kernel.<name>, CUDA and Pyccel compilation,sort_by_key,SegmentPlan.sum,compact_by_mask,morton_keys, the solvers,exchange, and the device copies ofmpi_bufferandDeviceMirror), behind the opt-in tagcunumpy: off unless the application enables it, e.g.sp.setup(enable_tags=["cunumpy"])orSCOPE_PROFILER_ENABLE_TAGS=cunumpy. New dependency:scope-profiler>=0.7.5.
xp.algorithms.sort_by_keygathers a 2-D NumPy array along its last axis (component-major markers,axis=-1) row by row, about 2x faster thantake(1e6 markers: 3 rows 12.9 to 6.7 ms, 8 rows 37 to 19 ms).
xp.kernels.kernel_outputs(*outs, like=..., dtype=..., strided=...): the buffers of several kernel outputs in one block, each written back into its array (askernel_outputdoes) when the block ends without an error.xp.kernels.PyccelCache(name): compiles a Pyccel kernel module once withpyccel compileand keeps the build on disk (~/.cache/<name>/kernels, or<NAME>_KERNEL_CACHE), keyed on its source, the OpenMP setting (<NAME>_OPENMP), the Pyccel and Python versions and the platform; a temporary directory if the cache is not writable, and an atomic publish for concurrent builders. Callable, so it can be thecompile_hostofKernel.from_folderandKernelCatalog.from_package.- Supported CuPy versions: 14.0 or newer (
xp.MIN_CUPY_VERSION,xp.cupy_version_supported); an older CuPy warns when the CuPy backend is first checked, andbackend_info()reports the minimum. The GPU CI runs the whole suite on CuPy 14.0.0 too (gpu_tests_min_cupy). - MIT license (
LICENSE.txt, referenced bypyproject.toml). xp.optimize.newton: Newton's method or the secant method on many independent scalar equations at once, with the steps ofscipy.optimize.newtonfor an arrayx0, on the array's backend (no host copies, fixed shapes, one synchronization per iteration).- The fake CuPy has
cupyx.scipy: SciPy behind the CuPy rules (host arrays rejected, fake device arrays and proxy objects returned), soxp.scipycode runs its CuPy path without a GPU. Everycupyx.scipysubpackage has only the names the oldest supported CuPy (14.0.0) provides, so e.g.special.jvorsparse.csr_arrayfails as on a GPU.testing/cupyx_names.pyandtests/unit/test_cupyx_names.pycheck these names against the installed CuPy in the GPU CI.cupyx.empty_pinned/zeros_pinnedreturn NumPy arrays. xp.optimize.fsolve,root,minimizeandxp.integrate.quad,odeint(cupyx.scipyhas neither): SciPy on the host with SciPy's arguments, the callbacks get their arrays on the backend ofx0/y0, and results come back on that backend.xp.scipy.linalg.solve_circulanton the CuPy backend, whichcupyx.scipylacks: SciPy's FFT solve and arguments, on the device.- Solvers guide: splines on the device with
xp.scipy.interpolate, and batched root finding. - Compiled Pyccel regression coverage for F-ordered arrays and column-block copy-back, run in CPU CI with fake CuPy and required compilation.
- Publishing now requires CPU and GPU validation of the release commit, checks the built distributions, and smoke-tests the wheel in a fresh environment.
- NumPy-format docstrings with runnable examples for the whole public API. The
API reference is generated from them (
docs/source/reference/); the hand-writtenapi.mdis now a short overview, and the CUDA headers have their own page. CI checks the docstrings (ruffDrules, numpydoc validation), runs their examples as doctests, and builds the docs with warnings as errors. Docstring style:docs/source/contributing.md.
as_kernel_arraygives a length-1 axis inside a longer one exactly the C-order stride:nodes[:, mask]with a single selected column (shape(2, 1), strides(8, 16)) is C-contiguous to NumPy but was rejected by Pyccel's order check.- Splines and other objects of the fake
cupyx.scipycan be copied withcopy.copyandcopy.deepcopy(also inside a copied container), as real CuPy splines can. xp.algorithms.segment_sumandSegmentPlan.sumwork on the fake CuPy: it cannot compile the CUDA kernel, so the sum runs on the host buffers of the fake arrays and the CuPy path of a program runs without a GPU.- The ordering guide identifies 0.6.3 as the first release preserving F order in CuPy-to-host conversions.
CudaStruct.from_signatureaccepts quoted pyccel annotations (markers: "float[:, :]") in modules withfrom __future__ import annotations.
- The documentation site is built with Astro and Starlight
(starlight-theme) instead of
Sphinx: the pages are in
docs/src/content/docs/, the API reference is generated from the docstrings by starlight-pydocs (/api/cunumpy/), the old.htmlURLs redirect, andmake docs-buildbuilds it. Thedocsextra is now onlygriffe;pre-commitandpyproject-fmtmoved todev. The#:comments of public constants are now attribute docstrings.
- The emulation of kernels with
__syncthreadscompiles with GCC on macOS. - Preserve Fortran order when copying CuPy arrays to the host through
to_numpy,host_call,evaluate_on_host, andPyccelKernelconversions.
emulate_cuda_kernelcompiles each kernel once, into a shared library that takes the arguments at run time and runs in the process (ctypes), on the arrays themselves; later launches with any values and sizes reuse it. Libraries are cached per process and on disk (kernel_testing.emulation_cache_dir(),CUNUMPY_EMULATION_CACHE, default~/.cache/cunumpy/emulation).kernel_testing.compile_for_emulation(kernel)builds one without a launch.__trap()(a failed bounds check) still raisesRuntimeError, but a segmentation fault now ends the process.- Inside
emulated_launches(),CudaKernel.compile()(and sorecompile(),CudaKernelVariants.compile_all()andKernelCatalog.compile_all()) builds the emulation library instead of compiling CUDA, and returns None. Code that compiles its kernels before the time loop runs on the fake CuPy and still reports compile errors there; patchingCudaKernel.compileis no longer needed. - The emulation compiles inline PTX (
asm(...),asm volatile(...)) as a trap, so a kernel with anasm("trap;")branch needs no-Dasm(x)=__trap()option. kernel_testing.fake_cupy_session()runs a CuPy-backend program on the CPU (CuPy backend on the fake CuPy, launches and compilation emulated);kernel_testing.device_backend_available()and the markerrequires_device_backend(a GPU or the fake CuPy);kernel_testing.run_in_fake_cupy_subprocess(code)runs code in a serial child process on the fake CuPy (rank 0 only under MPI) and fails the test with the signal or exit code and the end of the child's output.profiling.TransferBudgetcounts transfers per phase of a program (budget.phase(name), the decoratorbudget.count(name),start()/stop()) and checks a rule per phase (require(phase, allow={"to_host": {"max_nbytes": 8}}, calls=n),check(),report()).count_transfers(into=counter)adds to an existing counter (counted once when nested).TransferEventhasblocking(False forto_host_async()andHostStaging.copy()) andimplicit(True for the scalar reads of the fake CuPy).xp.to_host_async(a)copies a device scalar or small array to the host on a separate stream without waiting; the returnedmemory.HostCopyhasready()(never waits) andresult().kernel_testing.emulated_launches()runs everyCudaKernellaunch in a block on the CPU, on the host buffers of the fake CuPy arrays, so code that launches kernels can be tested without a GPU.emulate_cuda_kernelnow accepts struct parameters (a mapping of field values, aCudaStructValue, or an object with an attribute per field).kernel_testing.host_buffer(array)returns the NumPy array behind a fake CuPy array.CUNUMPY_REQUIRE_CUDA=1makes the GPU markers ofkernel_testingfail instead of skipping:requires_cupy, thecupyrun of thebackendfixture (which activates CuPy strictly) andassert_kernels_agree. Newkernel_testing.cuda_required().count_transfers()recordssyncevents (the host waiting for the device):xp.synchronize(), the waits of the MPI helpers and of the CUDA debug mode, and, on the fake CuPy, scalar reads of device arrays. They are incounter.syncsand the report but not intotal;assert_no_transfers(syncs=True)rejects them. The real CuPy's ownfloat(a)cannot be observed from Python and is not counted.xp.algorithms.compact_by_mask(mask, *arrays, axis=0)moves the masked entries of arrays to the front alongaxis, in place and in order, and returns their number;axis=-1compacts component-major(ncomp, N)and(N,)arrays together.as_kernel_array(..., strided=True)andkernel_output(..., strided=True)take a NumPy array in C order with gaps (positive strides, each at least the extent of the next axis, e.g.storage[:, :n]) unchanged for host kernels, instead of copying it to a C-contiguous array; Pyccel's wrappers take such arrays.CudaKernel(n_threads_from="last_axis"): one thread per entry of the last axis of the first array argument, for component-major(ncomp, N)marker arrays.- Kernel outputs: a name in
PyccelKernel(outputs=...)also finds a positional argument and an index a keyword argument, using the parameter names of the function (or the newparameters=); aKernelsupplies those of its host function.xp.kernels.outputs_from_annotations()reads the outputs from the annotations (notFinal,constor a scalar), andKernel.from_folder()/KernelCatalog.from_package()takeoutputs=(names, indices or"annotations").assert_kernels_agree(outputs=...)takes parameter names and"name.field"to compare only some fields of a struct argument. xp.kernels.MetalKernelruns a Metal Shading Language kernel on the GPU of an Apple silicon Mac through MLX (pip install 'cunumpy[metal]'). It takes and fills NumPy arrays, is float32 only (float64="cast"computes float64 data in float32), and its copies are counted byxp.profiling.count_transfers().xp.kernels.metal_available()tells whether it can run.xp.host_call,xp.evaluate_on_hostandxp.setup_on_hostrun host-only code (SciPy splines, file readers, external libraries) with arguments of either backend: device arrays are copied to the host, the call runs on the NumPy backend and array results are copied back. The copies are counted byxp.profiling.count_transfers().
- The launcher detection and the serial MPI stand-in moved to the new package
maybempi, a dependency of cunumpy.
xp.mpire-exports them (get_mpi,launched_under_mpi,local_rank,SerialMPI,SerialComm, ...), plus the newxp.mpi.is_serial. The override variable is nowMAYBEMPI=1/0;CUNUMPY_MPIis no longer read. CudaKernelandCudaKernelVariantsmoved tocunumpy.kernels, next toKernelandPyccelKernel. The argument classesCudaArguments,CudaStruct,CudaStructArguments,CudaStructValueandwrite_cuda_headermoved to the newcunumpy.arguments.cunumpy.cudakeeps the device runtime and the CUDA source tools. The oldcunumpy.cuda.<name>names are removed.- Removed the deprecated names that were kept for one release after the
0.5 reorganisation, with no replacement other than the submodules:
the top-level helpers (
xp.CudaKernel,xp.mpi_buffer,xp.fuseas cunumpy's, ...; usexp.kernels,xp.arguments,xp.cuda,xp.mpi,xp.rng,xp.algorithms,xp.profiling,xp.memoryandxp.petsc), and the modulescunumpy.testing(nowcunumpy.kernel_testing),cunumpy.kernel,cunumpy.dispatchandcunumpy.cuda_kernel(public names are incunumpy.kernelsandcunumpy.arguments). Also removed the placeholdercunumpy.main.xp.fuseis now CuPy's ownfuse. - Removed
kernels.KernelArguments,kernels.resolve_host_args,kernels.PyccelStructArgumentsand the__host_args__()protocol, with no replacement. Kernels receive argument objects as they are. Write the host argument class (e.g. pyccel) and aCudaStructArgumentswith the same constructor, and let the owner of the arrays build the one for its backend.Kernel(dispatch="arrays")now treats every object with__cuda_args__()as a device argument. - Rename
CUNUMPY_KERNEL_IMPLEMENTATIONtoCUNUMPY_HOST_KERNEL_IMPLEMENTATIONto make its host-only scope explicit. The former environment variable is no longer read; update job scripts. CUDA dispatch is unchanged. - Rename the
kernelsselection functions toset_host_kernel_implementation,get_host_kernel_implementation, anduse_host_kernel_implementation. The former function names are removed without compatibility aliases.
- Strided and C-contiguous CUDA array views through 16 dimensions, including
Array5D/Array6Dfor matrix accumulations. Higher-dimensional views work as kernel parameters, struct fields, annotations and in CPU emulation. - C-contiguous array views
CArray1D<T>toCArray16D<T>incunumpy/array_view.cuh. They hold a pointer and shape only, soa(i, j)isdata[i * shape[1] + j]. As kernel parameters or struct fields, they reject non-contiguous arrays and never copy them.CudaStruct.from_signatureandfrom_pyccel_classtakecontiguous=Trueor field names to generate them. - Device implementation selection via
kernels.set_device_kernel_implementation,get_device_kernel_implementation,use_device_kernel_implementation, andCUNUMPY_DEVICE_KERNEL_IMPLEMENTATION. Accept"cuda"or automatic selection (None); explicit CUDA selection rejects missing CUDA kernels instead of falling back to the host. Unsupported implementation names raise. - CUDA launches infer thread counts from the first array by default, including arrays in argument objects. 1D blocks use rows; multidimensional blocks use matching leading shape axes. Explicit sizes and callbacks override inference.
- Per-device eager CUDA compilation, compiler log streams and explicit
recompile(). - Launch validation against actual device/kernel dimensions, thread limits and static plus dynamic shared memory, with cached per-device opt-in state.
- Transfer payload byte counts, mirror-refresh and kernel-output accounting, and separate device-only conversion observations.
- Producer
stream=/event=dependencies for output staging and mirror downloads; device-bound retained storage and CPU-to-pinned staging upgrades. - GPU CI requires real hardware and runs focused Compute Sanitizer memory, shared-memory race and synchronization checks.
- Reusable
cuda.create_stream,create_event,record_event, andwait_event, with synchronous host equivalents;cuda.stream(existing)selects an existing stream. mpi.MPIStagingreuses host staging storage and rejects overlapping device uses.algorithms.cell_offsets,segment_boundaries, andSegmentPlanfor prepared grouping.- Strict backend selection via
set_backend/use_backend(..., strict=True)and JSON-compatiblebackend_info()diagnostics. cunumpy/scan.cuhinclusive/exclusive warp and block prefix sums, mask-aware warp reductions, partial-warp block reductions, and integer atomic-add helpers.
segment_sum(..., out=...)supports arbitrary trailing component dimensions; CUDA reduces components in one accumulation launch. Prepared plans avoid repeated key validation and GPU scalar reads. Floating-point order may vary.- MPI producer synchronization accepts a stream/event, or waits for all work on the buffer's device. Receive staging waits for copy-back before releasing storage.
- The helpers moved from the top level of
cunumpyto submodules, so that the top level is the NumPy/CuPy namespace plus backend selection and array conversion, and no helper hides a NumPy or CuPy name (xp.fusehidcupy.fuse):cunumpy.cuda(CUDA only:CudaKernel,CudaKernelVariants,CudaStruct*,CudaArguments,CudaParameter, header tools, debug mode, device selection and memory,stream,pin_memory),cunumpy.kernels(Kernel,KernelCatalog,PyccelKernel,KernelArguments,PyccelStructArguments, host implementations,as_kernel_array,kernel_output,fuse),cunumpy.rng(random_streams,RandomStreams,get_rng,philox_*),cunumpy.algorithms(morton_*,sort_by_key,segment_sum),cunumpy.mpi(mpi_buffer, CUDA-aware MPI,local_rank,synchronize_for_mpi),cunumpy.profiling(timed_region,Timing,nvtx_range, transfer counting),cunumpy.memory(HostStaging,StagedCopy,DeviceMirror) andcunumpy.petsc(petsc_vec). All are imported byimport cunumpy. The old top-level names still work and raise aDeprecationWarningnaming the new place; they will be removed in 0.6. cunumpy.testingis nowcunumpy.kernel_testing. Once imported,cunumpy.testingreplaced NumPy'sxp.testing, soxp.testing.assert_allclosefailed in every test that ran after animport cunumpy.testing.cunumpy.testingstill works, with aDeprecationWarning, until 0.6.- Importing
cunumpy.cudamakesxp.cudathe cunumpy submodule instead of CuPy'scupy.cuda; useimport cupyfor the latter. - The implementation modules are private (
cunumpy._cuda_kernel,_dispatch,_kernel,_fusion,_philox,_morton,_random_streams,_staging,_mirror,_transfers,_emulation,_scipy_backend, and the new_device,_mpi,_profiling,_algorithmssplit offcunumpy.xp), so every public name has one import path, through the submodules above.cunumpy.cuda_kernel,cunumpy.dispatchandcunumpy.kernel(in 0.3.0) still import, with aDeprecationWarning, until 0.6.cunumpy.xpkeeps the backend selection and array conversion only.
xp.<name>for a NumPy/CuPy function (xp.zeros,xp.add, ...) is a plain attribute lookup, as fast asnumpy.<name>(before: about 3 us per access through the module__getattr__, 20 timesnumpy.add). The public names of the active backend module are copied into thecunumpynamespace and replaced whenset_backend/use_backendchange the backend (about 30 us per switch between NumPy and CuPy; nothing when the module stays the same).dir(xp)lists them, so IPython and Jupyter complete NumPy names.ArrayBackend.add_listener(callback)is called with the new module on every switch.
- Formatting is checked with
ruff formatand import order with ruff's isort rules (ruff check), onsrc/andtests/, instead of black and isort; thedevextra installs ruff. - GPU matrix/FFT correctness tests check numerical parity without timing assertions; performance comparisons belong in scope-profiler.
- Block min/max reductions synchronize warp shared-memory reads before lane 0 overwrites the result slot, fixing Compute Sanitizer racecheck hazards.
CudaKernel's header hash (-DCUNUMPY_INCLUDE_HASH) now covers the headers shipped with cunumpy (cunumpy/atomic.cuh,reduce.cuh, ...), also when included in angle brackets. Before, an upgrade of cunumpy that changed one of them left CuPy's kernel cache serving the kernel compiled with the old header.resolve_includes(..., angle_dirs=...)tracks angle-bracket includes found in the given directories.xp.testing.assert_kernels_agreereadsCudaStructArgumentsobjects and struct values through their struct fields, so their arrays get the same names as the attributes of the host argument object (before, arrays behind properties were named after the private attribute holding the owner, and the comparison failed with "do not have the same array arguments").
- Support for Python 3.8 and 3.9 (both end-of-life);
cunumpynow requires Python 3.10 or newer.
- Renamed the startup backend selector from
ARRAY_BACKENDtoCUNUMPY_BACKEND; update batch-job environments. CuNumpy-owned environment options useCUNUMPY_*. Kernel(..., dispatch="arrays")calls the host kernel directly for host arguments, withoutPyccelKernel's check for device arrays to convert, which converted nothing but ran while CuPy was the active backend (unless thePyccelKernelwas built withuse_cupy=True).Kernel.check_signature()(andKernelCatalog.check_signatures()) also compares the parameters of every host implementation (numba, NumPy; nothing is compiled) and of aCompiledHostKernel's fallback with those of the host kernel.KernelCatalog.from_package(..., compile_host=..., host_fallback=...)buildsHostImplementationsinstead ofCompiledHostKernels:host_fallbackbecomes the"numpy"implementation, and<name>_numba.py/<name>_numpy.pyfiles in a kernel folder are picked up.CudaKernelpointer and array view parameters andCudaStructpointer and view fields reject an array that lives on another CUDA device than the current one (ValueError;cupy.RawKernelwould read the foreign address silently). Checked only when CuPy is imported and the array reports adevice.assert_kernels_agree(..., n_threads=...)also takes a function of the argument tuple, andn_threadsmay be omitted when the CUDA kernel hasn_threads_from.- NumPy integer scalars passed to integer kernel parameters (and struct fields) are checked by value, like Python ints:
np.int64(5)fits anintparameter; before, they raisedTypeErrorunless their dtype was exactly the parameter's. - Python 3.14 is supported.
- The
testextra installs SciPy, so thexp.scipytests run in CI instead of being skipped. KernelCatalog.compile_all(jobs=1)andCudaKernelVariants.compile_all(keys, jobs=1): Withjobs > 1the CUDA kernels are compiled in threads (NVRTC releases the GIL);jobs=Noneuses the number of CPUs. All kernels are compiled even if one fails, and the first error is raised afterwards.- CI now tests every supported Python version (3.10, 3.11, 3.12, 3.13 and 3.14) instead of 3.8/3.10/3.13.
CudaKernel.compile()passescompile_options()to CuPy: the givenoptionsplus-DCUNUMPY_INCLUDE_HASH=0x<hash>when the source includes header files, so CuPy's kernel cache (keyed on source and options only) is invalidated when an included header changes.optionsstill returns the options as given.KernelCatalog.from_package(..., include_dirs=None)is now an explicit keyword; by default the source root of the top-level package (the directory containing it) is an include directory of every CUDA kernel, in addition to the kernel's own folder, so kernels can#include "my_pkg/common.cuh".
xp.mpi.get_mpi(use_mpi=None),launched_under_mpi(),SerialMPIandSerialComm: MPI only when it is used.launched_under_mpi()tells from the launcher's environment (Open MPI, MPICH, Intel MPI, PMIx/srun, MVAPICH2, Hydra, Cray ALPS/PALS;CUNUMPY_MPI=1/0overrides), without importing mpi4py, whether the process was started bympirun/mpiexec/srun.get_mpi()returnsmpi4py.MPIthen, and otherwise a serial stand-in whoseCOMM_WORLDis a communicator of size 1: object collectives return what one rank gets (allreduce(x)isx,gather(x)is[x]), buffer collectives copy (Allreduce,Allgather(v),Gather(v),Scatter(v),Sendrecvto self; nothing withIN_PLACE), on NumPy and CuPy buffers, and unsupported methods raiseAttributeError. The stand-in has the module attributes serial code needs (IN_PLACE, reduction ops, datatypes,PROC_NULL,ROOT,COMM_NULL,Request.Waitall,Prequest.Startall,Wtime, ...). It replaces feectools'MockComm/MockMPI, which returnedNonefor every call (MockComm().allreduce(5)wasNone,MockComm().ranka function). Kept incunumpy/_mpi_serial.pywithout dependencies on the rest of cunumpy, so that it could become a package of its own.cunumpy/morton.cuhandxp.morton_keys,morton_encode,morton_decode,morton_scales,MAX_MORTON_LEVELS: Morton (Z-order) keys of 2D and 3D points (uint64, up to 32 and 21 bits per axis), the same in a kernel and on the host (bit for bit), for sorting particles along a space-filling curve and building quadtrees and octrees from sorted keys.xp.sort_by_key(keys, *arrays): one stable argsort ofkeysapplied to every array; returns the sorted keys, the order and the sorted arrays.Kernel.from_folder(package, ...): the kernel of one kernel folder, with the options ofKernelCatalog.from_package(host_suffix,compile_host,dispatch,include_dirs, CUDA options...). Every version in the folder is an implementation:<name><host_suffix>.py("pyccel", compiled withcompile_host, and"python", uncompiled),<name>_numba.py,<name>_numpy.pyand<name>_cuda.cu. A folder's own__init__.pycan declarekernel = xp.Kernel.from_folder(__name__, ...), so code imports the kernel from where it is written;from_packagenow builds each kernel with it.Kernel.implementationslists them,Kernel.selected(device=False)tells which one a call runs.xp.HostImplementationsandxp.HOST_IMPLEMENTATIONS: the host implementations of a kernel, loaded on first use; a call runs the default, the first available of pyccel, numba and NumPy (the uncompiled Python version, with a warning, if none is), or the one chosen withxp.set_kernel_implementation(name)/with xp.use_kernel_implementation(name):/CUNUMPY_KERNEL_IMPLEMENTATION=name(read at import), likeset_backend/use_backend/CUNUMPY_BACKEND; a chosen implementation that a kernel lacks or cannot load raises instead of running another.xp.get_kernel_implementation()reads the setting.xp.as_kernel_array(value, like, dtype=None)andxp.kernel_output(out, like, dtype=None): bring the arguments of adispatch="arrays"kernel to the side of the main arraylike(CuPy or NumPy, C-contiguous,dtype), without a copy when they already fit;kernel_outputyields the buffer the kernel writes and copies it back intooutif it had to be converted.CompiledHostKernel.fallbackreturns the fallback.cunumpy/random.cuhandxp.philox_uniform,philox_uniform2,philox_normal,philox_normal2,philox4x32_10: counter-based random numbers (Philox4x32-10, passing the Random123 known-answer tests) as a pure function of(seed, stream, counter), the same in a kernel and on the host (uniform numbers bit for bit, normal numbers up to the last bits of the math functions), so kernels that draw random numbers can be compared with their host versions.CudaKernel(..., n_threads_from="first_array"): one thread per row of the first array argument when a launch gives neithern_threadsnorgrid.CudaKernellaunches withshared_memabove 48 KiB set the kernel'smax_dynamic_shared_size_bytesonce, up to the device's opt-in limit, and raiseValueErrorbeyond it.emulate_cuda_kernelemulates block shared memory (__shared__,extern __shared__withshared_mem=) and__syncthreads(the threads of a block run as coroutines and meet at every barrier), so per-block deposits, shared-memory reductions and tiled kernels can be tested without a GPU; warp intrinsics, now also in included headers, are still refused.xp.HostStaging(shape, dtype, buffers=2)andStagedCopy: copy device arrays to page-locked host buffers in the background (snapshot on the device, then an asynchronous copy on a separate stream), for output that overlaps the next time steps; stale results raise.- Documentation: a "Particle codes" guide with tested recipes (removing and sorting markers, sort-then-reduce deposits, marker exchange between MPI ranks, random numbers per particle, background output, CUDA graphs, block sizes).
xp.PyccelStructArguments:CudaStructArgumentswith a host form. A subclass names its pyccel-compiled (or any) host argument class inhost_classand the attributes passed to it inhost_fields;__host_args__()builds that object once and again when an attribute was replaced, so one object is passed to aKernelon both backends (the pyccel class itself cannot inherit from anything). On the CuPy backend__host_args__()raises unlesshost_copies = True, which builds the host object from host copies for read-only evaluations (results are not copied back). Objects holding host arrays are copied and pickled without packing;has_device_arrays()tells whether the struct can be packed.CudaStruct.from_pyccel_class(source, class_name, name=None, *, int_type, scalar_names, exclude, attribute_names): build a struct from the annotated__init__of a class in a.pyfile (or source string) by parsing it withast, for classes whose module is compiled by pyccel (the compiled class has no Python signature). Fields are named after the attributes the parameters are stored in (self.<attribute> = <parameter>);excludedrops parameters (e.g. scratch arrays).CudaKernel(..., n_threads_from=callable)(also a settable property): a launch that gives neithern_threadsnorgridtakesn_threads_from(args), e.g.lambda args: args[2].n_markers;Kernel.__call__andassert_kernels_agreeaccept a missingn_threadsthen.CudaKernel(..., check_finite=True)(also a settable property): after every launch (synchronized) the floating-point and complex arrays among the arguments, including the array fields of struct argument objects, are scanned, and a NaN or inf raisesRuntimeErrornaming the kernel and the argument. For debugging a kernel that produces NaN; costs a synchronization and a pass over the arrays per launch.cunumpy.testing.device_function_kernelaccepts struct parameters, by value (DomainArgs d) or by const reference (const DomainArgs& d), for the structs given instructs=; they are passed through to every thread unchanged, so device helpers that take argument structs can be tested from Python.- Test arguments next to the kernel:
KernelCatalog.from_package(..., test_args_suffix="_test_args")records<name>/<name>_test_args.pyasKernel.test_args_module(imported on first access asKernel.test_args;Kernel(..., test_args=...)sets it by hand). The module definesmake_args(backend, seed)andN_THREADS(an integer, a tuple, or a function of the argument tuple) orGRID, optionallyBLOCK,RTOL,ATOL,N_CALLS,OUTPUTS,SEED(cunumpy.testing.TEST_ARGS_SETTINGS).cunumpy.testing.parity_cases(catalog)gives onepytest.paramper kernel with a CUDA version, kernels without a test-arguments module markedskipwith a reason naming the missing file, andcheck_parity(kernel, **overrides)runsassert_kernels_agreewith the module's settings. A ported package's parity test is then one parametrized test, and a developer who adds a kernel adds a file, not test code. KernelCatalog.from_package(..., check_name_length=True)warns about a kernel whose module name does not fit pyccel's Fortran wrapper modulebind_c_<name>_kernelsinto Fortran's 63-character limit (FORTRAN_NAME_LIMIT): with the default suffix a kernel name has at most 48 characters.Kernel.host_parameters()reads the parameter names of a pyccel-compiled host kernel from the__pyccel__/<module>.pyistub pyccel writes next to the extension module, soKernel.check_signature()andKernelCatalog.check_signatures()also check compiled kernels.- The fake CuPy (
cunumpy._fake_cupy): a strict host stand-in for CuPy for CI machines without a GPU, installed with the environment variableCUNUMPY_FAKE_CUPY=1(read when cunumpy is imported) orcunumpy.testing.install_fake_cupy(). Its arrays live in host memory but are not NumPy arrays (numpy.asarrayraises, as for real CuPy arrays), reject host arrays and lists as CuPy does, havedata.ptr,deviceand__cuda_array_interface__, so argument objects, struct packing,as_device_array,count_transfersand backend branches run on the CuPy code path on the CPU; CUDA kernels cannot run (NotImplementedError).cunumpy.testing.fake_cupy_active()tells;requires_cupyandassert_kernels_agreeskip while it is active. xp.mpi_buffer(array, *, send=True, recv=False, cuda_aware=None): context manager yielding the buffer to hand to MPI: a host array unchanged; a device array unchanged (aftersynchronize_for_mpi) when MPI is CUDA-aware; otherwise a pinned host staging copy, copied from the device before the block (send) and back after it (recv), counted bycount_transfers().cuda_aware=Noneuses the answer recorded bympi_is_cuda_aware()(which now remembers its result) orxp.set_mpi_cuda_aware();xp.get_mpi_cuda_aware()reads it. One MPI call site for both backends and both kinds of MPI builds.xp.segment_sum(values, keys, n_segments):out[k] = sum(values[keys == k])on either backend (bincountper column), the reduction step of a sort-then-reduce accumulation; negative keys drop the value.xp.require_version("0.4.0"): raisesImportErrorif the installed cunumpy is older.Kernel(..., dispatch="arrays")andKernelCatalog.from_package(..., dispatch="arrays"): choose the CUDA kernel when an argument lives on the GPU (a CuPy array or a device-only argument object) and the host kernel otherwise, whatever the backend, for codes that hand host arrays to kernels while CuPy is active. The default,dispatch="backend", is unchanged.xp.CompiledHostKernel: a host kernel compiled on its first call by a compile function the caller provides (cunumpy does not compile anything itself, e.g. a wrapper aroundpyccel.epyccel), falling back to a given callable (or, with a warning, to the uncompiled Python function) when compilation fails.KernelCatalog.from_package(..., compile_host=..., host_fallback=...)uses it for every host kernel.Kernel.check_signature(),Kernel.host_parameters()andKernelCatalog.check_signatures(): check that a host kernel and its CUDA kernel take the same parameters in the same order, listing every kernel that differs.cunumpy.kernel_testing.emulate_cuda_kernel(kernel, *args, n_threads=...)andemulation_compiler(): run a CUDA kernel on the CPU, one thread after another, on NumPy arrays (any strides, written back), with the kernel compiled as C++ and the CUDA built-ins stubbed, so CPU-only CI can check the arithmetic of ported kernels. Kernels using shared memory,__syncthreadsor warp intrinsics are refused.Array4D<T>incunumpy/array_view.cuhand as a kernel parameter, struct field andfrom_signatureannotation ("float[:, :, :, :]"), e.g. for a 3D grid of vector components.xp.max_shared_memory_per_block(device=None, *, opt_in=False)andxp.DEFAULT_SHARED_MEMORY_PER_BLOCK: the shared memory a block may use on a device (48 KiB without a GPU).xp.rng.random_streams(cunumpy.rng.RandomStreams): one seeded generator per process and backend, with the stream(seed, rank)for MPI runs, a choice of NumPy bit generator, per-component generators and draw functions that work with NumPy and CuPy generators.- Documentation restructured into getting started, user guide (backends, backend-agnostic code, data movement, devices, MPI, profiling), kernel porting guides (
PyccelKernel,CudaKernel,Kernel/KernelCatalog, argument objects, accumulation, debugging, testing), worked examples, best practices and troubleshooting pages. cunumpy/LLM_GUIDE.md: a self-contained guide to the API and its rules for AI coding assistants, shipped as package data and rendered in the documentation.xp.CudaKernel: Wraps a CUDA C kernel (cupy.RawKernel, compiled lazily with NVRTC) so it can be called with the same arguments as the host kernel it mirrors, plusn_threads. Theextern "C" __global__signature is parsed once and every call is checked against it: argument count, array dtypes (host arrays raise, they are never copied), and scalars (Python scalars are cast to the declared C types with range checks; lossy or mismatching scalars raise instead of reaching the kernel as silently wrong values). Supportsblock_size, NVRTCoptions,include_dirs,shared_mem,stream,CudaKernel.from_file()(<name>_cuda.cu),compile()andprepare_args();check_signature=Falseskips the checks.xp.CudaArguments: Base class for argument objects that are flattened into several CUDA kernel arguments; any object with a__cuda_args__()method is flattened.xp.parse_cuda_signature(source, name)andxp.CudaParameter: Parse the parameters of a__global__function.xp.Kernel: A host kernel (PyccelKernel) and its CUDA counterpart, calling the one matching the active backend. Without a CUDA kernel on the CuPy backend it raisesNotImplementedError(missing_cuda="raise", default) or falls back to the host kernel with host copies (missing_cuda="fallback").xp.KernelCatalog: Read-only mapping ofKernels;KernelCatalog.from_package()collects them from a package with one folder per kernel (name/name_kernels.py,name/name_cuda.cu);without_cudalists the kernels still to port.xp.CudaStructArguments: Base class for argument objects that are passed to CUDA kernels as one C struct (the class form ofCudaStruct). A subclass setsstruct_nameandfields, stores each field as an attribute and callspack(); theCudaStructis built once per class (cls.struct), and__cuda_args__()returns the packed struct. The struct is packed again automatically at the next use when a field attribute changed (another array address, shape or strides, or another scalar value), so fields can be properties that follow an owner's resized arrays; copies and unpickled objects are packed again from their own arrays.- Debug mode no longer synchronizes after a launch while the stream is being captured into a CUDA graph, which would invalidate the capture.
xp.scipy: SciPy for the active backend,scipyon NumPy andcupyx.scipyon CuPy, resolved at every access (fft,fftpack,interpolate,linalg,ndimage,signal,sparse,sparse.csgraph,sparse.linalg,spatial,special,stats). A name missing on the active backend raisesAttributeErrornaming the backend;available(name)checks without raising;resolve()returns the module. SciPy stays an optional dependency.xp.fuse: Decorator that compiles an elementwise function into one kernel withcupy.fusewhen it is called with CuPy arrays (with the CuPy backend active while tracing) and calls it unchanged otherwise.xp.petsc_vec(array, comm=None): Apetsc4pyvector sharing the memory of a NumPy or CuPy array through DLPack (a CUDA or HIP vector for a CuPy array), never copying; raises instead of falling back to a host copy when petsc4py has no GPU support, or when the dtype or layout would need a copy.cunumpy/reduce.cuh: Warp and block reductions for CUDA kernels (cunumpy_warp_sum/min/max,cunumpy_block_sum/min/max, andcunumpy_block_sum_to(out, v)with one atomic add per block), for in-kernel diagnostics and per-block accumulation.CudaStruct.verify_layout(include=None, *, include_dirs=(), options=())andCudaStruct.layout_source(): Compile and run a one-thread kernel that reportssizeof,alignofand the field offsets of the struct as the CUDA compiler lays it out, and raiseValueErrorif they differ from the NumPydtypethat values are packed into; withincludethe struct is defined by a header instead ofdeclaration.xp.CudaStructandxp.CudaStructValue: C structs passed to CUDA kernels by value. ACudaStructis defined once from(field, C type)pairs; it provides the Cdeclaration, the NumPydtypewith the C memory layout, and packs values (device arrays as addresses, scalars checked and cast) into aCudaStructValuethat is passed as one kernel argument.CudaKernel(..., structs=[...])checks struct parameters and that a struct definition in the source matches.CudaKernel(..., template_args=...): Instantiate C++ function templates (e.g.template_args=(np.float64, 3)forname<double, 3>); the template parameters are substituted into the checked signature.xp.CudaKernelVariants: Creates and caches oneCudaKernelper variant key for generated kernel sources (e.g. per dimension and dtype);compile_all()compiles given and existing variants.xp.ctype_of(dtype): The C type of a NumPy dtype, e.g. for generating CUDA source.- 1D to 3D launches:
CudaKernelaccepts a tupleblock_size, and calls taken_threadsas an integer or tuple, or an explicitgrid, plus a per-callblock;launch_shape()returns the(grid, block)of a call. Dynamic shared memory (shared_mem) andstreamare passed through byKernelas well. - Compiling at setup:
CudaKernel.compile()andis_compiled,Kernel.compile(), andKernelCatalog.compile_all(). Kernel(..., host_options=...)andKernelCatalog.from_package(..., host_options=...):PyccelKerneloptions (e.g.object_modules,outputs) for the host kernels, for all kernels or per kernel name; needed for the fallback to find device arrays inside application objects.xp.local_rank(): The node-local rank from the MPI launcher's environment (Open MPI, MVAPICH2, Intel MPI/MPICH, PMI, Cray PALS, Slurm,LOCAL_RANK), available beforeMPI_Init.xp.bind_local_device(): Selects the GPUlocal_rank() % device_count()and creates its context, beforeMPI_Init, for one-rank-per-GPU MPI programs.KernelCatalog.summary()(alsostr(catalog)) andKernelCatalog.with_cuda: One line on the porting status,"CUDA kernels: 3 of 60 (missing: a, b, c)"(at most 10 missing names, then...), and the names of the ported kernels, mirroringwithout_cuda.CudaKernel.all_from_file(path, **kwargs)andxp.cuda_kernel_names(source): Load every__global__function of a file as aCudaKernel(adictby name, sharing the source so CuPy compiles the file once), and list the__global__functions of a source string.KernelCatalog.from_packagestill uses only the function<name>of<name>_cuda.cu; other kernels in the file are ignored by the catalog.xp.synchronize_for_mpi(*arrays): Waits for pending work on the current stream before MPI uses device buffers (no-op for host buffers and on the NumPy backend).- CUDA headers shipped as package data, found by every
CudaKernelautomatically (xp.cuda_include_dir()for other compilers):cunumpy/array_view.cuhdefines the strided viewsArray1D<T>,Array2D<T>,Array3D<T>(data,shape[],strides[]in elements,a(i, j),size(), bounds checks with-DCUNUMPY_BOUNDS_CHECK), so ported pyccel kernels indexmarkers(ip, j)instead of computing offsets from hand-passed sizes;cunumpy/index.cuhdefinesCUNUMPY_THREAD_1D(i, n)(2D/3D likewise) and the grid-stride loopCUNUMPY_GRID_STRIDE_1D(i, n). - Array view parameters and struct fields:
CudaKernelsignatures andCudaStructfields acceptArray1D<T>toArray3D<T>of the scalar C types (CudaParameter.view_ndim). Such a parameter takes a CuPy array of the declared dtype and number of dimensions, contiguous or not, and is packed into (pointer, shape, strides in elements) with the memory layout of the C struct; dtype and ndim mismatches raise.CudaStruct.has_viewstells whether the declaration needs#include "cunumpy/array_view.cuh". CudaStruct.from_signature(func, name, *, int_type="long long", scalar_names=None): Builds a struct from the pyccel-style annotations of a Python function (typically an argument class's__init__;selfis skipped):"float[:, :]"->Array2D<double>,"int[:]"->Array1D<long long>,int->int_type,float->double,bool->bool;Final[...]andconstare ignored. The Python class becomes the one definition of the arguments on the host and on the device.CudaStruct.to_header(path=None, *, guard=None, includes=())andxp.write_cuda_header(path, structs, guard=None, *, includes=()): Generate a header with include guard, thecunumpy/array_view.cuhinclude when needed, and the struct definitions; the header can be written at setup and a test can assert that the committed file equals the generated one.xp.DeviceMirror(host_array): Pairs a host NumPy array owned by another library (e.g. a stencil vector's_data) with a lazily allocated device copy.deviceis the CuPy array kernels write into on the CuPy backend, and the host array itself on the NumPy backend, so accumulation code is written once without copies on the CPU.to_device()andto_host()copy explicitly and in place (the host array keeps its identity; no-ops on NumPy),zero()clears the buffer, andrebind()follows a reallocation by the owner; a host array whose shape or dtype changed raisesValueError. Non-NumPy inputs raiseTypeError.cunumpy/atomic.cuh: CUDA header shipped with the package, withcunumpy_atomic_add(double*|float*, value)(atomicAdd, with a compare-and-swap fallback fordoublebefore sm_60) and the indexedcunumpy_atomic_add_2d()/cunumpy_atomic_add_3d()for C-contiguous arrays, for many-threads-to-one-cell accumulation.xp.cuda_include_dir(): The directory of the shipped CUDA headers;CudaKerneladds it to its NVRTC options automatically (once), so sources can#include <cunumpy/atomic.cuh>.cunumpy.testing: Helpers for testing host/CUDA kernel pairs with pytest (pytest is imported only when its objects are used, never byimport cunumpy).requires_cupyis askipifmarker for tests that need a GPU,BACKENDS = ["numpy", pytest.param("cupy", marks=requires_cupy)]parametrizes a test over the backends, and thebackendfixture runs a test once per backend with that backend active.cunumpy.testing.assert_kernels_agree(kernel, make_args, *, n_threads=..., rtol=1e-12, atol=0.0, n_calls=1, outputs=None, seed=0): Builds the arguments withmake_args(backend, seed)on the NumPy and the CuPy backend, runs the host and the CUDA kernel of aKernel, and compares the arrays they wrote (the declaredoutputs, or every array argument, including arrays held by argument objects) withnumpy.testing.assert_allclose, naming the differing argument. Skips the test without a GPU and returns the host arrays.KernelCatalog.parity_cases(): The(name, kernel)pairs of the kernels with a CUDA version, so one test parametrised with them andassert_kernels_agreecovers a whole catalog.cunumpy.testing.device_function_kernel(header_source, signature, *, name=None, includes=(), n_threads_param="n"): Generates an elementwiseextern "C" __global__wrapper around a__device__function given its C prototype (pointer parameters are shared, scalar parameters become per-thread arrays, the return value goes intoout), so device helpers can be tested from Python against their host versions without a hand-written test kernel.xp.mpi_is_cuda_aware(comm=None): Collective startup check of whether the MPI library can pass device buffers: each rank exchanges a tiny CuPy array withSendrecvand the ranks agree withallreduce; any failure givesFalse. ReturnsFalseon the NumPy backend and without a functional CuPy, without importingmpi4py.xp.require_cuda_aware_mpi(comm=None): RaisesRuntimeError, with hints on obtaining a CUDA-aware build, whenmpi_is_cuda_aware()fails on the CuPy backend; no-op on NumPy.xp.nvtx_range(name, color=None): Context manager and decorator marking a code region as an NVTX range (cupy.cuda.nvtx.RangePush/RangePop), so it shows up innsys/Nsight next to the kernels it launches; no-op on the NumPy backend or without NVTX. The range is popped when the block raises.xp.timed_region(name, sync=True)andxp.Timing: Context manager timing a code region including the device work it queues: on the CuPy backend it synchronizes before reading the clock (wall-clock timers around launches otherwise measure the launch, not the kernel), and pushes an NVTX range of the same name. Yields aTimingwithname,elapsed(seconds) andsynced.xp.count_transfers(): Context manager yielding aTransferCounterthat records every host/device transfer made through cunumpy in the block, with the call site of each:to_numpy/to_cunumpyof a device array (to_host),to_cupy/to_cunumpyof a host array (to_device),PyccelKernelcalls that copy device arrays to the host (kernel_conversions, one per call) andKernelcalls that fall back to the host kernel on the CuPy backend (fallbacks).counter.total,counter.events(TransferEvent(kind, description, where)) andcounter.report()(events grouped by kind and call site) let a test verify that a time step does not transfer. Counters nest; calls that do not copy (e.g.to_numpyof a NumPy array) are not counted. Transfers that bypass cunumpy (rawcupy.ndarray.get(),cupy.asarray(numpy_array), conversions inside other libraries) are not seen.xp.assert_no_transfers(): Context manager raisingAssertionErrorwith the counter's report if the block makes a transfer through cunumpy.- CUDA debug mode:
CudaKernel(..., debug=True),xp.set_cuda_debug(True), the context managerxp.cuda_debug()or the environment variableCUNUMPY_CUDA_DEBUG=1compile kernels with-lineinfoand-DCUNUMPY_BOUNDS_CHECK(xp.DEBUG_OPTIONS;-Gis not available with NVRTC) and synchronize the stream after every launch, so an asynchronous CUDA error (illegal memory access, launch failure) is raised as aRuntimeErrornaming the kernel and its launch shape instead of surfacing at a later.get()or MPI call.xp.get_cuda_debug()reads the global setting, which applies to kernels created withdebug=Noneat every launch;CudaKernel.debug,debug_active()andcompile_options()expose a kernel's setting and the options a compilation uses. - Header-aware compile cache:
xp.resolve_includes(source, include_dirs, base_dir=None)lists the#include "..."files of a CUDA source recursively (resolved relative to the including file, then ininclude_dirs; cycles, system headers and missing files are ignored), andxp.include_hash(paths)is a short digest of their contents.CudaKernelexposesincluded_headers,include_dirs,source_dir(set byfrom_file, or the newsource_dirkeyword) andcompile_options(). cunumpy.testing: Helpers for testing host/CUDA kernel pairs with pytest (pytest is imported only when its objects are used, never byimport cunumpy).requires_cupyis askipifmarker for tests that need a GPU,BACKENDS = ["numpy", pytest.param("cupy", marks=requires_cupy)]parametrizes a test over the backends, and thebackendfixture runs a test once per backend with that backend active.cunumpy.testing.assert_kernels_agree(kernel, make_args, *, n_threads=..., rtol=1e-12, atol=0.0, n_calls=1, outputs=None, seed=0): Builds the arguments withmake_args(backend, seed)on the NumPy and the CuPy backend, runs the host and the CUDA kernel of aKernel, and compares the arrays they wrote (the declaredoutputs, or every array argument, including arrays held by argument objects) withnumpy.testing.assert_allclose, naming the differing argument. Skips the test without a GPU and returns the host arrays.KernelCatalog.parity_cases(): The(name, kernel)pairs of the kernels with a CUDA version, so one test parametrised with them andassert_kernels_agreecovers a whole catalog.cunumpy.testing.device_function_kernel(header_source, signature, *, name=None, includes=(), n_threads_param="n"): Generates an elementwiseextern "C" __global__wrapper around a__device__function given its C prototype (pointer parameters are shared, scalar parameters become per-thread arrays, the return value goes intoout), so device helpers can be tested from Python against their host versions without a hand-written test kernel.xp.as_device_array(value, dtype=None, ndim=None, *, name=None): The "reference or copy once" rule for building CUDA argument objects: a CuPy array that already has the requested dtype and is C-contiguous is returned unchanged, anything else (tuples, lists, host arrays, other dtypes, non-contiguous views) becomes one C-contiguous device copy. RaisesRuntimeErroron the NumPy backend, so host data is never copied to the device implicitly, andValueErrorifndimdoes not match.CudaKernelpointer parameters andCudaStructpointer fields now also reject non-C-contiguous arrays withTypeError: a kernel reads a pointer as a flat buffer, so a view such asa[:, 0:3]would give silently wrong results.xp.KernelArgumentsandxp.resolve_host_args(args, kwargs=None): Argument objects with a host and a device form. An object whose type defines__host_args__()is replaced by its result (the object the host kernel receives, e.g. a Pyccel class of NumPy arrays) byKernelon the host path and byPyccelKernel(so themissing_cuda="fallback"path works too); on the CuPy backendCudaKernelflattens the same object via__cuda_args__(). Owners can expose onekernel_argsproperty that builds each form lazily, so call sites never branch on the backend and CPU runs never build device arguments.
xp.get_backend()now returns the active global backend, mirroringxp.set_backend(). Use the newxp.get_array_backend(array)to inspect an individual array. Calls to the formerxp.get_backend(array)must be updated.- Expanded the README and documentation with backend selection, array conversion, GPU controls, kernel adaptation, and Pyodide examples.
- GPU shape round-trip coverage now creates a zero-dimensional NumPy array for the scalar case instead of calling
.astype()on a Python float. - GPU tests now account for CuPy's retained split memory blocks and provide an array conversion method on the custom host-array test fixture.
set_backend()anduse_backend()now reject unsupported backend names withValueErrorwithout changing the active selection.
xp.get_array_module(array): Return the array-api-compat module (numpy/cupy) matching a given array's own backend, regardless of the process-wide active backend. Mirrorscupy.get_array_moduleand works in Pyodide.xp.get_rng(seed=None): Return anumpy.random.Generator/cupy.random.Generatormatching the active backend, without having to branch on the backend yourself.xp.device_count(): Number of visible CUDA devices (0without a functional CuPy/CUDA install), independent of the currently active backend.xp.set_device_for_rank(rank, devices_per_node=None): Convenience for one-MPI-rank-per-GPU codes; selectsrank % devices_per_node(defaultingdevices_per_nodetodevice_count()) viaset_device()and returns the chosen device id.xp.memory_info():(free, total)bytes of memory on the active CUDA device, orNoneon the NumPy backend.xp.free_memory(): Release all free blocks held by CuPy's device and pinned-host memory pools (no-op on the NumPy backend).xp.default_float_dtype(): Return the active backend'sfloat64dtype object, for pinning a portable float precision instead of the backend/platform-dependentdtype=float.xp.stream(): Context manager for a CUDA stream, to overlap host/device transfers with compute (no-op, yieldingNone, on the NumPy backend).xp.pin_memory(array): Copy a host array into pinned (page-locked) CUDA host memory for faster transfers.PyccelKernel(..., is_array=...): Extension point overriding the defaultisinstance(value, np.ndarray)check used to decide which host values returned by (or reachable from a declared output of) the wrapped kernel are converted back to the device -- for kernels that return/mutate a NumPy subclass or other custom host array type.- Pyodide NumPy support documentation and CI that installs the built wheel in Pyodide's WebAssembly runtime and runs compiler-free tests for arrays, conversions, contexts, and Python kernels without CuPy or Pyccel imports.
test-compiledextra for native Pyccel tests. Thetestextra is now compiler-free;devcontinues to include compiled-test dependencies.xp.same_backend(*arrays): ReturnTrueif all given arrays live on the same backend.xp.assert_same_backend(*arrays): RaiseTypeErrorwith a clear message if the given arrays don't all live on the same backend, instead of letting a mixed-backend operation fail with a confusing backend-internal error.xp.PyccelKernel: Wraps a kernel compiled with pyccel (which only accepts NumPy arrays) so it can be called with CuPy arrays. Arguments are copied to the host before the call, in-place kernel updates are copied back to the device, and returned arrays are moved back to the device. On the NumPy backend the kernel is called directly, without conversion. Tuples, lists and dicts are traversed recursively; passobject_modules=("your_package.",)to also traverse the attributes of your own objects. Passoutputs=(5,)(indices for positional arguments, names for keyword arguments) to declare which arguments the kernel writes to, so only those are copied back to the device instead of every converted array;outputs=()declares none. Conversion is identity-aware: an array reachable by several paths (passed twice, or both directly and as an object attribute) becomes a single host array, so the kernel sees the aliasing the caller intended and in-place updates are not lost; reference cycles are handled rather than recursed into.
xp.set_device(device_id): Select the active CUDA device for the current process (no-op on the NumPy backend).xp.__version__: Reports the installedcunumpypackage version.
ArrayBackendno longer silently reports"cupy"as the active backend when CuPy was requested but is unavailable; it now correctly falls back to reporting"numpy"soxp.cupy_backend/xp.numpy_backendreflect what actually loaded.to_numpy()no longer misdetects CPU objects that merely expose a.getmethod (e.g. dict-like objects) as CuPy arrays; it now checksget_backend()instead ofhasattr(array, "get").- Invalid backend names now raise
ValueErrorinstead of relying on a bareassert, which was previously stripped underpython -O.
- Removed the redundant
ArrayBackend.__init_post__double-initialization path. ArrayBackenddocuments that it is not thread-safe (global mutable backend state).- CI now runs the test suite across a Python 3.8/3.10/3.13 matrix instead of only 3.10, and
ruffis now an enforced check rather than advisory. - Added
array-api-compatas a core dependency:get_backend()/is_gpu()/is_cpu()now usearray_api_compat.is_cupy_array()instead of sniffingtype(array).__module__for the substring"cupy".- The active backend module (
xp.xp) and array conversions (to_numpy(),to_cupy()) now resolve througharray_api_compat.numpy/array_api_compat.cupyinstead of the raw modules, for standard-conformant behavior across backends (e.g.xp.xp.__name__is now"array_api_compat.numpy"/"array_api_compat.cupy"rather than"numpy"/"cupy"). Device/synchronization control (set_device(),synchronize(),cupy_available()) still uses rawcupy, since CUDA device management isn't part of the Array API standard.
- Backend Management Helpers:
xp.to_numpy(arr): Explicitly move an array to CPU (NumPy).xp.to_cupy(arr): Explicitly move an array to GPU (CuPy).xp.to_cunumpy(arr): Normalize an array to the currently active backend.xp.get_backend(arr): Identify if an array is"numpy"or"cupy".xp.is_gpu(arr)&xp.is_cpu(arr): Quick boolean checks for array residence.
- Global Backend Control:
xp.set_backend(name): Globally switch the active backend at runtime.xp.use_backend(name): Context manager for temporary, scoped backend switching.xp.numpy_backend&xp.cupy_backend: Boolean properties to check the globally active backend.
- Synchronization:
xp.synchronize(): Blocks until GPU operations are complete (no-op on CPU). Essential for accurate benchmarking.
- Developer Experience:
- Added
isortconfiguration topyproject.tomlwithblackprofile compatibility. - Reorganized test suite into specialized files:
test_numpy.py,test_cupy.py, andtest_cunumpy.py.
- Added
- Dynamic Dispatch Architecture: Refactored
src/cunumpy/xp.pyto use module-level__getattr__. This ensures thatcunumpy.<op>calls always resolve to the currently active backend module, enabling seamless runtime switching viaset_backend. - Type Safety: Updated
src/cunumpy/__init__.pyistubs to provide full IDE autocompletion and type-checking for all new API methods. - Documentation:
- Simplified
README.mdand documentation to exclusively focus on PyPI installation (pip install cunumpy). - Enhanced
quickstart.mdandapi.mdwith usage examples for the new backend control and synchronization features.
- Simplified
- CI/CD: Restricted GitHub Pages documentation deployment to the
develbranch only.
- Improved
ArrayBackendinitialization to fallback gracefully to NumPy if CuPy is requested but not installed. - Fixed symbol accessibility tests to correctly handle custom helper methods in the
cunumpynamespace.
- Type Inspection Support: Added
.pyistub files to enable proper symbol inspection and autocompletion for Pylance/VS Code. - CI/CD: Added GitHub Action for automated publishing to PyPI.
- Improved import structure in
src/cunumpy/__init__.pyto allow direct access toxp.
- Initial Core Functionality:
ArrayBackendclass for dispatching between NumPy and CuPy.- Environment variable support (
ARRAY_BACKEND) for selecting the backend. - Basic module structure and
src/cunumpy/xp.py.
- Project Scaffold:
- Documentation setup with Sphinx and nbsphinx.
- Initial unit tests and testing infrastructure.
- Basic tutorial notebook and README instructions.
- Metadata: Initial configuration of
pyproject.tomland project metadata.