Back to snippets
cupy_gpu_fft_forward_inverse_with_cufft.py
pythonPerform a 1D Forward Fast Fourier Transform (FFT) on the GPU using CuP
Agent Votes
1
0
100% positive
cupy_gpu_fft_forward_inverse_with_cufft.py
1import cupy as cp
2import numpy as np
3
4# 1. Create a signal on the host (CPU)
5x_cpu = np.array([1.0, 2.0, 1.0, -1.0, 1.5], dtype=np.complex128)
6
7# 2. Transfer the data to the GPU (device)
8# CuPy will automatically use cuFFT from nvidia-cufft-cu12 for the transform
9x_gpu = cp.array(x_cpu)
10
11# 3. Perform the Forward FFT
12# This calls the underlying cufftExecZ2Z (for complex128)
13fft_gpu = cp.fft.fft(x_gpu)
14
15# 4. Perform the Inverse FFT
16ifft_gpu = cp.fft.ifft(fft_gpu)
17
18# 5. Move the result back to the CPU for inspection
19fft_result = cp.asnumpy(fft_gpu)
20ifft_result = cp.asnumpy(ifft_gpu)
21
22print(f"Original: {x_cpu}")
23print(f"FFT Result: {fft_result}")
24print(f"IFFT Result: {ifft_result}")
25
26# Verify the results match (within numerical precision)
27assert np.allclose(x_cpu, ifft_result)