Generated banner for Optimize For Gpu
Generated logo for Optimize For Gpu

Optimize For Gpu

K-DenseCommunityCreated by K-Dense, Inc.

  • Skill
  • Tool integration
  • Science and research
  • MIT
  • No issues found

From the author

GPU-accelerates scientific Python on NVIDIA hardware and verifies that the result is correct and faster. Use for CUDA/GPU optimization; CPU-bound NumPy, SciPy, pandas, scikit-learn, NetworkX, scikit-image, vector-search, image-processing, graph, simulation, or file-I/O workloads; CuPy, cuDF, cuML, cuGraph, cuVS, cuCIM, KvikIO, Warp, Newton, Numba-CUDA, or RAFT questions; and profiling, memory-transfer, kernel, or multi-GPU bottlenecks. Also use when large data-parallel Python code is slow and GPU acceleration is a plausible option, even if the user does not name CUDA.
— the description by K-Dense, Inc.

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a systematic approach to GPU-accelerating CPU-bound scientific Python code. It emphasizes an evidence-driven workflow: profiling existing bottlenecks, selecting the appropriate library (e.g., CuPy, cuDF, cuML, cuGraph, cuCIM, or Warp), and validating performance gains through synchronized benchmarks. It guides users to maintain numerical contracts, minimize host-device data transfers, and choose the least disruptive implementation path—from backend acceleration modes to custom Numba-CUDA kernels.

What it does

  • Identifies CPU-bound bottlenecks in NumPy, pandas, and scikit-learn workflows.
  • Maps scientific tasks to GPU-accelerated libraries like CuPy, cuDF, and cuML.
  • Provides patterns for migrating CPU code to GPU-resident execution.
  • Guides the implementation of custom CUDA kernels for specialized simulation or processing.
  • Ensures correctness through comparative testing and numerical tolerance validation.
  • Facilitates accurate benchmarking using CUDA events and profilers.

When to use it

  • When processing large datasets that exceed CPU performance limits.
  • When working with compute-intensive tasks like image processing, graph analytics, or simulations.
  • When the workload involves data-parallel operations suitable for NVIDIA GPU architecture.
  • When you need to optimize existing Python code without rewriting the entire application.
  • When you require high-performance file I/O directly into GPU memory.

Advantages

  • Significant speedups for data-parallel scientific computations.
  • Maintains familiar Python API patterns through library-specific drop-in replacements.
  • Reduces overhead by keeping data resident on the GPU.
  • Provides a clear decision framework for choosing between high-level libraries and custom kernels.
  • Promotes rigorous validation to ensure GPU results match CPU expectations.

Usage examples

“How can I speed up my pandas groupby operation on a large dataset using my NVIDIA GPU?”
The agent will guide you to use cuDF, either by replacing the import or using the cudf.pandas accelerator mode, and explain how to benchmark the end-to-end performance.
“I have a slow Python loop performing particle integration. Can I run this on a GPU?”
The agent will recommend using NVIDIA Warp to JIT-compile the loop into a GPU kernel, providing a pattern for the integration function and explaining how to manage device memory.
“My scikit-learn random forest training is too slow. What are my options?”
The agent will suggest using cuML's RandomForestClassifier, explain the parameter matching process, and advise on how to validate the model's accuracy against the CPU version.
“How do I profile my GPU code to ensure I am actually getting a speedup?”
The agent will provide instructions on using CUDA events for synchronization, the cupyx.profiler for micro-benchmarking, and Nsight Systems for end-to-end timeline analysis.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/k-dense-ai/optimize-for-gpu/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip optimize-for-gpu.zip -d .agents/skills

Documentation by K-Dense, Inc.

GPU Optimization for Python with NVIDIA

Treat GPU acceleration as an evidence-driven optimization, not an automatic rewrite. Preserve the user's numerical and algorithmic contract, measure with representative data, and keep the GPU version only when synchronized end-to-end benchmarks show a useful improvement.

Reviewed against RAPIDS 26.08, CuPy 14.2, Numba-CUDA 0.30.4, and Warp 1.17. The references contain illustrative GPU examples: source/API review is not execution on CUDA hardware. Validate them on the user's target GPU before reporting correctness or speedup. Do not use a moving latest documentation page to infer compatibility with a pinned release.

When This Skill Applies

  • User wants to speed up numerical/scientific Python code

  • User is working with large arrays, matrices, or dataframes

  • User mentions CUDA, GPU, NVIDIA, or parallel computing

  • User has NumPy, pandas, SciPy, scikit-learn, NetworkX, or scipy.sparse.linalg code that processes large datasets

  • User needs low-level GPU primitives (sparse eigensolvers, device memory management, multi-GPU communication)

  • User is doing machine learning (training, inference, hyperparameter tuning, preprocessing)

  • User is doing graph analytics (centrality, community detection, shortest paths, PageRank, etc.)

  • User is doing vector search, nearest neighbor search, similarity search, or building a RAG pipeline

  • User has Faiss, Annoy, ScaNN, or sklearn NearestNeighbors code that could be GPU-accelerated

  • User wants GPU-accelerated interactive dashboards, cross-filtering, or exploratory data analysis on large datasets

  • User is doing geospatial analysis (point-in-polygon, spatial joins, trajectory analysis, distance calculations) with GeoPandas or shapely

  • User is doing image processing, computer vision, or medical imaging (filtering, segmentation, morphology, feature detection) with scikit-image or OpenCV

  • User is working with whole-slide images (WSI), digital pathology, microscopy, or remote sensing imagery

  • User is loading large binary data files into GPU memory (numpy.fromfile → cupy, or Python open() → GPU array)

  • User needs to read files from S3, HTTP, or WebHDFS directly into GPU memory

  • User mentions GPUDirect Storage (GDS) or wants to bypass CPU-memory staging for file IO

  • User is doing physics simulation (particles, cloth, fluids, rigid bodies) or differentiable simulation

  • User needs mesh operations (ray casting, closest-point queries, signed distance fields) or geometry processing on GPU

  • User is doing robotics (kinematics, dynamics, control) with transforms and quaternions

  • User has Python simulation loops that could be JIT-compiled to GPU kernels

  • User mentions NVIDIA Warp or wants differentiable GPU simulation integrated with PyTorch/JAX

  • User is doing simulations, signal processing, financial modeling, bioinformatics, physics, or any compute-intensive work

  • User wants to optimize existing code and GPU acceleration is the right answer

Choose the Smallest Suitable Layer

Prefer a maintained library implementation over a custom kernel:

Existing workloadPreferred pathUse for
NumPy / SciPyCuPyarrays, sparse matrices, linear algebra, FFTs, signal processing
pandascudf.pandas, then cuDFaccelerator mode first; native API for more control
scikit-learncuml.accel, then cuMLaccelerator mode first; native estimators as needed
NetworkXnx-cugraph, then cuGraphbackend dispatch first; native graph API at scale
scikit-imagecuCIMGPU image processing and whole-slide imaging
Faiss / Annoy / k-NNcuVSexact and approximate vector search
Raw or remote file I/OKvikIOGPU buffers and GPUDirect Storage
Custom array kernelsNumba-CUDA-MLIR for new work; Numba-CUDA for existing codeexplicit SIMT kernels and shared memory
Spatial or differentiable kernelsWarpgeometry, simulation kernels, robotics, autodiff
High-level physics simulationNewtonmaintained engine that succeeds the removed warp.sim module
Low-level RAPIDS primitivesRAFT (pylibraft)sparse eigensolvers, resources, multi-GPU building blocks

Do not move code out of PyTorch, JAX, TensorFlow, or another GPU-native framework merely to use one of these libraries. First remove CPU round trips and use the framework's compiler, profiler, mixed-precision, and batching facilities.

Treat these as legacy-only:

ProjectStatusGuidance
cuxfilterFinal release 26.06Maintain existing dashboards only. For new work, combine cuDF with HoloViews/hvPlot/Datashader and serve with Panel, Dash, Streamlit, or Bokeh.
cuSpatialArchived at 25.04Use only in an isolated legacy environment. For new work, keep geometry in GeoPandas/Shapely and accelerate compatible tabular stages with cuDF.

Full per-library guidance, including when each is the wrong choice and how to combine them, is in references/decision_framework.md. Install commands and CUDA version selection are in references/installation.md. Before/after conversions for every library are in references/code_transformation_patterns.md.

Optimization Workflow

1. Define the contract and baseline
  • Capture a representative input, expected output, and acceptable numerical tolerance.

  • Measure the current end-to-end path, including input, transfers, compute, and output.

  • Profile before changing code. Use CPU profilers for CPU code and identify whether the real limit is compute, memory bandwidth, allocation, transfer, synchronization, or storage.

  • Record hardware, package versions, dtypes, shapes, batch size, and warm-up policy with results.

2. Check suitability before porting

GPU execution is promising when the hot path exposes substantial independent work, runs often enough to amortize initialization and transfer, and has a working set that fits available device memory with room for temporaries. Keep a CPU path when the workload is small, mostly sequential, dominated by unsupported operations, or requires frequent host-device round trips.

Do not use fixed row-count thresholds as proof. Benchmark the user's actual shapes and hardware. For out-of-core data, estimate peak working memory and choose chunking, Dask, or a streaming design before allocating.

3. Try the least disruptive implementation
  1. If the code already uses a GPU-native framework, optimize within that framework.

  2. Try accelerator or backend modes (cudf.pandas, cuml.accel, nx-cugraph).

  3. Move to a native GPU API only where accelerator coverage or performance is insufficient.

  4. Write a custom kernel only when profiling shows an operation without a suitable library implementation.

Read the relevant library reference before writing code; compatible names can still differ in defaults, dtypes, output types, and supported arguments.

4. Keep a coherent GPU data path
  • Transfer inputs once and keep intermediates device-resident.

  • Reuse allocations and prefer out= or in-place forms when semantics allow.

  • Batch small operations; fuse elementwise work when it removes intermediate arrays.

  • Use pinned host memory and non-default streams only after profiling shows transfer overlap matters.

  • Choose float32, mixed precision, or reduced-precision storage only when the contract permits it.

5. Validate semantics before speed
  • Compare CPU and GPU outputs on small deterministic fixtures and representative data.

  • Use explicit tolerances for floating-point results and test edge cases, NaNs, ordering, and dtypes.

  • For approximate nearest-neighbor indexes, report recall@k against exact search; do not compare an exact CPU algorithm with an approximate GPU algorithm as if they were equivalent.

  • Check accelerator warnings and logs for CPU fallback.

6. Benchmark GPU code correctly

GPU work is asynchronous, so a CPU timer around an unsynchronized call measures enqueue time. Warm up context creation and JIT compilation, then use CUDA events or a library-aware timer:

from cupyx.profiler import benchmark

print(benchmark(gpu_function, (arg1, arg2), n_warmup=10, n_repeat=100))

Use %gpu_timeit in notebooks, Nsight Systems (nsys) for end-to-end timelines, and Nsight Compute (ncu) for kernel analysis. Report both synchronized kernel/region time and realistic end-to-end latency; include transfer and conversion costs when production pays them.

Measure peak device memory as well as time. For CuPy, distinguish live allocations from memory retained by its pool; a high nvidia-smi reading after arrays are released is not by itself a leak. Record the allocator and pooling policy, include temporary buffers and FFT caches, and leave headroom for CUDA context/library allocations outside the pool limit. Avoid clearing the pool inside timed repeats unless production does so. See CuPy memory management.

7. Keep, revise, or reject the port

Retain the GPU path only when it passes correctness checks and improves the metric the user cares about on representative data. If it does not, explain whether the limiting factor is problem size, transfers, unsupported fallback, memory pressure, launch granularity, or the algorithm itself.

Important Notes

  • Provide a CPU fallback when the application requires portability; otherwise fail early with a clear hardware and dependency error.

  • Test against a trusted reference with problem-specific tolerances; changed algorithms, precision, reduction order, and random streams can produce more than roundoff differences.

  • GPU memory is limited — for datasets larger than GPU memory, consider chunking or using RAPIDS Dask for multi-GPU

  • Prefer the CUDA Array Interface or DLPack for supported zero-copy interchange, but verify device, dtype, contiguity, ownership, and stream semantics rather than assuming every conversion is free.

Reference Files

Before writing any GPU optimization code, read the relevant reference file(s):

FileWhen to Read
references/cupy.mdUser has NumPy/SciPy code, or needs array operations on GPU
references/numba.mdUser has existing Numba-CUDA code or needs explicit SIMT kernels; note the migration path to Numba-CUDA-MLIR
references/cudf.mdUser has pandas code, or needs dataframe operations on GPU
references/cuml.mdUser has scikit-learn code, or needs ML training/inference/preprocessing on GPU
references/cugraph.mdUser has NetworkX code, or needs graph analytics on GPU
references/warp.mdUser needs GPU kernels for simulation, spatial computing, mesh/volume queries, differentiable programming, or robotics; use Newton for a high-level physics engine
references/kvikio.mdUser needs high-performance file IO to/from GPU, GPUDirect Storage, reading S3/HTTP to GPU, or Zarr on GPU
references/cuxfilter.mdUser maintains or explicitly requests cuxfilter (sunset — 26.06 is the final release)
references/cucim.mdUser has scikit-image code, or needs image processing, digital pathology, or WSI reading on GPU
references/cuvs.mdUser needs vector search, nearest neighbors, similarity search, or RAG retrieval on GPU
references/cuspatial.mdUser maintains or explicitly requests cuSpatial (archived — frozen at 25.04 and isolated from current RAPIDS)
references/raft.mdUser needs sparse eigensolvers, device memory management, or multi-GPU primitives

Read the specific reference before writing code — they contain detailed API patterns, optimization techniques, and pitfalls specific to each library.

Citing Scientific Agent Skills

This skill is part of Scientific Agent Skills by K-Dense. If it materially contributed to a manuscript, report, presentation, or code release, add the paper to the references or software section and tell the user you did so:

Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065

Always cite the current version. The DOI and https://arxiv.org/abs/2609.00065 resolve to the latest arXiv version, so never append a version suffix such as v1. When network access is available, fetch https://arxiv.org/abs/2609.00065 (or http://export.arxiv.org/api/query?id_list=2609.00065) before writing the reference and take the author list, year, and version from that record. If the record lists a journal reference or publisher DOI, cite the published version instead.

Files

references/cupy.md

CuPy Reference

Review: 2026-10-01. Code below is illustrative unless explicitly described as CPU-tested. GPU execution, performance, GDS, and multi-GPU behavior require validation on target hardware.

CuPy is a NumPy/SciPy-compatible array library for GPU-accelerated computing. It wraps NVIDIA's optimized libraries (cuBLAS, cuFFT, cuSOLVER, cuSPARSE, cuRAND) so standard array operations are already highly tuned. Most NumPy code works by simply changing the import.

Full documentation: https://docs.cupy.dev/en/stable/

Table of Contents

  1. Installation and Setup

  2. The Drop-In Replacement Pattern

  3. Core API: cupy.ndarray

  4. Supported Operations

  5. Custom Kernels

  6. Kernel Fusion

  7. Memory Management

  8. Streams and Async Operations

  9. Multi-GPU

  10. Performance Optimization

  11. Interoperability

  12. Key Differences from NumPy

  13. Common Pitfalls

  14. Environment Variables


Installation and Setup

Use uv add in standalone examples; follow the user's existing project package manager when one is already configured.

uv add "cupy-cuda12x==14.2.*"    # For CUDA 12.x
uv add "cupy-cuda13x==14.2.*"    # For CUDA 13.x

CuPy 14.2 requires CUDA >= 12.0, Python >= 3.10, and NumPy >= 2.0 (it follows NumPy 2 type-promotion rules, NEP 50), and supports free-threaded Python. The [ctk] extra (e.g. cupy-cuda13x[ctk]) pulls the required CUDA runtime components from PyPI, so only the NVIDIA driver needs to be pre-installed.

Verify:

import cupy as cp
print(cp.cuda.runtime.getDeviceCount())  # >= 1 means GPU is available
print(cp.show_config())                  # Full environment info

The Drop-In Replacement Pattern

The fastest way to GPU-accelerate NumPy code: change the import.

# Before (CPU)
import numpy as np
a = np.random.rand(10_000_000)
b = np.fft.fft(a)
c = np.sort(b.real)

# After (GPU)
import cupy as cp
a = cp.random.rand(10_000_000)
b = cp.fft.fft(a)
c = cp.sort(b.real)
Data Transfer Between CPU and GPU
# NumPy → CuPy (CPU → GPU)
gpu_array = cp.asarray(numpy_array)     # Zero-copy if already on current device
gpu_array = cp.array(numpy_array)       # Always copies

# CuPy → NumPy (GPU → CPU)
cpu_array = cp.asnumpy(gpu_array)       # Copy to CPU
cpu_array = gpu_array.get()             # Same thing
Writing CPU/GPU Agnostic Code
def normalize(x):
    xp = cp.get_array_module(x)  # Returns cupy or numpy depending on input
    return x / xp.linalg.norm(x)

# Works with both NumPy and CuPy arrays
normalize(numpy_array)   # Runs on CPU
normalize(cupy_array)    # Runs on GPU

CuPy arrays implement __array_ufunc__ and __array_function__, so NumPy functions can dispatch to CuPy automatically when given CuPy arrays (NumPy >= 1.17).


Core API

cupy.ndarray mirrors numpy.ndarray — same attributes (shape, dtype, ndim, size, strides, T), plus device (which GPU the array lives on).

Important: cupy.ndarray and numpy.ndarray are NOT implicitly convertible. Every conversion incurs a host-device data transfer.

Array Creation
cp.empty((1000, 1000), dtype=cp.float32)
cp.zeros((1000,), dtype=cp.float64)
cp.ones((512, 512), dtype=cp.float32)
cp.full((100,), fill_value=3.14, dtype=cp.float32)
cp.arange(0, 100, 0.1)
cp.linspace(0, 1, 1000)
cp.eye(100)
cp.random.rand(1000, 1000)                    # Uniform [0, 1)
cp.random.randn(1000, 1000)                   # Standard normal
cp.random.default_rng(42).normal(0, 1, 1000)  # Generator API

Many CuPy random methods accept dtype; check each method. NumPy Generator.random also supports float32/float64. Choose precision from the numerical contract.


Supported Operations

CuPy implements most of NumPy and large parts of SciPy. All are GPU-accelerated.

Array Math and Element-wise Operations

sin, cos, tan, exp, log, log2, log10, sqrt, square, abs, power, add, subtract, multiply, divide, mod, clip, sign, ceil, floor, round, maximum, minimum

Reductions

sum, prod, mean, std, var, min, max, argmin, argmax, cumsum, cumprod, any, all, nansum, nanmean, nanstd, nanvar

Linear Algebra (cupy.linalg — powered by cuBLAS/cuSOLVER)

dot, matmul, @ operator, tensordot, einsum, inner, outer, cholesky, qr, svd, eig, eigh, eigvalsh, norm, solve, inv, pinv, lstsq, det, slogdet, matrix_rank, matrix_power

FFT (cupy.fft — powered by cuFFT)

fft, ifft, fft2, ifft2, fftn, ifftn, rfft, irfft, rfft2, irfft2, rfftn, irfftn, fftfreq, rfftfreq, fftshift, ifftshift

Sorting and Searching

sort, argsort, partition, argpartition, argmin, argmax, where, nonzero, unique, searchsorted

Array Manipulation

reshape, ravel, flatten, transpose, swapaxes, concatenate, stack, vstack, hstack, dstack, split, hsplit, vsplit, tile, repeat, pad, flip, fliplr, flipud, roll, rot90, broadcast_to, expand_dims, squeeze

Sparse Matrices (cupyx.scipy.sparse)

CSR, CSC, COO formats. Matrix-vector multiply, matrix-matrix multiply, conversions between formats. Powered by cuSPARSE. CuPy v14 adds support for large sparse matrices with 64-bit dimensions and nonzero counts.

Signal Processing (cupyx.scipy.signal)

Convolution, correlation, filtering, window functions.

Special Functions (cupyx.scipy.special)

Bessel functions, error functions, gamma functions, and more.

Statistics

mean, median, std, var, percentile, quantile, corrcoef, cov, histogram, bincount, digitize


Custom Kernels

When built-in operations aren't enough, CuPy offers several ways to write custom GPU code, ordered from simplest to most powerful.

ElementwiseKernel — Custom Element-wise Operations

CuPy handles indexing and broadcasting automatically. You just write the per-element logic in C++.

squared_diff = cp.ElementwiseKernel(
    'float32 x, float32 y',   # Input params
    'float32 z',               # Output params
    'z = (x - y) * (x - y)',  # Per-element operation (C++ code)
    'squared_diff'             # Kernel name
)

result = squared_diff(a, b)  # Broadcasting works automatically

Type-generic kernels: Use single-letter type placeholders. Same letter = same type, resolved from arguments at call time.

generic_squared_diff = cp.ElementwiseKernel(
    'T x, T y', 'T z',
    'z = (x - y) * (x - y)',
    'generic_squared_diff'
)
# Works with float32, float64, etc. — type inferred from inputs

Raw indexing: Prefix with raw to disable automatic indexing. Use i for loop index.

# Access neighbors — raw disables auto-indexing so you can index manually
stencil = cp.ElementwiseKernel(
    'raw T x', 'T y',
    'y = (x[i > 0 ? i-1 : 0] + x[i] + x[i < _ind.size()-1 ? i+1 : _ind.size()-1]) / 3',
    'stencil_1d'
)
ReductionKernel — Custom Reductions

Four-part reduction: map each element, reduce pairs, post-process the result.

l2norm = cp.ReductionKernel(
    'T x',           # Input
    'T y',           # Output
    'x * x',         # Map: square each element
    'a + b',         # Reduce: sum pairs (a, b are the binary operands)
    'y = sqrt(a)',   # Post-map: sqrt of final sum
    '0',             # Identity element
    'l2norm'         # Kernel name
)

norm = l2norm(array)        # Full reduction → scalar
norms = l2norm(matrix, axis=1)  # Reduce along axis → vector
RawKernel — Full CUDA C/C++

For complete control over grid, blocks, shared memory — write raw CUDA.

import numpy as np

kernel_code = r'''
extern "C" __global__
void vector_add(const float* a, const float* b, float* c, int n) {
    int tid = blockDim.x * blockIdx.x + threadIdx.x;
    if (tid < n) {
        c[tid] = a[tid] + b[tid];
    }
}
'''
vector_add = cp.RawKernel(kernel_code, 'vector_add')

n = 1_000_000
a = cp.random.rand(n, dtype=cp.float32)
b = cp.random.rand(n, dtype=cp.float32)
c = cp.zeros(n, dtype=cp.float32)

threads = 256
blocks = (n + threads - 1) // threads
vector_add((blocks,), (threads,), (a, b, c, np.int32(n)))  # CUDA int is int32

Important RawKernel caveats:

  • Ignores array views/strides — matrix.T is treated as matrix. Handle strides yourself.

  • Use extern "C" to prevent C++ name mangling.

  • For complex numbers, include <cupy/complex.cuh>.

  • Compiled binaries cached in ~/.cupy/kernel_cache.

CuPy dtype to CUDA type mapping:

CuPy dtypeCUDA type
float16half
float32float
float64double
int32int
int64long long
complex64complex<float>
complex128complex<double>
RawModule — Large CUDA Codebases

For multi-kernel CUDA files or precompiled binaries:

module = cp.RawModule(code=cuda_source)       # From source string
from pathlib import Path
module = cp.RawModule(code=Path('kernels.cu').read_text())  # CUDA source file
module = cp.RawModule(path='kernels.cubin')   # From precompiled

kernel = module.get_function('my_kernel')
kernel((blocks,), (threads,), args)  # args is the kernel argument tuple
JIT Kernel (cupyx.jit.rawkernel) — CUDA Kernels in Python Syntax

Write CUDA-style kernels using Python syntax instead of C++.

@cupyx.jit.rawkernel()
def my_kernel(x, y, size):
    tid = cupyx.jit.grid(1)
    if tid < size:
        y[tid] = x[tid] * 2.0

my_kernel[blocks, threads](x, y, n)

Available JIT primitives:

  • cupyx.jit.threadIdx, blockIdx, blockDim, gridDim

  • cupyx.jit.grid(ndim), gridsize(ndim)

  • cupyx.jit.syncthreads(), syncwarp()

  • cupyx.jit.shared_memory(dtype, size)

  • cupyx.jit.atomic_add/min/max/and/or/xor(array, index, value)

  • Warp shuffles: shfl_sync, shfl_up_sync, shfl_down_sync, shfl_xor_sync

Limitation: Does not work in Python REPL (needs source code access). Use from .py files.


Kernel Fusion

Combine multiple element-wise operations into a single kernel launch — eliminates intermediate arrays and reduces kernel launch overhead.

@cp.fuse()
def fused_op(x, y):
    return cp.sqrt((x - y) ** 2 + 1.0)

# This compiles into ONE kernel instead of multiple
result = fused_op(a, b)

Limitation: Only fuses elementwise and simple reduction operations. Does not support matmul, reshape, indexing, etc.


Memory Management

Memory Pools (Default Behavior)

CuPy uses memory pools by default — this is critical for performance. The pool caches freed GPU memory for reuse, avoiding expensive cudaMalloc/cudaFree calls and implicit synchronization.

Key insight: Memory is NOT freed to the OS when arrays go out of scope — it's returned to the pool. This is expected behavior (shows up in nvidia-smi as still-allocated).

mempool = cp.get_default_memory_pool()
mempool.used_bytes()        # Currently allocated by CuPy arrays
mempool.total_bytes()       # Total held by pool (including free blocks)
mempool.free_all_blocks()   # Release all unused memory back to OS

pinned_mempool = cp.get_default_pinned_memory_pool()
pinned_mempool.free_all_blocks()
Limiting GPU Memory
mempool = cp.get_default_memory_pool()
with cp.cuda.Device(0):
    mempool.set_limit(size=4 * 1024**3)  # 4 GiB limit for GPU 0

Or via environment variable (set before import cupy):

export CUPY_GPU_MEMORY_LIMIT="50%"     # Percentage of total GPU memory
export CUPY_GPU_MEMORY_LIMIT="4294967296"  # Bytes
Managed (Unified) Memory

Data auto-migrates between CPU and GPU. Useful when data doesn't fit in GPU memory.

cp.cuda.set_allocator(cp.cuda.MemoryPool(cp.cuda.malloc_managed).malloc)
Pinned Memory for Fast Transfers
# High-level API
pinned_array = cupyx.empty_pinned((1000,), dtype=np.float32)
pinned_array = cupyx.zeros_pinned((1000,), dtype=np.float32)

# These are NumPy arrays backed by page-locked memory — transfers to GPU are faster
Disabling Pools
cp.cuda.set_allocator(None)                    # Disable device pool
cp.cuda.set_pinned_memory_allocator(None)      # Disable pinned pool

Must be done before any CuPy operations.

Using RMM (RAPIDS Memory Manager)

When using CuPy alongside cuDF/RAPIDS, align on a single allocator:

import rmm
from rmm.allocators.cupy import rmm_cupy_allocator

rmm.reinitialize(pool_allocator=True)  # Configure before allocating any live device arrays
cp.cuda.set_allocator(rmm_cupy_allocator)

Streams and Async Operations

Streams enable overlapping computation with data transfer and running multiple operations concurrently.

stream = cp.cuda.Stream()

# Context manager style
with stream:
    d_data = cp.asarray(host_data)     # H→D transfer on this stream
    result = cp.sum(d_data)            # Kernel on this stream
# Operations enqueued but may not be complete here

stream.synchronize()  # Wait for all operations on this stream
Multiple Streams for Overlap
s1 = cp.cuda.Stream()
s2 = cp.cuda.Stream()

with s1:
    d_a = cp.asarray(data_a)
    result_a = cp.fft.fft(d_a)

with s2:
    d_b = cp.asarray(data_b)  # Overlaps with s1's FFT
    result_b = cp.fft.fft(d_b)

cp.cuda.Device().synchronize()  # Wait for all streams
Events for Timing
start = cp.cuda.Event()
end = cp.cuda.Event()

start.record()
# ... GPU operations ...
end.record()
end.synchronize()

elapsed_ms = cp.cuda.get_elapsed_time(start, end)
Per-Thread Default Stream
export CUPY_CUDA_PER_THREAD_DEFAULT_STREAM=1

Enables per-thread default streams for better concurrency in multi-threaded applications.


Multi-GPU

# Set current device
cp.cuda.Device(0).use()

# Context manager
with cp.cuda.Device(1):
    x = cp.array([1, 2, 3])  # Allocated on GPU 1

# Check which device an array is on
print(x.device)  # Device 1

Cross-device operations may work via P2P (peer-to-peer) memory access if the GPU topology supports it. Use cp.asarray() to explicitly transfer arrays between devices.

Per-Device Memory Limits
mempool = cp.get_default_memory_pool()
with cp.cuda.Device(0):
    mempool.set_limit(size=4 * 1024**3)
with cp.cuda.Device(1):
    mempool.set_limit(size=4 * 1024**3)

Performance Optimization

Benchmarking (Critical First Step)

An unsynchronized time.perf_counter() or %timeit measures enqueue latency. For end-to-end wall time, synchronize the relevant device/streams before starting and before stopping the timer. For GPU region timing use CUDA events or the benchmark helper below.

from cupyx.profiler import benchmark

result = benchmark(my_function, (arg1, arg2), n_repeat=100, n_warmup=10)
print(result)  # Shows CPU and GPU elapsed times with statistics

In IPython/Jupyter:

%load_ext cupyx.profiler
%gpu_timeit my_function(args)
One-Time Overheads
  • Context initialization: First CuPy call may take 1-5 seconds (CUDA context creation). This is one-time.

  • Kernel JIT compilation: First call to any operation triggers on-the-fly kernel compilation. Cached in ~/.cupy/kernel_cache. Persist this directory across CI/CD runs.

CUB and cuTENSOR Acceleration
# CuPy v11+ uses CUB by default
export CUPY_ACCELERATORS=cub          # CUB only (default)
export CUPY_ACCELERATORS=cub,cutensor # Both (requires cuTENSOR installed)

CUB accelerates reductions (sum, prod, amin, amax, argmin, argmax), inclusive scans (cumsum), histograms, sparse matrix-vector multiply, and ReductionKernel. The benefit depends on dtype, shape, axis, and hardware; benchmark the target operation.

cuTENSOR accelerates: binary elementwise ufuncs, reduction, tensor contraction.

Key Optimization Strategies
  1. Prefer float32 over float64 when the numerical contract allows it. Throughput differences depend on GPU architecture; validate accuracy and benchmark the target device.

  2. Minimize CPU-GPU transfers. Every cp.asnumpy() / .get() triggers synchronization and PCI-e transfer. Keep data on GPU as long as possible.

  3. Use kernel fusion. @cp.fuse() combines multiple elementwise operations into one kernel, eliminating intermediate arrays.

  4. Batch operations. Fewer large operations usually beat many small ones. Measure launch overhead on the target system rather than relying on a fixed latency.

  5. Pre-allocate output arrays. Use out= parameter in ufuncs to avoid repeated allocation:

    cp.add(a, b, out=result)  # Writes into existing array
  6. Use in-place operations. a += b avoids allocating a new array.

  7. Use streams to overlap computation and data transfer.

  8. Profile with NVTX markers for Nsight Systems analysis:

    with cupyx.profiler.time_range('my_operation', color_id=0):
        result = heavy_computation()
Decision Tree: Which Kernel Approach?
  1. Can be expressed as NumPy ops? → Use built-in CuPy functions (fastest development, often best performance)

  2. Multiple chained elementwise ops? → Use @cp.fuse()

  3. Custom elementwise with broadcasting? → Use ElementwiseKernel

  4. Custom reduction? → Use ReductionKernel

  5. Need full grid/block/shared memory control? → Use RawKernel or cupyx.jit.rawkernel

  6. Large CUDA codebase? → Use RawModule


Interoperability

CuPy interoperates with other GPU libraries via the CUDA Array Interface and DLPack protocol — both enable zero-copy data sharing.

NumPy
# NumPy functions auto-dispatch to CuPy (NumPy >= 1.17)
import numpy as np
result = np.sum(cupy_array)  # Dispatches to CuPy, returns CuPy array
Numba
from numba import cuda

@cuda.jit
def numba_kernel(x, y):
    i = cuda.grid(1)
    if i < x.shape[0]:
        y[i] = x[i] * 2

# CuPy arrays pass directly to Numba kernels — zero copy
a = cp.arange(1000, dtype=cp.float32)
b = cp.zeros_like(a)
numba_kernel[4, 256](a, b)
PyTorch
import torch

# CuPy → PyTorch (zero copy via CUDA Array Interface)
cupy_array = cp.array([1.0, 2.0, 3.0], dtype=cp.float32)
torch_tensor = torch.as_tensor(cupy_array, device='cuda')

# PyTorch → CuPy (zero copy)
cupy_array = cp.asarray(torch_tensor)

# Via DLPack (also zero copy)
cupy_array = cp.from_dlpack(torch_tensor)
torch_tensor = torch.from_dlpack(cupy_array)
cuDF
import cudf

# cuDF → CuPy
arr = df.to_cupy()
arr = cp.asarray(df['column'])

# CuPy → cuDF
df = cudf.DataFrame(cupy_array)
s = cudf.Series(cupy_array)
Raw Pointer Interop
# Export pointer
ptr = cupy_array.data.ptr  # Raw device pointer as int

# Import foreign pointer
mem = cp.cuda.UnownedMemory(ptr, size_bytes, owner=owner_obj)
memptr = cp.cuda.MemoryPointer(mem, offset=0)
arr = cp.ndarray(shape, dtype, memptr=memptr)

Key Differences from NumPy

These are the behavioral differences that can cause bugs if you're not aware of them.

  1. Reductions return 0-d arrays, not scalars. cp.sum(a) returns a 0-d cupy.ndarray, not a Python float. This avoids implicit GPU-CPU synchronization. Use .item() if you need a scalar.

  2. Out-of-bounds integer-array indexing can wrap silently. Validate indices rather than relying on NumPy error behavior.

  3. Duplicate indices in assignment are undefined. a[[0, 0]] = [1, 2] — NumPy stores the last value; CuPy stores an undefined value (GPU race condition).

  4. Float-to-integer casts differ at edges. Casting negative float to unsigned int or infinity to int gives different results than NumPy.

  5. No string/object dtypes. CuPy only supports numeric types. No structured arrays with string fields.

  6. CuPy ufuncs require CuPy arrays. Unlike NumPy ufuncs, CuPy ufuncs don't accept lists or NumPy arrays — convert first.

  7. Random streams differ. The same seed does not produce the same sequence across NumPy and CuPy or guarantee identical streams across versions. Use shared input fixtures for numerical comparisons.


Common Pitfalls

  1. Unsynchronized timing. Use CUDA events/cupyx.profiler.benchmark() for device regions, or explicitly synchronize before and after wall-clock timing.

  2. Unnecessary round-trips. Every cp.asnumpy() / .get() syncs the GPU and copies data across PCI-e. Restructure code to keep data on GPU.

  3. "Memory leak" from pools. The memory pool caches freed blocks. nvidia-smi shows them as allocated. Use mempool.free_all_blocks() to release.

  4. First-call latency. CUDA context init + kernel JIT compilation. Warm up before benchmarking.

  5. Mixing devices. Using an array from GPU 0 on GPU 1 without explicit transfer can fail or be slow.

  6. RawKernel ignoring views. Transposed or sliced arrays passed to RawKernel are treated as the original contiguous layout. You must handle strides manually.

  7. Forgetting synchronize() before reading results. If you pass data back to CPU or use it in non-CuPy code, ensure the GPU is done first.


Environment Variables

VariablePurpose
CUPY_ACCELERATORSBackend list: cub, cutensor (default: cub for v11+)
CUPY_CACHE_DIRKernel cache directory (default: ~/.cupy/kernel_cache)
CUPY_GPU_MEMORY_LIMITGPU memory limit (bytes or "50%")
CUPY_CACHE_SAVE_CUDA_SOURCESet 1 to dump kernel source for profiling
CUPY_CUDA_PER_THREAD_DEFAULT_STREAMSet 1 for per-thread default streams

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs network access, Needs Python

The author says: Requires an NVIDIA CUDA-capable GPU for GPU execution. RAPIDS 26.08 requires Python 3.11-3.14 on Linux or WSL2, NumPy 2, CuPy 14, and compatible CUDA 12 or 13 wheels. Package installation needs network access.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
K-Dense, Inc.
Publisher
K-Dense (Community)
Source
K-Dense-AI/scientific-agent-skills · skills/optimize-for-gpu · commit a25cf9e
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE.md)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by K-Dense, Inc. or K-Dense.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download optimize-for-gpu.zip