🧠 torch.fft in PyTorch: fft(), rfft(), ifft() with Real Code Examples

If you’re working with signal processing or deep learning in PyTorch, Fourier Transforms can help analyze frequencies and patterns in data. Fortunately, PyTorch provides a built-in module, torch.fft, that makes it easy to apply 1D, 2D, or N-dimensional FFTs.

In this tutorial, we’ll explain how to use torch.fft effectively — including functions like fft(), ifft(), and rfft() — along with code examples, performance tips, and error debugging.


šŸ“˜ What is torch.fft in PyTorch?

The torch.fft module is part of PyTorch’s high-level API for computing Fast Fourier Transforms (FFT) on tensors. It supports:

  • 1D, 2D, and N-dimensional FFTs
  • Real and complex number inputs
  • GPU acceleration
  • Inverse FFT operations

FFT is essential in many domains, such as:

  • Audio and image processing
  • Physics simulations
  • Frequency-domain analysis
  • Spectral deep learning

šŸ”¢ Code Examples Using torch.fft

šŸ”¹ 1. Basic 1D FFT Example

import torch

signal = torch.tensor([1.0, 2.0, 0.0, -1.0])
fft_result = torch.fft.fft(signal)
print("FFT:", fft_result)

This will return a complex tensor containing frequency components.


šŸ”¹ 2. Inverse FFT in PyTorch

ifft_result = torch.fft.ifft(fft_result)
print("Inverse FFT:", ifft_result)

The output should closely match the original signal (within numerical precision).


šŸ”¹ 3. 2D FFT for Images

image = torch.rand(128, 128)  # simulate grayscale image
fft2d = torch.fft.fft2(image)
ifft2d = torch.fft.ifft2(fft2d)

Useful in image compression, sharpening, and filtering.


šŸ”¹ 4. Using Real FFT (rfft) for Performance

pythonCopyEditreal_signal = torch.randn(1024)

rfft = torch.fft.rfft(real_signal)
irfft = torch.fft.irfft(rfft, n=1024)

Real FFT is more efficient and optimized for real-valued signals.


šŸ›  Common Functions in torch.fft

FunctionDescription
torch.fft.fft()1D Fast Fourier Transform
torch.fft.ifft()Inverse 1D FFT
torch.fft.fft2()2D FFT (useful for images)
torch.fft.ifft2()Inverse 2D FFT
torch.fft.fftn()N-dimensional FFT
torch.fft.rfft()Real FFT (faster, optimized)
torch.fft.irfft()Inverse Real FFT
torch.fft.fftshift()Centers zero frequency
torch.fft.ifftshift()Reverts fftshift

šŸ” Working with Complex Tensors

PyTorch supports complex tensors:

z = torch.tensor([1 + 2j, 3 - 4j], dtype=torch.cfloat)
print(z.real) # real part
print(z.imag) # imaginary part

Ensure correct types like torch.cfloat when using fft() or ifft().


ā— Common Errors & Fixes in torch.fft

🚫 Error 1: FFT requires complex dtype

āœ… Fix: Use dtype=torch.cfloat

x = torch.tensor([1.0, 2.0], dtype=torch.cfloat)

🚫 Error 2: rfft requires input to be real

āœ… Fix: Use torch.float for real-valued inputs.


🚫 Error 3: Shape mismatch in inverse transforms

āœ… Fix: Always specify original size in irfft:

torch.fft.irfft(rfft, n=1024)

šŸ™‹ People Also Ask (FAQ)

ā“ What is torch.fft used for?

It performs fast Fourier transforms on PyTorch tensors for tasks like frequency analysis, signal filtering, and image processing.


ā“ Difference between fft() and rfft() in PyTorch?

  • fft(): Works with complex input, returns full frequency spectrum.
  • rfft(): Optimized for real input, returns only positive frequencies.

ā“ Can FFT be used in deep learning?

Yes! It’s used in convolutional layers, spectral transforms, or for efficient data processing.


ā“ How to visualize FFT output in PyTorch?

Use torch.abs() to get magnitude and plot using matplotlib:

pythonCopyEditimport matplotlib.pyplot as plt
plt.plot(torch.abs(fft_result))

šŸš€ Final Thoughts

The torch.fft module is a powerful and efficient tool for frequency-based computations in PyTorch. Whether you’re working on audio, images, or scientific data, mastering FFT will enhance your model’s performance and versatility.

āœ… Key Benefits:

  • GPU-accelerated FFTs
  • Works with 1D/2D/N-D tensors
  • Supports real/complex transforms
  • Ideal for deep learning workflows

šŸ”— Internal Links to Add


šŸ”— External Links to Add

Leave a Reply