Check an FFT library#

The problem#

You compute Fourier transforms, for spectrograms, convolutions of long signals, or spectral layers, with NumPy, PyTorch, or a library or kernel of your own. You want to know that its spectra are right at the sizes you use, including lengths that are not powers of two.

Why the usual approach falls short#

The usual check compares the spectra with a float64 FFT under a hand-picked tolerance. But a float64 FFT is rounded too. How far a correct FFT may land from it depends on how the length factors into passes, on the inputs' size, and on how the library holds its twiddle factors, the roots of unity it multiplies by between passes. A tolerance picked at one size fails correct spectra, or hides wrong ones, at another. A length with a large prime factor may run another algorithm altogether, Bluestein's, with errors of its own.

The solution#

Check each size's spectra with covers(), which says for every real and imaginary part whether a correct FFT can produce it. Test lengths beyond powers of two: here 4096, 4000 (32 x 125), 3072 (3 x 1024), and the prime 4093, for 64 frames each, through NumPy and PyTorch in float32:

Code
import numpy as np
import torch
import exactref as er

# Seeded, so every run uses the same values
rng = np.random.default_rng(67)

for n in (4096, 4000, 3072, 4093):
    # 64 frames of n samples in float32, and ExactRef's spectra for them
    x = rng.standard_normal((64, n)).astype(np.float32)
    r = er.fft.fft(x)
    # Could a correct FFT produce each library's spectra?
    numpy_ok = r.covers(np.fft.fft(x)).all()
    torch_ok = r.covers(torch.fft.fft(torch.from_numpy(x))).all()
    print(f"n={n}: NumPy covered: {numpy_ok}, PyTorch covered: {torch_ok}")
Output
n=4096: NumPy covered: True, PyTorch covered: True
n=4000: NumPy covered: True, PyTorch covered: True
n=3072: NumPy covered: True, PyTorch covered: True
n=4093: NumPy covered: True, PyTorch covered: True

At 4093, pocketfft, the FFT that NumPy runs, uses Bluestein's algorithm, and there the transform's own tolerance is not proven, only measured. Bluestein passes gives the proven check.

A tighter check from the library's plan#

The tolerance allows for the worst way of factoring the length. NumPy, and PyTorch's CPU in its builds without MKL, such as its ARM builds, run pocketfft, whose plan follows from the length: passes of radix 8 while they divide it, then 4s, one 2 moved to the front, then the odd primes. An FFT algorithm with that plan has a tighter tolerance:

Code
def pocketfft_plan(n):
    """pocketfft's complex passes for a length n: 8s, 4s, one 2 moved first, then odd primes."""
    passes = []
    while n % 8 == 0:
        passes.append(8)
        n //= 8
    while n % 4 == 0:
        passes.append(4)
        n //= 4
    # One factor of 2 left over goes first
    if n % 2 == 0:
        passes.insert(0, 2)
        n //= 2
    # Then the odd prime factors, smallest first
    divisor = 3
    while divisor * divisor <= n:
        while n % divisor == 0:
            passes.append(divisor)
            n //= divisor
        divisor += 2
    # What is left is a prime, or 1
    if n > 1:
        passes.append(n)
    return passes


def largest(tolerance):
    """The largest bound of a complex tolerance, over both parts."""
    return max(max(t.real, t.imag) for t in tolerance.scalars())


# 64 frames of 3072 samples, and NumPy's spectra
x = rng.standard_normal((64, 3072)).astype(np.float32)
algorithm = er.fft.dft.FFTAlgorithm(pocketfft_plan(3072))
print("plan:", pocketfft_plan(3072))
print("covered:", algorithm.covers(np.fft.fft(x), x).all())

# The transform's own tolerance, for every factorization, and the plan's
own = largest(er.fft.fft(x).tolerance())
print(f"largest tolerance, the transform's own: {own:.2g}")
print(f"largest tolerance, pocketfft's plan: {largest(algorithm.tolerance(x)):.2g}")
Output
plan: [2, 8, 8, 8, 3]
covered: True
largest tolerance, the transform's own: 0.015
largest tolerance, pocketfft's plan: 0.007

Bluestein's algorithm#

pocketfft computes some lengths with a large prime factor by Bluestein's algorithm: from 89 for complex transforms and 191 for real ones, but not every such length. The transform becomes a convolution of a padded length with small factors. The transform's own tolerance does not model Bluestein's roundings, so check such a length with a Bluestein pass, whose bound is proven: Bluestein passes shows how. PyTorch's x86-64 builds run MKL's FFT, whose plans are not public; check it with the transform's own tolerance.

Gradients#

A spectral loss backpropagates through the transform. Each transform's .backward gives the exact gradient in PyTorch's convention, as Backward on the transforms' reference page shows.