Skip to content

Latest commit

 

History

History
597 lines (549 loc) · 70.6 KB

CHANGELOG.md

File metadata and controls

597 lines (549 loc) · 70.6 KB

Changelog

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.

[Unreleased]

Added

  • 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.c next to the Pyccel version (the same arguments; arrays as pointer and shape). CCache (in KernelPackage.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_report and python -m cunumpy.threads; spinning BLAS threads slowed the OpenMP kernels run after a BLAS call. Needs threadpoolctl>=3.7.
  • PyccelCache takes extra C compiler flags from <PREFIX>_FLAGS (flags_env, flags()), passed to pyccel compile --flags and part of the build key, e.g. -march=native for the machine at hand. None by default.
  • CUDA kernels written in Python: xp.kernels.CupyJitKernel (cupyx.jit) and xp.kernels.NumbaCudaKernel (numba-cuda), launched like a CudaKernel (n_threads, grid, block, shared_mem, stream, launch size from the first array). Device arrays only (NumPy arrays raise instead of being copied), CudaArguments flattened, the number of arguments checked; numba-cuda launches on CuPy's current stream. A Kernel takes them as cupy_jit_kernel= and numba_cuda_kernel=, and kernel folders as <name>_cupy_jit.py and <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_implementation takes these names (DEVICE_IMPLEMENTATIONS) besides "cuda" (any of them, no host fallback). assert_kernels_agree compares every device implementation with the host kernel (implementations= to choose). The fake CuPy emulates cupyx.jit on 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 @inline Pyccel blocks under OpenMP, no min/max, -0.0 for 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): PyccelCache builds those modules with the kernel (copied under flat names, imports rewritten, so Pyccel also inlines their @inline functions, 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.

Changed

  • CudaKernel.from_file(path) without a name works with any file name: it takes the file name minus _cuda_c.cu, _cuda.cu or .cu if 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 Kernel is called "cuda_c" in Kernel.implementations and Kernel.selected(device=True) (was "cuda"); "cuda" remains the setting that requires any device implementation. Kernel.has_cuda, KernelCatalog.with_cuda and parity_cases count Python device kernels too, and the repr of a Kernel lists its device implementations.
  • Kernel.from_folder (and KernelPackage.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 imports pyccel.stdlib.internal.openmp in 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 and outputs="annotations" come from the new HostImplementations.reference: the Python version, else the NumPy or numba one.

[0.8.0] - 2026-11-16

Added

  • Faster hot paths for particle codes: host segment sums with np.add.reduceat (sorted keys) and np.bincount (unsorted), up to 10x faster for three components; deterministic CUDA segment sums for sorted keys; sort_by_key(..., out=...); Kernel.resolve(*args) and PyccelKernel.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(...), a BoundLaunch for repeated launches; and CUDA graphs (capture_graph).
  • The interop adapters convert nested containers and scalar objectives.
  • The scope_profiler.opt_in_tags entry point.
  • cunumpy.interop.julia (extra cunumpy[julia], juliacall): to_julia / from_julia between NumPy arrays and Julia Arrays 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 | False on every interop conversion (as in the array API): False raises when the conversion cannot share memory, True always copies.
  • supports_float64(device) in the JAX, PyTorch and MLX adapters and cunumpy.interop.jax.enable_x64().

Changed

  • 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 a TypeError with advice instead of becoming float32. MLX keeps float64 for device=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 memory device_copy (before, every conversion was a device_copy).
  • from_framework copies between host and device explicitly (a recorded transfer, an error under copy=False) instead of falling back to asarray silently, and a framework that cannot take an array's device raises a ValueError naming the device.
  • from_jax raises a clear TypeError for traced values (inside jax.jit, grad, vmap).
  • to_mlx(device=...) names the device the array is meant for (MLX arrays have no device); before, it passed device to mlx.core.array, which does not take it.

Fixed

  • The fake cupy.random no longer answers dunder names (__file__, ...) with a wrapped NumPy function, which broke module introspection: importing astropy after cunumpy failed under CUNUMPY_FAKE_CUPY.

[0.7.2] - 2026-10-27

Fixed

  • PyccelCache imports 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 to libpython in a Python that has it built in, such as uv's CPython 3.12 on macOS), is a RuntimeError and is not stored, instead of a segmentation fault in every process that loads it.
  • The PyccelCache key includes the NumPy version, so environments that share an interpreter but not NumPy no longer share builds.

Added

  • xp.kernels.KernelPackage(name): the PyccelCache and the Kernel.from_folder options shared by the kernel folders of one package (host_suffix="_pyccel", dispatch="arrays", block_size=256, n_threads_from="last_axis"), with from_folder(package, **overrides) and metal_kernel(...) (float32 MetalKernels 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, for include_dirs of a CUDA kernel that includes another package's header.
  • xp.cuda.shared_memory_fits(num_values, itemsize=8): whether a per-block buffer fits DEFAULT_SHARED_MEMORY_PER_BLOCK.
  • scope-profiler regions around the coarse operations (Kernel calls as cunumpy.kernel.<name>, CUDA and Pyccel compilation, sort_by_key, SegmentPlan.sum, compact_by_mask, morton_keys, the solvers, exchange, and the device copies of mpi_buffer and DeviceMirror), behind the opt-in tag cunumpy: off unless the application enables it, e.g. sp.setup(enable_tags=["cunumpy"]) or SCOPE_PROFILER_ENABLE_TAGS=cunumpy. New dependency: scope-profiler>=0.7.5.

Changed

  • xp.algorithms.sort_by_key gathers a 2-D NumPy array along its last axis (component-major markers, axis=-1) row by row, about 2x faster than take (1e6 markers: 3 rows 12.9 to 6.7 ms, 8 rows 37 to 19 ms).

[0.7.0] - 2026-10-20

Added

  • xp.kernels.kernel_outputs(*outs, like=..., dtype=..., strided=...): the buffers of several kernel outputs in one block, each written back into its array (as kernel_output does) when the block ends without an error.
  • xp.kernels.PyccelCache(name): compiles a Pyccel kernel module once with pyccel compile and 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 the compile_host of Kernel.from_folder and KernelCatalog.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, and backend_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 by pyproject.toml).
  • xp.optimize.newton: Newton's method or the secant method on many independent scalar equations at once, with the steps of scipy.optimize.newton for an array x0, 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), so xp.scipy code runs its CuPy path without a GPU. Every cupyx.scipy subpackage has only the names the oldest supported CuPy (14.0.0) provides, so e.g. special.jv or sparse.csr_array fails as on a GPU. testing/cupyx_names.py and tests/unit/test_cupyx_names.py check these names against the installed CuPy in the GPU CI. cupyx.empty_pinned/zeros_pinned return NumPy arrays.
  • xp.optimize.fsolve, root, minimize and xp.integrate.quad, odeint (cupyx.scipy has neither): SciPy on the host with SciPy's arguments, the callbacks get their arrays on the backend of x0/y0, and results come back on that backend.
  • xp.scipy.linalg.solve_circulant on the CuPy backend, which cupyx.scipy lacks: 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-written api.md is now a short overview, and the CUDA headers have their own page. CI checks the docstrings (ruff D rules, numpydoc validation), runs their examples as doctests, and builds the docs with warnings as errors. Docstring style: docs/source/contributing.md.

Fixed

  • as_kernel_array gives 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.scipy can be copied with copy.copy and copy.deepcopy (also inside a copied container), as real CuPy splines can.
  • xp.algorithms.segment_sum and SegmentPlan.sum work 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_signature accepts quoted pyccel annotations (markers: "float[:, :]") in modules with from __future__ import annotations.

Changed

  • 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 .html URLs redirect, and make docs-build builds it. The docs extra is now only griffe; pre-commit and pyproject-fmt moved to dev. The #: comments of public constants are now attribute docstrings.

[0.6.3] - 2026-10-08

Fixed

  • The emulation of kernels with __syncthreads compiles with GCC on macOS.
  • Preserve Fortran order when copying CuPy arrays to the host through to_numpy, host_call, evaluate_on_host, and PyccelKernel conversions.

Added

  • emulate_cuda_kernel compiles 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 raises RuntimeError, but a segmentation fault now ends the process.
  • Inside emulated_launches(), CudaKernel.compile() (and so recompile(), CudaKernelVariants.compile_all() and KernelCatalog.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; patching CudaKernel.compile is no longer needed.
  • The emulation compiles inline PTX (asm(...), asm volatile(...)) as a trap, so a kernel with an asm("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 marker requires_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.TransferBudget counts transfers per phase of a program (budget.phase(name), the decorator budget.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).
  • TransferEvent has blocking (False for to_host_async() and HostStaging.copy()) and implicit (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 returned memory.HostCopy has ready() (never waits) and result().
  • kernel_testing.emulated_launches() runs every CudaKernel launch 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_kernel now accepts struct parameters (a mapping of field values, a CudaStructValue, 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=1 makes the GPU markers of kernel_testing fail instead of skipping: requires_cupy, the cupy run of the backend fixture (which activates CuPy strictly) and assert_kernels_agree. New kernel_testing.cuda_required().
  • count_transfers() records sync events (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 in counter.syncs and the report but not in total; assert_no_transfers(syncs=True) rejects them. The real CuPy's own float(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 along axis, in place and in order, and returns their number; axis=-1 compacts component-major (ncomp, N) and (N,) arrays together.
  • as_kernel_array(..., strided=True) and kernel_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 new parameters=); a Kernel supplies those of its host function. xp.kernels.outputs_from_annotations() reads the outputs from the annotations (not Final, const or a scalar), and Kernel.from_folder() / KernelCatalog.from_package() take outputs= (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.MetalKernel runs 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 by xp.profiling.count_transfers(). xp.kernels.metal_available() tells whether it can run.
  • xp.host_call, xp.evaluate_on_host and xp.setup_on_host run 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 by xp.profiling.count_transfers().

Changed

  • The launcher detection and the serial MPI stand-in moved to the new package maybempi, a dependency of cunumpy. xp.mpi re-exports them (get_mpi, launched_under_mpi, local_rank, SerialMPI, SerialComm, ...), plus the new xp.mpi.is_serial. The override variable is now MAYBEMPI=1/0; CUNUMPY_MPI is no longer read.
  • CudaKernel and CudaKernelVariants moved to cunumpy.kernels, next to Kernel and PyccelKernel. The argument classes CudaArguments, CudaStruct, CudaStructArguments, CudaStructValue and write_cuda_header moved to the new cunumpy.arguments. cunumpy.cuda keeps the device runtime and the CUDA source tools. The old cunumpy.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.fuse as cunumpy's, ...; use xp.kernels, xp.arguments, xp.cuda, xp.mpi, xp.rng, xp.algorithms, xp.profiling, xp.memory and xp.petsc), and the modules cunumpy.testing (now cunumpy.kernel_testing), cunumpy.kernel, cunumpy.dispatch and cunumpy.cuda_kernel (public names are in cunumpy.kernels and cunumpy.arguments). Also removed the placeholder cunumpy.main. xp.fuse is now CuPy's own fuse.
  • Removed kernels.KernelArguments, kernels.resolve_host_args, kernels.PyccelStructArguments and the __host_args__() protocol, with no replacement. Kernels receive argument objects as they are. Write the host argument class (e.g. pyccel) and a CudaStructArguments with 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_IMPLEMENTATION to CUNUMPY_HOST_KERNEL_IMPLEMENTATION to make its host-only scope explicit. The former environment variable is no longer read; update job scripts. CUDA dispatch is unchanged.
  • Rename the kernels selection functions to set_host_kernel_implementation, get_host_kernel_implementation, and use_host_kernel_implementation. The former function names are removed without compatibility aliases.

Added

  • Strided and C-contiguous CUDA array views through 16 dimensions, including Array5D/Array6D for matrix accumulations. Higher-dimensional views work as kernel parameters, struct fields, annotations and in CPU emulation.
  • C-contiguous array views CArray1D<T> to CArray16D<T> in cunumpy/array_view.cuh. They hold a pointer and shape only, so a(i, j) is data[i * shape[1] + j]. As kernel parameters or struct fields, they reject non-contiguous arrays and never copy them. CudaStruct.from_signature and from_pyccel_class take contiguous=True or field names to generate them.
  • Device implementation selection via kernels.set_device_kernel_implementation, get_device_kernel_implementation, use_device_kernel_implementation, and CUNUMPY_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, and wait_event, with synchronous host equivalents; cuda.stream(existing) selects an existing stream.
  • mpi.MPIStaging reuses host staging storage and rejects overlapping device uses.
  • algorithms.cell_offsets, segment_boundaries, and SegmentPlan for prepared grouping.
  • Strict backend selection via set_backend/use_backend(..., strict=True) and JSON-compatible backend_info() diagnostics.
  • cunumpy/scan.cuh inclusive/exclusive warp and block prefix sums, mask-aware warp reductions, partial-warp block reductions, and integer atomic-add helpers.

Execution 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.

Changed (breaking, with deprecation)

  • The helpers moved from the top level of cunumpy to 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.fuse hid cupy.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) and cunumpy.petsc (petsc_vec). All are imported by import cunumpy. The old top-level names still work and raise a DeprecationWarning naming the new place; they will be removed in 0.6.
  • cunumpy.testing is now cunumpy.kernel_testing. Once imported, cunumpy.testing replaced NumPy's xp.testing, so xp.testing.assert_allclose failed in every test that ran after an import cunumpy.testing. cunumpy.testing still works, with a DeprecationWarning, until 0.6.
  • Importing cunumpy.cuda makes xp.cuda the cunumpy submodule instead of CuPy's cupy.cuda; use import cupy for 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, _algorithms split off cunumpy.xp), so every public name has one import path, through the submodules above. cunumpy.cuda_kernel, cunumpy.dispatch and cunumpy.kernel (in 0.3.0) still import, with a DeprecationWarning, until 0.6. cunumpy.xp keeps the backend selection and array conversion only.

Performance

  • xp.<name> for a NumPy/CuPy function (xp.zeros, xp.add, ...) is a plain attribute lookup, as fast as numpy.<name> (before: about 3 us per access through the module __getattr__, 20 times numpy.add). The public names of the active backend module are copied into the cunumpy namespace and replaced when set_backend/use_backend change 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.

Development

  • Formatting is checked with ruff format and import order with ruff's isort rules (ruff check), on src/ and tests/, instead of black and isort; the dev extra installs ruff.
  • GPU matrix/FFT correctness tests check numerical parity without timing assertions; performance comparisons belong in scope-profiler.

Fixed

  • 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_agree reads CudaStructArguments objects 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").

Removed

  • Support for Python 3.8 and 3.9 (both end-of-life); cunumpy now requires Python 3.10 or newer.

Changed

  • Renamed the startup backend selector from ARRAY_BACKEND to CUNUMPY_BACKEND; update batch-job environments. CuNumpy-owned environment options use CUNUMPY_*.
  • Kernel(..., dispatch="arrays") calls the host kernel directly for host arguments, without PyccelKernel's check for device arrays to convert, which converted nothing but ran while CuPy was the active backend (unless the PyccelKernel was built with use_cupy=True).
  • Kernel.check_signature() (and KernelCatalog.check_signatures()) also compares the parameters of every host implementation (numba, NumPy; nothing is compiled) and of a CompiledHostKernel's fallback with those of the host kernel.
  • KernelCatalog.from_package(..., compile_host=..., host_fallback=...) builds HostImplementations instead of CompiledHostKernels: host_fallback becomes the "numpy" implementation, and <name>_numba.py/<name>_numpy.py files in a kernel folder are picked up.
  • CudaKernel pointer and array view parameters and CudaStruct pointer and view fields reject an array that lives on another CUDA device than the current one (ValueError; cupy.RawKernel would read the foreign address silently). Checked only when CuPy is imported and the array reports a device.
  • assert_kernels_agree(..., n_threads=...) also takes a function of the argument tuple, and n_threads may be omitted when the CUDA kernel has n_threads_from.
  • NumPy integer scalars passed to integer kernel parameters (and struct fields) are checked by value, like Python ints: np.int64(5) fits an int parameter; before, they raised TypeError unless their dtype was exactly the parameter's.
  • Python 3.14 is supported.
  • The test extra installs SciPy, so the xp.scipy tests run in CI instead of being skipped.
  • KernelCatalog.compile_all(jobs=1) and CudaKernelVariants.compile_all(keys, jobs=1): With jobs > 1 the CUDA kernels are compiled in threads (NVRTC releases the GIL); jobs=None uses 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() passes compile_options() to CuPy: the given options plus -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. options still 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".

Added

  • xp.mpi.get_mpi(use_mpi=None), launched_under_mpi(), SerialMPI and SerialComm: 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/0 overrides), without importing mpi4py, whether the process was started by mpirun/mpiexec/srun. get_mpi() returns mpi4py.MPI then, and otherwise a serial stand-in whose COMM_WORLD is a communicator of size 1: object collectives return what one rank gets (allreduce(x) is x, gather(x) is [x]), buffer collectives copy (Allreduce, Allgather(v), Gather(v), Scatter(v), Sendrecv to self; nothing with IN_PLACE), on NumPy and CuPy buffers, and unsupported methods raise AttributeError. 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 returned None for every call (MockComm().allreduce(5) was None, MockComm().rank a function). Kept in cunumpy/_mpi_serial.py without dependencies on the rest of cunumpy, so that it could become a package of its own.
  • cunumpy/morton.cuh and xp.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 of keys applied 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 of KernelCatalog.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 with compile_host, and "python", uncompiled), <name>_numba.py, <name>_numpy.py and <name>_cuda.cu. A folder's own __init__.py can declare kernel = xp.Kernel.from_folder(__name__, ...), so code imports the kernel from where it is written; from_package now builds each kernel with it. Kernel.implementations lists them, Kernel.selected(device=False) tells which one a call runs.
  • xp.HostImplementations and xp.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 with xp.set_kernel_implementation(name) / with xp.use_kernel_implementation(name): / CUNUMPY_KERNEL_IMPLEMENTATION=name (read at import), like set_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) and xp.kernel_output(out, like, dtype=None): bring the arguments of a dispatch="arrays" kernel to the side of the main array like (CuPy or NumPy, C-contiguous, dtype), without a copy when they already fit; kernel_output yields the buffer the kernel writes and copies it back into out if it had to be converted.
  • CompiledHostKernel.fallback returns the fallback.
  • cunumpy/random.cuh and xp.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 neither n_threads nor grid.
  • CudaKernel launches with shared_mem above 48 KiB set the kernel's max_dynamic_shared_size_bytes once, up to the device's opt-in limit, and raise ValueError beyond it.
  • emulate_cuda_kernel emulates block shared memory (__shared__, extern __shared__ with shared_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) and StagedCopy: 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: CudaStructArguments with a host form. A subclass names its pyccel-compiled (or any) host argument class in host_class and the attributes passed to it in host_fields; __host_args__() builds that object once and again when an attribute was replaced, so one object is passed to a Kernel on both backends (the pyccel class itself cannot inherit from anything). On the CuPy backend __host_args__() raises unless host_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 .py file (or source string) by parsing it with ast, 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>); exclude drops parameters (e.g. scratch arrays).
  • CudaKernel(..., n_threads_from=callable) (also a settable property): a launch that gives neither n_threads nor grid takes n_threads_from(args), e.g. lambda args: args[2].n_markers; Kernel.__call__ and assert_kernels_agree accept a missing n_threads then.
  • 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 raises RuntimeError naming 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_kernel accepts struct parameters, by value (DomainArgs d) or by const reference (const DomainArgs& d), for the structs given in structs=; 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.py as Kernel.test_args_module (imported on first access as Kernel.test_args; Kernel(..., test_args=...) sets it by hand). The module defines make_args(backend, seed) and N_THREADS (an integer, a tuple, or a function of the argument tuple) or GRID, optionally BLOCK, RTOL, ATOL, N_CALLS, OUTPUTS, SEED (cunumpy.testing.TEST_ARGS_SETTINGS). cunumpy.testing.parity_cases(catalog) gives one pytest.param per kernel with a CUDA version, kernels without a test-arguments module marked skip with a reason naming the missing file, and check_parity(kernel, **overrides) runs assert_kernels_agree with 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 module bind_c_<name>_kernels into 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>.pyi stub pyccel writes next to the extension module, so Kernel.check_signature() and KernelCatalog.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 variable CUNUMPY_FAKE_CUPY=1 (read when cunumpy is imported) or cunumpy.testing.install_fake_cupy(). Its arrays live in host memory but are not NumPy arrays (numpy.asarray raises, as for real CuPy arrays), reject host arrays and lists as CuPy does, have data.ptr, device and __cuda_array_interface__, so argument objects, struct packing, as_device_array, count_transfers and backend branches run on the CuPy code path on the CPU; CUDA kernels cannot run (NotImplementedError). cunumpy.testing.fake_cupy_active() tells; requires_cupy and assert_kernels_agree skip 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 (after synchronize_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 by count_transfers(). cuda_aware=None uses the answer recorded by mpi_is_cuda_aware() (which now remembers its result) or xp.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 (bincount per column), the reduction step of a sort-then-reduce accumulation; negative keys drop the value.
  • xp.require_version("0.4.0"): raises ImportError if the installed cunumpy is older.
  • Kernel(..., dispatch="arrays") and KernelCatalog.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 around pyccel.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() and KernelCatalog.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=...) and emulation_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, __syncthreads or warp intrinsics are refused.
  • Array4D<T> in cunumpy/array_view.cuh and as a kernel parameter, struct field and from_signature annotation ("float[:, :, :, :]"), e.g. for a 3D grid of vector components.
  • xp.max_shared_memory_per_block(device=None, *, opt_in=False) and xp.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, plus n_threads. The extern "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). Supports block_size, NVRTC options, include_dirs, shared_mem, stream, CudaKernel.from_file() (<name>_cuda.cu), compile() and prepare_args(); check_signature=False skips 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) and xp.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 raises NotImplementedError (missing_cuda="raise", default) or falls back to the host kernel with host copies (missing_cuda="fallback").
  • xp.KernelCatalog: Read-only mapping of Kernels; KernelCatalog.from_package() collects them from a package with one folder per kernel (name/name_kernels.py, name/name_cuda.cu); without_cuda lists 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 of CudaStruct). A subclass sets struct_name and fields, stores each field as an attribute and calls pack(); the CudaStruct is 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, scipy on NumPy and cupyx.scipy on 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 raises AttributeError naming 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 with cupy.fuse when it is called with CuPy arrays (with the CuPy backend active while tracing) and calls it unchanged otherwise.
  • xp.petsc_vec(array, comm=None): A petsc4py vector 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, and cunumpy_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=()) and CudaStruct.layout_source(): Compile and run a one-thread kernel that reports sizeof, alignof and the field offsets of the struct as the CUDA compiler lays it out, and raise ValueError if they differ from the NumPy dtype that values are packed into; with include the struct is defined by a header instead of declaration.
  • xp.CudaStruct and xp.CudaStructValue: C structs passed to CUDA kernels by value. A CudaStruct is defined once from (field, C type) pairs; it provides the C declaration, the NumPy dtype with the C memory layout, and packs values (device arrays as addresses, scalars checked and cast) into a CudaStructValue that 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) for name<double, 3>); the template parameters are substituted into the checked signature.
  • xp.CudaKernelVariants: Creates and caches one CudaKernel per 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: CudaKernel accepts a tuple block_size, and calls take n_threads as an integer or tuple, or an explicit grid, plus a per-call block; launch_shape() returns the (grid, block) of a call. Dynamic shared memory (shared_mem) and stream are passed through by Kernel as well.
  • Compiling at setup: CudaKernel.compile() and is_compiled, Kernel.compile(), and KernelCatalog.compile_all().
  • Kernel(..., host_options=...) and KernelCatalog.from_package(..., host_options=...): PyccelKernel options (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 before MPI_Init.
  • xp.bind_local_device(): Selects the GPU local_rank() % device_count() and creates its context, before MPI_Init, for one-rank-per-GPU MPI programs.
  • KernelCatalog.summary() (also str(catalog)) and KernelCatalog.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, mirroring without_cuda.
  • CudaKernel.all_from_file(path, **kwargs) and xp.cuda_kernel_names(source): Load every __global__ function of a file as a CudaKernel (a dict by name, sharing the source so CuPy compiles the file once), and list the __global__ functions of a source string. KernelCatalog.from_package still 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 CudaKernel automatically (xp.cuda_include_dir() for other compilers): cunumpy/array_view.cuh defines the strided views Array1D<T>, Array2D<T>, Array3D<T> (data, shape[], strides[] in elements, a(i, j), size(), bounds checks with -DCUNUMPY_BOUNDS_CHECK), so ported pyccel kernels index markers(ip, j) instead of computing offsets from hand-passed sizes; cunumpy/index.cuh defines CUNUMPY_THREAD_1D(i, n) (2D/3D likewise) and the grid-stride loop CUNUMPY_GRID_STRIDE_1D(i, n).
  • Array view parameters and struct fields: CudaKernel signatures and CudaStruct fields accept Array1D<T> to Array3D<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_views tells 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__; self is skipped): "float[:, :]" -> Array2D<double>, "int[:]" -> Array1D<long long>, int -> int_type, float -> double, bool -> bool; Final[...] and const are 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=()) and xp.write_cuda_header(path, structs, guard=None, *, includes=()): Generate a header with include guard, the cunumpy/array_view.cuh include 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. device is 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() and to_host() copy explicitly and in place (the host array keeps its identity; no-ops on NumPy), zero() clears the buffer, and rebind() follows a reallocation by the owner; a host array whose shape or dtype changed raises ValueError. Non-NumPy inputs raise TypeError.
  • cunumpy/atomic.cuh: CUDA header shipped with the package, with cunumpy_atomic_add(double*|float*, value) (atomicAdd, with a compare-and-swap fallback for double before sm_60) and the indexed cunumpy_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; CudaKernel adds 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 by import cunumpy). requires_cupy is a skipif marker for tests that need a GPU, BACKENDS = ["numpy", pytest.param("cupy", marks=requires_cupy)] parametrizes a test over the backends, and the backend fixture 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 with make_args(backend, seed) on the NumPy and the CuPy backend, runs the host and the CUDA kernel of a Kernel, and compares the arrays they wrote (the declared outputs, or every array argument, including arrays held by argument objects) with numpy.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 and assert_kernels_agree covers a whole catalog.
  • cunumpy.testing.device_function_kernel(header_source, signature, *, name=None, includes=(), n_threads_param="n"): Generates an elementwise extern "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 into out), 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 with Sendrecv and the ranks agree with allreduce; any failure gives False. Returns False on the NumPy backend and without a functional CuPy, without importing mpi4py.
  • xp.require_cuda_aware_mpi(comm=None): Raises RuntimeError, with hints on obtaining a CUDA-aware build, when mpi_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 in nsys/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) and xp.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 a Timing with name, elapsed (seconds) and synced.
  • xp.count_transfers(): Context manager yielding a TransferCounter that records every host/device transfer made through cunumpy in the block, with the call site of each: to_numpy/to_cunumpy of a device array (to_host), to_cupy/to_cunumpy of a host array (to_device), PyccelKernel calls that copy device arrays to the host (kernel_conversions, one per call) and Kernel calls that fall back to the host kernel on the CuPy backend (fallbacks). counter.total, counter.events (TransferEvent(kind, description, where)) and counter.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_numpy of a NumPy array) are not counted. Transfers that bypass cunumpy (raw cupy.ndarray.get(), cupy.asarray(numpy_array), conversions inside other libraries) are not seen.
  • xp.assert_no_transfers(): Context manager raising AssertionError with 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 manager xp.cuda_debug() or the environment variable CUNUMPY_CUDA_DEBUG=1 compile kernels with -lineinfo and -DCUNUMPY_BOUNDS_CHECK (xp.DEBUG_OPTIONS; -G is not available with NVRTC) and synchronize the stream after every launch, so an asynchronous CUDA error (illegal memory access, launch failure) is raised as a RuntimeError naming 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 with debug=None at every launch; CudaKernel.debug, debug_active() and compile_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 in include_dirs; cycles, system headers and missing files are ignored), and xp.include_hash(paths) is a short digest of their contents. CudaKernel exposes included_headers, include_dirs, source_dir (set by from_file, or the new source_dir keyword) and compile_options().
  • cunumpy.testing: Helpers for testing host/CUDA kernel pairs with pytest (pytest is imported only when its objects are used, never by import cunumpy). requires_cupy is a skipif marker for tests that need a GPU, BACKENDS = ["numpy", pytest.param("cupy", marks=requires_cupy)] parametrizes a test over the backends, and the backend fixture 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 with make_args(backend, seed) on the NumPy and the CuPy backend, runs the host and the CUDA kernel of a Kernel, and compares the arrays they wrote (the declared outputs, or every array argument, including arrays held by argument objects) with numpy.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 and assert_kernels_agree covers a whole catalog.
  • cunumpy.testing.device_function_kernel(header_source, signature, *, name=None, includes=(), n_threads_param="n"): Generates an elementwise extern "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 into out), 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. Raises RuntimeError on the NumPy backend, so host data is never copied to the device implicitly, and ValueError if ndim does not match.
  • CudaKernel pointer parameters and CudaStruct pointer fields now also reject non-C-contiguous arrays with TypeError: a kernel reads a pointer as a flat buffer, so a view such as a[:, 0:3] would give silently wrong results.
  • xp.KernelArguments and xp.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) by Kernel on the host path and by PyccelKernel (so the missing_cuda="fallback" path works too); on the CuPy backend CudaKernel flattens the same object via __cuda_args__(). Owners can expose one kernel_args property that builds each form lazily, so call sites never branch on the backend and CPU runs never build device arguments.

[0.2.0] - 2026-09-28

Changed

  • xp.get_backend() now returns the active global backend, mirroring xp.set_backend(). Use the new xp.get_array_backend(array) to inspect an individual array. Calls to the former xp.get_backend(array) must be updated.
  • Expanded the README and documentation with backend selection, array conversion, GPU controls, kernel adaptation, and Pyodide examples.

Fixed

  • 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() and use_backend() now reject unsupported backend names with ValueError without changing the active selection.

Added

  • 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. Mirrors cupy.get_array_module and works in Pyodide.
  • xp.get_rng(seed=None): Return a numpy.random.Generator/cupy.random.Generator matching the active backend, without having to branch on the backend yourself.
  • xp.device_count(): Number of visible CUDA devices (0 without 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; selects rank % devices_per_node (defaulting devices_per_node to device_count()) via set_device() and returns the chosen device id.
  • xp.memory_info(): (free, total) bytes of memory on the active CUDA device, or None on 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's float64 dtype object, for pinning a portable float precision instead of the backend/platform-dependent dtype=float.
  • xp.stream(): Context manager for a CUDA stream, to overlap host/device transfers with compute (no-op, yielding None, 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 default isinstance(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-compiled extra for native Pyccel tests. The test extra is now compiler-free; dev continues to include compiled-test dependencies.
  • xp.same_backend(*arrays): Return True if all given arrays live on the same backend.
  • xp.assert_same_backend(*arrays): Raise TypeError with 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; pass object_modules=("your_package.",) to also traverse the attributes of your own objects. Pass outputs=(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.

[0.1.3] - 2026-07-31

Added

  • xp.set_device(device_id): Select the active CUDA device for the current process (no-op on the NumPy backend).
  • xp.__version__: Reports the installed cunumpy package version.

Fixed

  • ArrayBackend no longer silently reports "cupy" as the active backend when CuPy was requested but is unavailable; it now correctly falls back to reporting "numpy" so xp.cupy_backend/xp.numpy_backend reflect what actually loaded.
  • to_numpy() no longer misdetects CPU objects that merely expose a .get method (e.g. dict-like objects) as CuPy arrays; it now checks get_backend() instead of hasattr(array, "get").
  • Invalid backend names now raise ValueError instead of relying on a bare assert, which was previously stripped under python -O.

Changed

  • Removed the redundant ArrayBackend.__init_post__ double-initialization path.
  • ArrayBackend documents 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 ruff is now an enforced check rather than advisory.
  • Added array-api-compat as a core dependency:
    • get_backend()/is_gpu()/is_cpu() now use array_api_compat.is_cupy_array() instead of sniffing type(array).__module__ for the substring "cupy".
    • The active backend module (xp.xp) and array conversions (to_numpy(), to_cupy()) now resolve through array_api_compat.numpy/array_api_compat.cupy instead 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 raw cupy, since CUDA device management isn't part of the Array API standard.

[0.1.2] - 2026-05-27

Added

  • 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 isort configuration to pyproject.toml with black profile compatibility.
    • Reorganized test suite into specialized files: test_numpy.py, test_cupy.py, and test_cunumpy.py.

Changed

  • Dynamic Dispatch Architecture: Refactored src/cunumpy/xp.py to use module-level __getattr__. This ensures that cunumpy.<op> calls always resolve to the currently active backend module, enabling seamless runtime switching via set_backend.
  • Type Safety: Updated src/cunumpy/__init__.pyi stubs to provide full IDE autocompletion and type-checking for all new API methods.
  • Documentation:
    • Simplified README.md and documentation to exclusively focus on PyPI installation (pip install cunumpy).
    • Enhanced quickstart.md and api.md with usage examples for the new backend control and synchronization features.
  • CI/CD: Restricted GitHub Pages documentation deployment to the devel branch only.

Fixed

  • Improved ArrayBackend initialization to fallback gracefully to NumPy if CuPy is requested but not installed.
  • Fixed symbol accessibility tests to correctly handle custom helper methods in the cunumpy namespace.

[0.1.1] - 2026-05-27

Added

  • Type Inspection Support: Added .pyi stub files to enable proper symbol inspection and autocompletion for Pylance/VS Code.
  • CI/CD: Added GitHub Action for automated publishing to PyPI.

Changed

  • Improved import structure in src/cunumpy/__init__.py to allow direct access to xp.

[0.1.0] - 2026-05-27

Added

  • Initial Core Functionality:
    • ArrayBackend class 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.toml and project metadata.