18.4 DFT and FFT
Whisper’s audio frontend takes a Fourier transform of every 25 ms frame of audio: 3000 frames of 400 samples for each 30 s clip. Multiplying each frame by a DFT matrix costs 160000 complex multiplies per frame; an FFT does it in about 4000. More importantly, 400 is not a power of two, so the radix-2 FFT of most textbooks cannot transform it at all, and padding to 512 changes the frequencies of the bins and breaks parity with Whisper.
Concepts from other sections (6)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- STFT: the DFT of overlapping windowed frames, giving a spectrum per time step. Read more: 18.5 Sampling, Nyquist, windows, and the STFT
- Change of basis: rewriting a matrix in new coordinates as ; the transformation is the same, only its description changes. Read more: Chapter 9: Linear Algebra
- Orthonormal: a set of unit-length vectors that are pairwise orthogonal. Read more: 9.3 Orthogonality, Householder QR, and orthogonal initialization
- machine epsilon: , the gap between 1 and the next float64. Read more: 7.1 Derivatives and Finite Differences
- Geometric series: , with partial sum and limit for . Read more: 8.2 Series convergence, the EMA as a geometric series, and bias correction
- Base case: an input on which a recursive function returns directly without calling itself; together with an input that strictly shrinks on every call, it guarantees that the recursion terminates. Read more: Chapter 13: Recursion and divide-and-conquer in Programming and Algorithms
This section builds the transform that the STFT of Sampling, Nyquist, windows, and the STFT and the perceptual hash of an image deduplication pipeline both stand on, and it matches numpy to within a rounding bound that grows like . You will derive the DFT as a unitary change of basis, the convolution theorem, the mixed-radix Cooley-Tukey split, the half-size real FFT, and the DCT-II, and work a four-point transform by hand. The section draws on roots of unity from Trigonometry, rotations, complex numbers, and Euler’s formula, on unitary matrices from Orthogonality, Householder QR, and orthogonal initialization, and on error bounds that grow with from Error analysis, condition numbers, and tolerance budgets.
The reference implementation is python/tinyllm/sig/fft.py, with its interface in course/contracts/py/tinyllm/sig/fft.pyi. It provides dft_matrix, a mixed-radix fft (radices 4, 2, 3, 5) and ifft, rfft and irfft from one half-size complex FFT, fft_convolve (the convolution theorem), and dct2_ortho (the DCT-II via an FFT). As you read, try to predict why each reshape, twiddle, and sign is what it is.
Learning objectives
- Show that is unitary and use it to derive Parseval’s identity and the inverse DFT.
- Derive the Cooley-Tukey split for any radix and implement a mixed-radix FFT for .
- Compute a real signal’s bins from one complex FFT of size .
- Use the convolution theorem with the right zero padding to compute linear convolution.
- Compute the orthonormal DCT-II with one FFT using Makhoul’s reordering.
Notation
Section titled “Notation”| Symbol | Meaning | Type / shape |
|---|---|---|
| transform length | int | |
| primitive -th root of unity | complex | |
| , | DFT matrix | complex128[n, n] |
| spectrum of | complex128[n] | |
| , | radix and subsequence length | ints |
| DFT of the subsequence | complex128[m] | |
| half length for the real FFT | int | |
| float64 machine epsilon, | float |
The DFT and its matrix
Section titled “The DFT and its matrix”The DFT writes samples as coefficients of complex sinusoids, The rows of are orthogonal: , a geometric series of roots of unity that is if and 0 otherwise. So satisfies : it is unitary, it keeps lengths, and that is Parseval’s identity .
The inverse is the conjugate transform: , which is how ifft reuses fft. dft_matrix reduces before computing the phase, so every entry is evaluated at an angle in .
The convolution theorem
Section titled “The convolution theorem”The reason the DFT matters beyond spectra is what it does to convolution. For circular convolution , the DFT turns convolution into a product: . Linear convolution, what numpy.convolve computes, has length . Padding both inputs with zeros to any makes the wrap-around terms vanish, so the circular result equals the linear one. fft_convolve picks the smallest whose prime factors are 2, 3, 5.
Cooley-Tukey, any radix
Section titled “Cooley-Tukey, any radix”All of this is only useful if the transform is fast. Split into interleaved subsequences , , with DFTs of size . Writing with , : So the size- DFT is size- DFTs, a multiply by the twiddle factors , and a size- DFT for each . Recursing until costs operations, for small radices.
With radices 4, 2, 3, 5 every works: , Whisper’s frame. A size with another prime factor (7, 11, …) is a ValueError, not a silent fallback. Each level adds a few roundings, so the error grows like : a correct implementation stays within per entry.
Real input: half the work
Section titled “Real input: half the work”Audio samples are real, and real signals have redundant spectra. If is real, , so the bins determine everything. Pack the even samples as real parts and the odd ones as imaginary parts, , and take one complex FFT of size . The DFTs of the even and odd samples untangle as
and for , with the Nyquist bin because . irfft runs the steps backwards; the imaginary parts of and must be zero for a real signal, so it drops them first, as numpy does.
The DCT-II via an FFT
Section titled “The DCT-II via an FFT”One more transform rides on the FFT. A perceptual hash (pHash) takes the orthonormal DCT-II, with and . Makhoul’s trick reorders the input into (even samples forward, odd samples backward); then with . The scales make the DCT matrix orthogonal, which transforming the identity confirms.
Working it by hand
Section titled “Working it by hand”Take , , . The four bins are:
| 0 | ||
| 1 | ||
| 2 | ||
| 3 |
, so rfft returns . Parseval checks out: and .
Now through the real-FFT packing: , ; then , , so and .
Designing the interface
Section titled “Designing the interface”def dft_matrix(n, unitary=False) -> NDArray: ...def fft(x) -> NDArray: ... # last axis, n = 2^a 3^b 5^cdef ifft(X) -> NDArray: ...def rfft(x) -> NDArray: ... # n // 2 + 1 bins, one FFT of size n/2def irfft(X, n) -> NDArray: ...def fft_convolve(a, b) -> NDArray: ... # == numpy.convolve(a, b)def dct2_ortho(x, axis=-1) -> NDArray: ... # == scipy.fft.dct(x, 2, norm='ortho')The transforms follow numpy’s conventions (a minus sign in the forward exponent, on the inverse) and work on the last axis, so a batch of frames is one call. rfft requires real input of even length; irfft requires exactly bins and the output length. Sizes with prime factors other than 2, 3, and 5, empty inputs, odd or complex rfft input, and the wrong bin count raise errors, and inputs are never modified.
Building it step by step
Section titled “Building it step by step”The implementation follows eight steps.
- The reference is the matrix. Everything must equal to rounding, so
dft_matrixcomes first: a direct, obviously correct definition that the fast code is compared against. Reducing before computing the phase keeps every angle in , whereexpis accurate. - The FFT is the Cooley-Tukey split, applied recursively. For the smallest usable radix of : form the interleaved subsequences, transform each (recursively) at size , multiply by the twiddles , and finish with a size- DFT across for every . The base case is the identity.
- Interleaving is a reshape and a swap. Reading row-major as an matrix puts at row , column ; swapping the last two axes gives a array whose row is subsequence . No index arithmetic, and the recursion transforms the last axis of a batch of rows at once.
- Only sizes are allowed, checked up front. If any other prime divides , the recursion would reach a size with no radix. Checking before starting gives a clear error at the call site. Radix 4 is tried before 2 so that powers of two use fewer, larger levels.
- The inverse reuses the forward transform. Since , . One FFT implementation, one set of twiddles.
- A real FFT is a half-size complex FFT plus untangling. Pack even and odd samples into one complex signal, transform at size , and separate and using the conjugate symmetry of real signals.
irfftinverts each step: rebuild and from , recombine into , inverse transform, and unpack real and imaginary parts into even and odd samples. - Linear convolution needs padding. The DFT computes circular convolution. Padding both inputs to leaves room for the whole result, so nothing wraps; the smallest such with factors 2, 3, 5 keeps the FFT applicable.
- The DCT-II is an FFT of a permuted input. Makhoul’s reordering makes equal to , so one FFT plus a phase and a scale computes it.
Step 1, the reference matrix:
def dft_matrix(n: int, unitary: bool = False) -> NDArray: if n < 1: raise ValueError(f"dft_matrix: n must be >= 1, got {n}") j = np.arange(n) # Reduce k * j mod n before scaling: the phase stays in [0, 2 pi) and # exp is evaluated where it is accurate. w = np.exp(-2j * np.pi * (np.outer(j, j) % n) / n) # minus sign: numpy's forward convention return w / np.sqrt(n) if unitary else wSteps 2 to 4, the recursive FFT:
_RADICES = (4, 2, 3, 5)
def _radix(n: int) -> int: """The first radix the FFT splits n by (4 before 2); ValueError if none.""" for p in _RADICES: if n % p == 0: return p raise ValueError(f"fft: n = {n} has a prime factor other than 2, 3, 5")
def _fft(x: NDArray) -> NDArray: """Decimation in time over the last axis of a complex array.""" n = x.shape[-1] if n == 1: return x.copy() # the DFT of one sample is itself p = _radix(n) m = n // p lead = x.shape[:-1] # Subsequence r holds x[r], x[r + p], x[r + 2p], ...: shape [..., p, m]. sub = _fft(np.swapaxes(x.reshape(*lead, m, p), -1, -2)) # p transforms of size m r = np.arange(p)[:, None] k = np.arange(m)[None, :] tw = np.exp(-2j * np.pi * ((r * k) % n) / n) # W_n^{r k}, [p, m] # X[q m + k] = sum_r W_p^{r q} (W_n^{r k} Y_r[k]): a size-p DFT per k. out = np.einsum("qr,...rk->...qk", dft_matrix(p), sub * tw) return out.reshape(*lead, n) # row q, column k -> index q m + kThe output’s last two axes are , and the row-major reshape maps them to , exactly the index in the formula. For the levels are radix 4 (to 100), 4 (to 25), 5 (to 5), 5 (to 1).
The public wrappers validate once and implement step 5:
def fft(x: NDArray) -> NDArray: a = np.asarray(x, dtype=np.complex128) if a.ndim == 0 or a.shape[-1] < 1: raise ValueError("fft: need at least one sample on the last axis") _check_size(a.shape[-1]) # strip 2, 3, 5 and require 1 to remain return _fft(a)
def ifft(X: NDArray) -> NDArray: a = np.asarray(X, dtype=np.complex128) # The inverse is the conjugate transform, divided by n. return np.conj(fft(np.conj(a))) / a.shape[-1]Step 6, the real FFT, with a reversal trick for :
def rfft(x: NDArray) -> NDArray: # ... reject complex input and odd or short lengths ... h = n // 2 # Pack: even samples as the real part, odd samples as the imaginary part. z = fft(a[..., 0::2] + 1j * a[..., 1::2]) # [..., h] # Reversing gives Z[h-1], ..., Z[0]; rolling by one gives Z[0], Z[h-1], ..., Z[1], # which is Z[(h - k) mod h] for k = 0 .. h-1. zr = np.conj(np.roll(z[..., ::-1], 1, axis=-1)) # conj(Z[(h - k) mod h]) even = 0.5 * (z + zr) # DFT of the even samples odd = -0.5j * (z - zr) # DFT of the odd samples k = np.arange(h) lower = even + np.exp(-2j * np.pi * k / n) * odd # bins 0 .. h-1 nyq = even[..., :1] - odd[..., :1] # bin h: W_n^h = -1 return np.concatenate([lower, nyq], axis=-1)The inverse runs the same algebra backwards. Given and , and , and :
def irfft(X: NDArray, n: int) -> NDArray: # ... require even n >= 2 and exactly h + 1 bins ... a = a.copy() # never modify the caller's spectrum # The DC and Nyquist bins of a real signal are real: drop any imaginary # part, as numpy does, instead of letting it leak into the samples. a[..., 0] = a[..., 0].real a[..., h] = a[..., h].real k = np.arange(h) xk = a[..., :h] xr = np.conj(a[..., h - k]) # conj(X[h - k]), k = 0 .. h-1 even = 0.5 * (xk + xr) odd = 0.5 * (xk - xr) * np.exp(2j * np.pi * k / n) z = ifft(even + 1j * odd) out = np.empty(a.shape[:-1] + (n,)) out[..., 0::2] = z.real # unpack: real part -> even samples out[..., 1::2] = z.imag # imaginary part -> odd samples return outSteps 7 and 8, convolution and the DCT:
def fft_convolve(a: NDArray, b: NDArray) -> NDArray: # ... two non-empty 1-D arrays ... full = a.size + b.size - 1 # Zero-pad past the full length so the circular convolution the DFT # computes never wraps around: then it equals the linear one. m = _fast_size(full) # smallest m >= full with factors 2, 3, 5 fa = fft(np.pad(a.astype(np.complex128), (0, m - a.size))) fb = fft(np.pad(b.astype(np.complex128), (0, m - b.size))) y = ifft(fa * fb)[:full] if not (np.iscomplexobj(a) or np.iscomplexobj(b)): return y.real.copy() # real inputs: drop rounding-level imaginary parts return y
def dct2_ortho(x: NDArray, axis: int = -1) -> NDArray: a = np.moveaxis(np.asarray(x, dtype=np.float64), axis, -1) # ... n >= 1 ... # Makhoul: even samples forward, odd samples backward, then one FFT. v = np.concatenate([a[..., 0::2], a[..., 1::2][..., ::-1]], axis=-1) vf = fft(v) k = np.arange(n) # scipy's unnormalized DCT-II: y[k] = 2 Re(exp(-i pi k / 2n) V[k]). y = 2.0 * (vf * np.exp(-1j * np.pi * k / (2 * n))).real scale = np.full(n, np.sqrt(1.0 / (2 * n))) scale[0] = np.sqrt(1.0 / (4 * n)) # norm='ortho' makes the DCT matrix orthogonal return np.moveaxis(y * scale, -1, axis)dct2_ortho works along any axis, so a 2-D DCT of a 32 x 32 block, as pHash needs, can be computed as dct2_ortho(dct2_ortho(block, axis=0), axis=1).
The full solution is fft.py.
Why this design
Section titled “Why this design”Each recursion level does work (the size- DFTs) plus twiddles, and there are levels, so costs about complex multiply-adds instead of . rfft halves that again by transforming points. Memory is per level.
Mixed radix beats radix 2 with padding because padding a 400-sample frame to 512 changes the bin frequencies from multiples of Hz to multiples of Hz, which is a different spectrogram than the one Whisper was trained on. Supporting radices 3 and 5 gives the exact transform for every size this book uses.
Other primes raise rather than fall back to . A silent quadratic path turns a misconfigured frame length into a slow pipeline with no error. Production libraries handle large primes with Bluestein’s algorithm; here the sizes are known, so an error is more useful.
The recursion uses dft_matrix(p) for the small DFT because for a dense matrix product is the simplest correct butterfly, and einsum vectorizes it over every and every batch row. Hand-written radix-4 butterflies would be faster but would duplicate the math.
On accuracy, each level adds a few roundings, so the error grows like , about per entry. The direct matrix product, by contrast, accumulates terms per entry.
What can go wrong
Section titled “What can go wrong”A correct implementation reproduces the hand example’s spectrum, its rfft half, and Parseval, which fixes the sign and packing conventions. The DFT matrix must be unitary ( for several ), match the formula entry by entry, and reject . fft must match numpy within the bound on 19 sizes up to 512, including 240 and 400, and on a batch, which is what STFT parity rests on; it must also equal on mixed-radix sizes, since the FFT is only fast multiplication. rfft and irfft must match numpy for every even size, with irfft dropping imaginary DC and Nyquist parts. Round trips must hold: ifft(fft(x)) = x, Parseval, and irfft(rfft(r)) = r. fft_convolve must equal numpy.convolve, including lengths that need padding to 12. dct2_ortho must match scipy’s orthonormal DCT-II on vectors and a 32 x 32 block and be orthogonal. Unsupported sizes (prime factors 7 and 11), empty input, odd or complex rfft input, and the wrong bin count must raise, with inputs untouched, so misconfigured frames fail loudly.
The usual mistakes:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| twiddle factors with | every size above 4 wrong; spectra mirrored | every forward exponent is , matching dft_matrix |
| Nyquist bin as | the last rfft bin wrong | nyq = even[..., :1] - odd[..., :1], since |
| ifft without the | round trips scaled by | ifft divides the conjugate transform by a.shape[-1] |
| multiplying unpadded spectra | circular wrap-around; wrong length | pads both inputs to _fast_size(len(a) + len(b) - 1) and slices to full (step 7) |
| scaling bin 0 like the others in the DCT | the DC coefficient too large; not orthogonal | scale[0] = sqrt(1 / (4n)) |
| keeping an imaginary DC part in irfft | a spurious alternating component | irfft sets bins 0 and to their real parts first |
| splitting into contiguous blocks instead of interleaved subsequences | a different transform that still has the right shape | reshapes to (m, p) and swaps axes (step 3) |
accepting in dft_matrix | an empty matrix instead of an error | raises for n < 1 |
| accepting extra bins in irfft | the trailing bins silently ignored | requires exactly bins |
| accepting complex input in rfft | the imaginary part discarded | rfft rejects complex input with np.iscomplexobj |
Where this leads
Section titled “Where this leads”The next section, Sampling, Nyquist, windows, and the STFT, runs rfft on every frame in stft and irfft in istft. The image deduplication stage of the corpus pipeline in Data Engineering computes pHash with a 32 x 32 dct2_ortho. The chapter’s problem set works DFT properties, the convolution theorem, and FFT operation counts by hand.
Each piece has a production counterpart:
| Solution piece | Production equivalent | What it adds | Where to look |
|---|---|---|---|
fft | pocketfft (numpy, scipy) | radices up to 11 plus Bluestein for large primes, cache-friendly plans | numpy/fft/_pocketfft_umath.cpp |
fft | FFTW | plans tuned by measurement (“wisdom”), codelets generated by genfft | Frigo and Johnson, Proc. IEEE 2005 |
rfft in Rust | rustfft and realfft (used by the Rust serving engine) | SIMD butterflies; the same half-size packing | realfft crate docs |
fft in C | an optional C kernel | mixed-radix real FFT plans for the Whisper frontend | c/src/kernels/audio.c |
Further reading
Section titled “Further reading”- Cooley and Tukey, “An algorithm for the machine calculation of complex Fourier series” (1965).
- Van Loan, Computational Frameworks for the Fast Fourier Transform, ch. 1 to 2.
- Makhoul, “A fast cosine transform in one and two dimensions” (1980).
Key terms
Section titled “Key terms”- DFT: multiplication by , writing samples as coefficients of complex sinusoids.
- Parseval’s identity: , a consequence of being unitary.
- Twiddle factor: the phase that aligns subsequence transforms before the final size- DFT.
- Radix: the factor by which one FFT level splits the length.
- Conjugate symmetry: for real input, which lets
rfftkeep only bins. - DCT-II: the cosine transform ; orthonormal with the scales .
Summary
Section titled “Summary”- The DFT is multiplication by ; is unitary, so the transform keeps energy (Parseval) and its inverse is the conjugate transform divided by .
- An FFT splits into interleaved subsequences, transforms them, and recombines them with twiddle factors and one size- DFT; mixed radices cover .
- A real signal’s spectrum is conjugate symmetric, so
rfftcomputes bins from one complex FFT of size . - The convolution theorem gives circular convolution; zero-padding to
len(a) + len(b) - 1makes it linear. - The orthonormal DCT-II is a reordered FFT.
Review questions
Section titled “Review questions”- Why does
x.reshape(*lead, m, p)followed byswapaxesgive the interleaved subsequences rather than contiguous blocks?Answer
A row-major $m \times p$ view puts $x[tp + r]$ at $(t, r)$: column $r$ collects every $p$-th sample starting at $r$. Swapping makes that column a row. Reshaping to $(p, m)$ directly would give contiguous blocks $x[rm \dots rm + m - 1]$, a different (and wrong) decomposition with the same shape. - Why is the Nyquist bin and not ?
Answer
$X[k] = E[k] + \omega_n^k O[k]$ with $E$ and $O$ periodic in $h$. At $k = h$, $E[h] = E[0]$, $O[h] = O[0]$, and $\omega_n^h = e^{-i\pi} = -1$. In the hand-worked example this gives $X[2] = 1 - 1 = 0$. - Why does
irfftdiscard the imaginary parts of bins and ?Answer
For a real signal those bins are real ($X[0] = \sum x$, $X[h] = \sum (-1)^j x[j]$). Any imaginary part there has no real signal behind it, and passing it through the inverse would add a spurious component (an alternating pattern for the Nyquist bin). numpy drops it, so the solution does too. - Lengths 5 and 4 give a full convolution of length 8. Why not transform at size 5 and multiply?
Answer
The DFT product is circular convolution of length 5: the last 3 terms of the linear result wrap around and add onto the first 3. Padding to $m \ge 8$ leaves room for every term, so nothing wraps and the first 8 entries are the linear convolution. - Why is
scale[0]different from the other DCT scales?Answer
The $k = 0$ basis vector is constant, $\cos 0 = 1$ everywhere, and its squared norm under the unnormalized transform is twice that of the other cosines. Scaling it by $\sqrt{1/(4n)}$ instead of $\sqrt{1/(2n)}$ gives every row unit norm, which is what makes the DCT matrix orthogonal.