Thursday, December 3, 2026 | London 10°C · Drizzle
DailyGlimpse

AI

CuPy Tutorial: Unlocking GPU Power with Custom Kernels and Streams

CuPy tutorial: speed Python computing with GPU-accelerated custom kernels and streams.

MarkTechPost 2 min read

CuPy Tutorial: Unlocking GPU Power with Custom Kernels and Streams

CuPy Tutorial: Unlocking GPU Power with Custom Kernels and Streams

This tutorial explores CuPy as a high-performance GPU-accelerated alternative to NumPy for numerical computing in Python. It covers GPU introspection, memory management, custom elementwise and reduction kernels, raw CUDA kernels for Mandelbrot set computation, concurrent streams, sparse matrix operations, and linear system solving.

GPU Introspection

Before running heavy computations, inspect your CUDA device: CuPy version, CUDA runtime, device name, compute capability, number of SMs, and total global memory.

NumPy vs. CuPy Benchmark

Benchmark large matrix multiplication (4096x4096) and FFT (2^21 complex samples). CuPy achieves significant speedups: for matrix multiply, CuPy is ~50x faster; for FFT, ~10x faster.

Memory Pool Management

CuPy uses memory pools to reuse GPU memory. Check used and total memory, then free all blocks to release memory.

Custom Elementwise Kernel

Write an ElementwiseKernel that computes a robust distance between two arrays: sqrt((x-y)^2 + eps). This avoids Python overhead and runs fully on GPU.

Custom Reduction Kernel – L2 Norm

Implement an L2 norm reduction kernel manually: map each element to its square, reduce by summation, then post-map with a square root. Compare with CuPy's built-in linalg.norm.

Raw CUDA Kernel – Mandelbrot Set

Write a raw CUDA kernel in C to compute the Mandelbrot set. Launch it with specified thread and block dimensions, synchronize, and display the fractal using Matplotlib. This demonstrates how to embed custom GPU code directly in Python.

CUDA Streams for Concurrency

Use two non-blocking streams to run independent matrix multiplications concurrently. Synchronize both streams and check the output means.

Sparse Linear Algebra

Create a large random sparse CSR matrix (8000x8000, density 0.05%). Compare sparse matrix-vector multiplication with its dense counterpart, showing dramatic speedups for sparse operations.

Solving Linear Systems

Solve a dense linear system Ax = b for a 2000x2000 matrix using CuPy's linalg.solve. Verify the solution by computing residual norm.

This tutorial provides a practical foundation for leveraging CuPy to write familiar NumPy-like code while accessing advanced CUDA features for high-performance GPU computing.

React