Circular and Fast Convolution
Direct convolution of a signal of length with a filter of length costs multiplications. Through the FFT it costs about with : for long filters that is a huge saving. This lesson builds FFT convolution, shows the overlap-add method for streams, and finds where FFT convolution starts to win.
FFT convolution
- Pad both sequences to (a fast size).
- Multiply their FFTs.
- Inverse FFT and keep the first samples.
import numpy as np
def fft_convolve(x, h):
n_out = len(x) + len(h) - 1
N = 1 << (n_out - 1).bit_length() # next power of two
y = np.fft.irfft(np.fft.rfft(x, N) * np.fft.rfft(h, N), N)
return y[:n_out]
rng = np.random.default_rng(1)
x = rng.normal(size=1000)
h = rng.normal(size=300)
print("same as np.convolve:", np.allclose(fft_convolve(x, h), np.convolve(x, h)))
print("max difference:", f"{np.max(np.abs(fft_convolve(x, h) - np.convolve(x, h))):.1e}")same as np.convolve: True
max difference: 6.4e-14
The tiny differences are floating-point rounding; FFT convolution is as accurate as direct convolution for practical purposes.
Counting the cost
import math
def direct(L, M):
return L * M
def via_fft(L, M):
N = 1 << (L + M - 2).bit_length()
return 3 * (N // 2) * int(math.log2(N)) + N # three FFTs plus the pointwise product
for L, M in ((1000, 8), (1000, 64), (1000, 1000), (48000, 4800), (10**6, 10**4)):
d, f = direct(L, M), via_fft(L, M)
print(f"L={L:7d} M={M:5d}: direct {d:.1e} FFT {f:.1e} -> {'FFT' if f < d else 'direct'} wins by {max(d, f) / min(d, f):.1f}x")L= 1000 M= 8: direct 8.0e+03 FFT 1.6e+04 -> direct wins by 2.0x
L= 1000 M= 64: direct 6.4e+04 FFT 3.6e+04 -> FFT wins by 1.8x
L= 1000 M= 1000: direct 1.0e+06 FFT 3.6e+04 -> FFT wins by 27.9x
L= 48000 M= 4800: direct 2.3e+08 FFT 1.6e+06 -> FFT wins by 140.6x
L=1000000 M=10000: direct 1.0e+10 FFT 3.3e+07 -> FFT wins by 307.6x
Short filters (up to a few dozen taps) are faster directly, especially with SIMD; long filters, such as a one-second reverb impulse response, are far faster via FFT.
Overlap-add for long streams
A live audio stream has no end, and one giant FFT would add huge latency. Overlap-add cuts the input into blocks of length , convolves each block with via FFT (output length ), and adds the overlapping tails:
import numpy as np
def overlap_add(x, h, B=256):
M = len(h)
N = 1 << (B + M - 2).bit_length()
H = np.fft.rfft(h, N)
y = np.zeros(len(x) + M - 1)
for start in range(0, len(x), B):
block = x[start:start + B]
yb = np.fft.irfft(np.fft.rfft(block, N) * H, N)[:len(block) + M - 1]
y[start:start + len(yb)] += yb
return y
rng = np.random.default_rng(2)
x = rng.normal(size=10000)
h = rng.normal(size=500)
y = overlap_add(x, h)
print("overlap-add equals full convolution:", np.allclose(y, np.convolve(x, h)))
print("blocks processed:", -(-len(x) // 256), " FFT size per block:", 1 << (256 + 500 - 2).bit_length())overlap-add equals full convolution: True
blocks processed: 40 FFT size per block: 1024
The related overlap-save method overlaps the input blocks instead and discards the wrapped part of each output.
In software
scipy.signal.fftconvolve(single FFT),oaconvolve(overlap-add) andconvolve(method="auto"), which chooses direct or FFT by estimating the cost as above.- Real-time convolution reverbs use partitioned overlap-add: short blocks for the start of the impulse response (low latency), long blocks for the tail (efficiency).
Exercises
Exercise 1: Choose a size
What power-of-two FFT size is needed to convolve 3000 samples with a 1200-tap filter?
Answer
Solution
, and the next power of two is 8192. (A mixed-radix size such as 4200 would also work and is smaller.)
Exercise 2: Latency
With overlap-add and blocks of samples at 48 kHz, what is the minimum processing latency?
Answer
About 10.7 ms.
Solution
A block can only be processed once all 512 samples have arrived: ms, plus computation time.
Exercise 3: Wrong padding (code)
Convolve with via FFT using instead of 6. Which output sample is wrong?
Answer
The first: it becomes instead of 1.
Solution
import numpy as np
x = np.array([1, 2, 3, 4, 5], dtype=float)
h = np.array([1, 1], dtype=float)
print((np.round(np.fft.irfft(np.fft.rfft(x, 5) * np.fft.rfft(h, 5), 5), 10) + 0.0).tolist())
print(np.convolve(x, h).tolist())[6.0, 3.0, 5.0, 7.0, 9.0]
[1.0, 3.0, 5.0, 7.0, 9.0, 5.0]
The last linear output (5) wrapped around onto position 0.
Test yourself
FFT convolution beats direct convolution when…
- the filter is very short
- the filter is long
- the signal is complex
- never
Overlap-add processes a stream by…
- one FFT of the whole stream
- convolving blocks and adding their overlapping tails
- dropping samples
- averaging blocks
If the FFT size is smaller than …
- the result is exact anyway
- the tail wraps around and corrupts the start
- the FFT fails
- only the end is lost