Lesson overview | Previous part | Next part
Discrete Fourier Transform and FFT: Part 7: Short-Time Fourier Transform to Appendix H: The FFT in Modern Hardware
7. Short-Time Fourier Transform
7.1 Motivation: Time-Varying Spectra
The DFT and continuous FT assume the signal's spectral content is stationary - constant over the entire observation window. This assumption fails catastrophically for real-world signals:
- Speech: phonemes last 20-100 ms, with frequency content changing at each phoneme boundary
- Music: pitch and timbre evolve continuously; a melody is precisely a time-varying spectrum
- EEG: neural oscillations appear and disappear; seizure onset is detected by spectral changes
- Radar: target velocity changes the Doppler shift over time
The Short-Time Fourier Transform (STFT) addresses this by computing a sequence of DFTs on overlapping short segments of the signal. The result is a two-dimensional representation: time on one axis, frequency on the other.
7.2 STFT Definition
Definition (STFT). The Short-Time Fourier Transform of signal with analysis window of length and hop size is:
where:
- is the frame index (time axis), is the starting sample of frame
- is the hop size (number of samples between consecutive frames, )
- is the FFT size (zero-padding if )
- is the number of frames
Parameters and their effects:
| Parameter | Effect |
|---|---|
| Window length | Longer -> better frequency resolution, worse time resolution |
| Hop size | Smaller -> more frames (denser time axis), more computation |
| FFT size | : zero-padding for denser frequency grid (not more resolution) |
| Window type | Hann (default), Hamming, Blackman - sidelobe/resolution tradeoff (Section 5.2) |
Whisper's STFT parameters: samples (25 ms), samples (10 ms), , window = Hann. At 16 kHz, this gives 257 frequency bins and one frame every 10 ms.
7.3 The Spectrogram
Definition (Spectrogram). The spectrogram is the squared magnitude of the STFT:
It represents the power (not amplitude) of each frequency at each time frame. Displayed as a heatmap (time on x-axis, frequency on y-axis, color = power), it visualizes how the frequency content of the signal evolves over time.
Log-power spectrogram: in decibels. The logarithmic scale compresses the dynamic range and matches the perceptual sensitivity of human hearing (roughly logarithmic in both time and frequency).
Mel spectrogram: sum the spectrogram over mel-frequency filterbanks (triangular filters spaced on the mel scale, which is a perceptual frequency scale logarithmic above 1 kHz). Used in Whisper, most modern ASR systems, and many audio AI models. Full details in Section 8.1.
Chirp spectrogram (example): a signal sweeping linearly from to shows a diagonal stripe in the spectrogram - the instantaneous frequency increases linearly with time. This illustrates how the STFT tracks time-varying frequency content.
7.4 Uncertainty Principle for STFT
The STFT cannot escape the Heisenberg uncertainty principle from Section 02. For the windowed transform with window of duration and bandwidth :
For a Hann window of length samples (duration ), the effective bandwidth is (the -3 dB bandwidth of the Hann spectral window). The time-frequency resolution product is fixed:
Practical consequence: you cannot simultaneously achieve:
- Fine time resolution (short window small )
- Fine frequency resolution (long window large )
For speech recognition (Whisper): samples -> , . For musical pitch tracking (need to distinguish semitones near 100 Hz): requires samples ( second window). The STFT is inadequate for simultaneously good time and frequency resolution across scales - this is exactly why wavelets exist (Section 05 Wavelets).
7.5 Synthesis and Perfect Reconstruction
Overlap-Add synthesis: Given STFT frames (possibly modified), reconstruct by:
where is the analysis window and is the synthesis window.
COLA (Constant Overlap-Add) condition: for perfect reconstruction of unmodified STFT:
Hann window with (50% overlap): for all - COLA satisfied.
Modified DFT (MDCT): audio codecs (AAC, Vorbis, Opus) use the MDCT - a cosine-based transform with 50% overlap and critically sampled (no redundancy). The MDCT satisfies exact reconstruction (called "Time Domain Aliasing Cancellation") and is why modern audio codecs can achieve high quality at low bit rates. Full filter bank theory is developed in Section 05 Wavelets.
Forward reference: The STFT and MDCT are the simplest multi-resolution analyses. Wavelets generalize this by allowing different window lengths at different frequencies - short windows at high frequencies (good time resolution) and long windows at low frequencies (good frequency resolution). See Section 20-05 Wavelets for the full treatment.
8. Applications in Machine Learning
8.1 Whisper: FFT Pipeline for Speech Recognition
OpenAI Whisper (Radford et al., 2022) is a 680M-parameter transformer trained on 680,000 hours of multilingual speech. Its input is not raw audio but an 80-channel log-mel spectrogram computed by a fixed FFT pipeline.
The Whisper preprocessing pipeline:
WHISPER AUDIO PREPROCESSING PIPELINE
========================================================================
Raw audio (PCM, 16 kHz)
|
1. Resample to 16 kHz (if needed)
|
2. Pad/trim to 30-second segments (480,000 samples)
|
3. STFT: window=Hann(400), hop=160, N_FFT=512
-> Complex spectrogram: shape (257, T_frames)
|
4. Power spectrogram: |STFT|2 -> shape (257, T_frames)
|
5. Apply 80 mel filterbanks (triangular, mel-spaced, 0-8000 Hz)
-> Mel power spectrogram: shape (80, T_frames)
|
6. Log compression: log10(max(mel_spec, 1e-10))
|
7. Normalize: (log_mel - mean) / 4 (empirically determined)
|
Transformer input: shape (80, 3000) for 30-second clip
(3000 frames 10ms/frame = 30 seconds)
========================================================================
Mel filterbanks: The mel scale maps frequency (Hz) to perceived pitch (mel):
Filterbanks are triangular filters equally spaced on the mel scale, covering the range . Human speech information is concentrated below 8 kHz; the mel scale matches the roughly logarithmic frequency resolution of the cochlea.
Why log-mel spectrograms? (1) Log compression matches the roughly logarithmic perception of loudness (Stevens' power law). (2) Log mel spectrograms are approximately translation-equivariant in the log-frequency dimension - a pitch shift is a translation in log-frequency. (3) Empirically, they produce much better ASR results than raw spectrograms or MFCCs (Mel-Frequency Cepstral Coefficients) for large-scale transformer models.
For AI: Every audio transformer (Whisper, AudioPaLM, MusicGen, AudioLM) uses a similar FFT -> mel spectrogram pipeline as its front-end. Understanding the pipeline is essential for debugging audio preprocessing bugs, which are among the most common sources of silent failure in audio AI systems.
8.2 Fourier Neural Operator (FNO)
The Fourier Neural Operator (Li et al., 2021, NeurIPS) is a neural architecture for learning solution operators of PDEs. Instead of learning to map one function to another pointwise, the FNO learns in the frequency domain.
Problem setting: given input function (e.g., initial condition of a PDE), learn the operator where is the solution (e.g., PDE solution at time ).
FNO layer: each FNO layer applies:
where:
- is the DFT along the spatial dimension
- is a learned complex weight matrix (parametrized by )
- is the number of retained frequency modes (truncation threshold)
- is a local linear transform (pointwise)
- is a nonlinearity
Key innovation: truncate to the lowest Fourier modes before applying :
This implements a global convolution with a low-frequency kernel - learning only the large-scale structure of the operator, discarding high-frequency noise. For 2D problems (e.g., Navier-Stokes), truncate to modes in each dimension.
Computational cost: for the DFT plus for the spectral convolution, vs. for full global convolution. For and : the FNO spectral layer is cheaper than full attention.
For AI: FNO was the first neural architecture to demonstrate that learning in frequency space outperforms learning in physical space for many PDE tasks. It has been extended to weather prediction (Pathak et al., 2022 "FourCastNet"), fluid dynamics, and climate modeling. The core idea - truncate, learn in frequency, invert - generalizes the classic Galerkin method from numerical PDE.
8.3 Monarch Matrices and Structured FFT
Dao et al. (2022, "Monarch: Expressive Structured Matrices for Efficient and Accurate Training") observed that the FFT matrix can be factored as a product of sparse butterfly matrices:
where is the bit-reversal permutation and each is a block-diagonal matrix with butterfly factors. Each has exactly non-zero entries (2 per butterfly), giving parameters per stage and total parameters for the full factorization.
Monarch parameterization: instead of fixing the butterfly structure to be the FFT, learn the butterfly weights:
where and are block-diagonal "butterfly-like" matrices. This gives a learnable structured matrix with parameters (between for diagonal and for dense).
Applications:
- Efficient attention: Monarch matrices can approximate attention in vs
- Hyperspherical projection: replacing standard linear layers with Monarch matrices in transformers for 2 speedup with minimal accuracy loss
- FFT-based initialization: Monarch matrices initialized as FFT butterfly factors learn sparse frequency representations naturally
For AI: The butterfly matrix decomposition connects signal processing (FFT structure) to deep learning (efficient matrix approximation). Models like FLASHATTENTION-2 and several emerging efficient transformer variants build on butterfly-structured operators as efficient replacements for dense weight matrices.
8.4 FlashFFTConv and Long-Range Convolutions
Dao et al. (2023, "FlashFFTConv: Efficient Convolutions for Long Sequences with Tensor Cores") addresses a key bottleneck in long-context sequence modeling: computing long convolutions efficiently on modern GPU hardware.
The problem: State Space Models (SSMs) like S4 (Gu et al., 2022) and Mamba (Gu & Dao, 2023) compute long convolutions in using the FFT-based convolution theorem. However, standard FFT implementations are memory-bandwidth-bound and do not efficiently utilize the Tensor Cores (matrix-multiply units) of modern GPUs (A100, H100).
FlashFFTConv solution: decompose the long convolution kernel of length using the Monarch factorization into a product of shorter matrix operations, enabling Tensor Core utilization while preserving asymptotic complexity.
Key results:
- 2-7.3 speedup over standard FFT convolution for sequences up to 4M tokens
- Linear memory in sequence length (vs. quadratic for full attention)
- Enables training SSMs on sequences orders of magnitude longer than attention allows
Connection to Mamba: Mamba (Gu & Dao, 2023) uses selective state spaces - a time-varying SSM where the transition matrices depend on the input. The resulting recurrence can be parallelized via a parallel scan (prefix sum), NOT an FFT. FlashFFTConv applies specifically to time-invariant SSMs like S4.
8.5 Spectral Methods in Graph Neural Networks
Graph Neural Networks (GCNs) performing spectral graph convolution use the graph Laplacian eigenvectors as a "Fourier basis" for the graph. The connection is:
- Graph Laplacian (where is degree matrix, is adjacency)
- Spectral decomposition provides "graph Fourier modes"
- Graph convolution: where is a learnable spectral filter
This is a graph-domain analog of the DFT, with the regular frequency grid replaced by the graph eigenvalue spectrum.
Forward reference to Section 11-04: The full treatment of spectral graph convolution - including ChebNet (Defferrard et al., 2016), GCN (Kipf & Welling, 2017), and the connection to the graph Laplacian - is the canonical content of Section 11-04 Spectral Graph Theory. Here we note only the structural analogy: DFT is to regular grids as graph Fourier transform is to irregular graphs.
9. Common Mistakes
| # | Mistake | Why It's Wrong | Fix |
|---|---|---|---|
| 1 | Using np.fft.fft output directly as frequency-domain amplitude without normalization | fft returns ; the amplitude of a unit sinusoid is , not 1 | Divide by (or for one-sided real FFT) to recover true sinusoidal amplitudes |
| 2 | Building frequency axis as np.arange(N) * fs / N and treating all bins as positive frequencies | Bins represent negative frequencies wrapped around; calling "frequency " is incorrect | Use np.fft.fftfreq(N, d=1/fs) which returns the correct signed frequencies; apply fftshift to center zero |
| 3 | Forgetting to apply fftshift before plotting a spectrum | Without fftshift, the negative-frequency bins appear at the right end of the plot, not the left, making the spectrum appear discontinuous | Always call fftshift(X) and fftshift(freqs) before plotting a two-sided spectrum |
| 4 | Concluding that zero-padding improves frequency resolution | Zero-padding increases the density of frequency bins but does NOT reduce ; two sinusoids closer than remain unresolvable regardless of zero-padding | Say "zero-padding interpolates the spectrum" not "improves resolution"; use longer observation windows for genuine resolution improvement |
| 5 | Applying DFT-property formulas (e.g., shift property) to linearly-shifted signals | The DFT shift property applies only to circular shifts. A linear shift (with zeros entering from one end) introduces boundary effects that invalidate | Use circular indexing explicitly, or use the linear convolution approach with appropriate zero-padding |
| 6 | Confusing the DFT normalization convention of different libraries | NumPy puts on ifft only; some textbooks use on both; PyTorch matches NumPy by default but has norm parameter options | Always check the documentation of the specific function; print a known signal (e.g., pure DC) and verify the expected coefficient |
| 7 | Misinterpreting spectral leakage as separate frequency components | When a sinusoid does not land on a DFT bin, its energy spreads to neighboring bins, appearing as multiple "peaks" in the spectrum | Apply a window function before the DFT and look for main lobes (not individual bins) as frequency indicators |
| 8 | Treating the Nyquist frequency bin as a complex value | For real input, is always real (by conjugate symmetry: ). Its imaginary part should be zero (up to numerical noise) | Assert np.allclose(X[N//2].imag, 0) for real input; take only the real part when reporting the Nyquist coefficient |
| 9 | Using an FFT size smaller than the signal length | If , NumPy silently truncates the input; this discards signal information and produces incorrect results | Set ; for linear convolution, use |
| 10 | Applying windowing after the FFT | Windows must be applied to the time-domain signal before the FFT. Multiplying the frequency-domain output by a window function is a circular convolution in frequency, not spectral smoothing | Multiply x * w in the time domain, then compute fft(x * w) |
| 11 | Overlooking numerical precision loss in the FFT | FFT algorithms propagate floating-point errors; for , accumulated rounding errors can be ; this matters for precision-sensitive applications | Use np.float64 (double precision) inputs; for critically sensitive applications, consider the inverse error bound |
| 12 | Applying DFT to complex-valued signals and expecting rfft to work | rfft assumes real input and returns values; calling it on complex input produces incorrect results (it treats the input as real, discarding imaginary parts) | Use fft (not rfft) for complex inputs; use rfft only when you are certain the signal is real-valued |
10. Exercises
Exercise 1 * - DFT by Hand
(a) Compute the 4-point DFT of by hand using . Show all four coefficients .
(b) Verify that equals the sum of all samples (DC component) and that satisfies Parseval's theorem.
(c) What is the IDFT of ? Compute by hand and verify.
(d) For , what is the DFT? Explain geometrically why for .
Exercise 2 * - DFT Matrix Properties
(a) Construct the 44 DFT matrix explicitly and verify numerically that .
(b) Show that where is the time-reversal permutation matrix (i.e., applying the DFT twice returns the time-reversed signal scaled by ).
(c) Compute the eigenvalues of and show they belong to . (Hint: .)
(d) For a random complex vector , numerically verify the unitary property: .
Exercise 3 * - FFT Implementation from Scratch
(a) Implement the radix-2 Cooley-Tukey FFT recursively in Python (without using numpy.fft). Your function should accept any power-of-2 length.
(b) Test on inputs of length . Verify against numpy.fft.fft with relative error .
(c) Time your implementation vs numpy.fft.fft for . By what factor is NumPy faster?
(d) Implement the bit-reversal permutation as a standalone function and verify it matches the permutation implicitly used by your FFT.
Exercise 4 ** - Spectral Leakage and Windowing
(a) Generate a signal for samples (a sinusoid at a non-integer frequency). Compute and plot the DFT magnitude for rectangular, Hann, and Blackman windows.
(b) Quantify the leakage: for the rectangular window, what fraction of the total spectral energy lies outside the main lobe (bins )?
(c) Two sinusoids at frequencies and cycles over samples. Show that they cannot be resolved with the rectangular window, but can be partially resolved after zero-padding to .
(d) Implement Kaiser window computation (using scipy.special.i0) and sweep from 0 to 14. Plot peak sidelobe level vs. main-lobe width. Reproduce the three window parameter rows from the table in Section 5.3.
Exercise 5 ** - Parseval, Energy, and the Power Spectral Density
(a) Generate a bandlimited noise signal: for with random phases . Verify Parseval's theorem numerically: .
(b) Compute the one-sided power spectral density (PSD) and identify the occupied bandwidth.
(c) Compare the PSD estimated by the DFT (single-frame) vs Welch's method (scipy.signal.welch, averaged over overlapping frames). Show that Welch's estimate is less noisy.
(d) For white noise , verify that the expected PSD is approximately flat, and that the variance of the PSD estimate decreases with the number of Welch averages.
Exercise 6 ** - STFT and Spectrogram Analysis
(a) Generate a chirp signal: with Hz, Hz, Hz, samples (1 second). Compute and display the STFT spectrogram using Hann window of length 256 samples with 50% overlap.
(b) Show how the spectrogram changes as you vary the window length: . Identify the time-frequency resolution tradeoff.
(c) Add a 500 Hz sinusoidal interference to the chirp. Show that a narrow window resolves the interference in time but not frequency, while a wide window resolves it in frequency but not time.
(d) Use the STFT to perform simple spectral subtraction denoising: estimate noise power from a "silent" region, subtract from all frames, reconstruct via overlap-add. Report the signal-to-noise ratio improvement.
Exercise 7 *** - Whisper Mel Spectrogram Pipeline
(a) Implement the full Whisper mel-spectrogram pipeline from scratch:
- STFT with Hann window (400 samples), hop 160, FFT size 512
- Power spectrogram
- 80 mel filterbanks covering 0-8000 Hz on the mel scale
- Log compression with floor at
Test on a 1-second synthetic signal: a mixture of three sinusoids at 300, 1200, and 3500 Hz.
(b) Verify that your mel filterbanks sum to (approximately) the total spectral power: .
(c) Apply your pipeline to the test signal and plot the 80100 mel spectrogram. Label the three sinusoid peaks.
(d) Analyze the effect of mel filterbank overlap: are the three sinusoids at 300, 1200, and 3500 Hz resolved in separate mel bins? What is the mel-bin width in Hz at each of the three frequencies?
Exercise 8 *** - Fourier Neural Operator: Spectral Convolution Layer
(a) Implement the 1D FNO spectral convolution layer:
def spectral_conv1d(x, weights, modes):
# x: (batch, channels, N)
# weights: (in_channels, out_channels, modes) complex
# modes: number of retained Fourier modes
The layer: DFT along last axis -> truncate to modes -> multiply by weights -> zero-pad -> IDFT.
(b) Test on the 1D Burgers' equation approximation: generate smooth initial conditions and apply your spectral layer. Show that retaining modes captures of the energy for smooth functions.
(c) Compare the spectral layer against a naive dense convolution layer of comparable parameter count. For and : how many parameters does the spectral layer have vs. the dense layer?
(d) Implement a 2-layer FNO and train it to approximate the integral operator on discretized grids of size . Report the relative error and show that the spectral layer generalizes across grid resolutions (resolution-invariance).
11. Why This Matters for AI (2026 Perspective)
| Concept | AI/ML Impact |
|---|---|
| FFT O(N log N) complexity | Foundation of all efficient sequence models: FNet, S4, Mamba, FNO, FlashFFTConv - the difference between feasible and infeasible at 100K+ token lengths |
| DFT matrix unitarity | Guarantees that FFT-based feature maps preserve signal energy; relevant to gradient stability in FNO and FNet - unitary transforms avoid the vanishing/exploding gradient problem in deep spectral networks |
| Spectral truncation | FNO's key innovation: learning only low-frequency behavior yields generalizable, resolution-invariant operators; matches the inductive bias that real physics is smooth |
| STFT and mel spectrograms | The front-end of every modern audio model (Whisper, AudioPaLM, MusicGen, AudioLM, VALL-E 2); getting the FFT pipeline right is prerequisite for any audio AI work |
| Windowing | Hann/Hamming windows in Whisper's STFT directly affect spectrogram quality; poor window choice causes leakage artifacts that corrupt speech features used by the ASR transformer |
| Butterfly matrix structure | Monarch matrices (Dao et al., 2022) parameterize structured transforms with parameters, enabling trainable FFT-like operations inside transformers at 2-4 speedup |
| Circular convolution theorem | Makes FFT-based convolution O(N log N) instead of O(N2); used in FlashFFTConv for long-range dependencies; connection to Section 04 where this is developed fully |
| Nyquist-Shannon theorem | Governs sample rate requirements for all audio AI; at 16 kHz (Whisper), the Nyquist limit is 8 kHz, matching the mel filterbank design; misunderstanding aliasing causes silent audio processing bugs |
| Frequency resolution | In FNO: retained modes determines the scale of PDE features the network can learn; too few modes = underfitting; too many = overfitting to noise; analogous to bandwidth selection in statistics |
| Fourier Neural Operator | State-of-the-art for weather prediction (FourCastNet, GraphCast partially inspired), fluid dynamics, and climate modeling at cost; represents the convergence of PDE numerics and deep learning |
12. Conceptual Bridge
Looking Backward
This section discretizes and algorithmizes the continuous Fourier Transform from Section 20-02. The connection is precise: the DFT evaluates the continuous FT of a sampled signal at equally-spaced frequencies, with errors bounded by the Nyquist theorem and the windowing artifact. Every property of the continuous FT - linearity, shift, scaling, Plancherel - has a discrete analog, with the crucial difference that shifts are now circular. The inner product of becomes the finite inner product on ; unitarity of the continuous FT (Plancherel) becomes unitarity of the DFT matrix. The Poisson summation formula from Section 02-7.5 directly explains why sampled spectra are periodic and why aliasing occurs.
The Cooley-Tukey FFT is not a mathematical theorem about the DFT - it is an algorithmic fact about how to implement the DFT matrix-vector product by exploiting the Vandermonde structure of the DFT matrix. The mathematics is in the DFT; the computer science is in the FFT.
Looking Forward
The immediate next step is Section 20-04 Convolution Theorem, which proves the central result previewed in Section 3.6: DFT multiplication equals circular convolution. This makes FFT-based convolution instead of , and underlies every CNN, SSM, and FNO architecture. Overlap-add and overlap-save (introduced in Section 5.5) are the standard tools for applying this theorem to long signals.
Section 20-05 Wavelets addresses the STFT's fundamental limitation: fixed time-frequency resolution. Wavelets use variable window sizes - short windows at high frequencies, long windows at low frequencies - to achieve optimal time-frequency localization simultaneously across all scales. The connection runs through the filter bank theory developed in Section 04: Daubechies wavelets are exactly the solution to the "perfect reconstruction filter bank" problem.
Further afield, the Fourier Neural Operator of Section 8.2 will appear again in advanced PDE-solving contexts, and the spectral graph convolution preview of Section 8.5 connects to Section 11-04 Spectral Graph Theory. The mathematical framework of the DFT as a change of basis in a finite-dimensional Hilbert space generalizes to infinite-dimensional Hilbert spaces in Section 12-02 Hilbert Spaces, where the orthonormal Fourier basis becomes a complete orthonormal system and Parseval's identity extends to an equality that characterizes separable Hilbert spaces.
POSITION IN THE FOURIER ANALYSIS CURRICULUM
========================================================================
Section 20-01 Fourier Series periodic functions, L2[-,]
v (take period T -> infty)
Section 20-02 Fourier Transform continuous FT, Plancherel, uncertainty
v (sample at rate fs, observe N points)
Section 20-03 DFT and FFT <- YOU ARE HERE
v (DFT multiplication = circular convolution)
Section 20-04 Convolution Theorem CNNs, WaveNet, S4/Mamba, Hyena
v (variable-resolution analysis)
Section 20-05 Wavelets MRA, Daubechies, scattering networks
Key Connections:
+-----------------------------------------------------------+
| DFT = discrete + finite version of the continuous FT |
| FFT = O(N log N) algorithm for computing the DFT matrix |
| STFT = sliding DFT -> time-frequency representation |
| Windowing = control leakage frequency resolution |
| Parseval: x2 = X2/N (energy conserved by DFT) |
| Circular convolution theorem -> leads to Section 04 |
| Fixed resolution limitation of STFT -> leads to Section 05 |
+-----------------------------------------------------------+
========================================================================
<- Back to Fourier Analysis | Previous: Fourier Transform <- | Next: Convolution Theorem ->
Appendix A: Extended DFT Theory
A.1 The DFT as a Projection onto the Fourier Basis
The geometric interpretation of the DFT deserves deeper development. Working in with the standard Hermitian inner product , we construct the Fourier basis.
Orthonormality proof. Define . Then:
by the geometric sum formula. The normalized DFT matrix has columns (up to conjugation), confirming it is unitary.
The DFT as expansion coefficients. The expansion of any in the Fourier basis is:
The DFT coefficient is times the coordinate of in the -th Fourier direction.
Projection interpretation. measures the "overlap" or "correlation" of with the -th complex sinusoid. A large means has significant oscillatory component at frequency cycles per sample.
A.2 Spectral Density and the Periodogram
The periodogram is the classical (non-parametric) estimator of the Power Spectral Density (PSD):
The periodogram is an inconsistent estimator - its variance does not decrease as , even though its mean converges to the true PSD. This is because each DFT coefficient is approximately a chi-squared random variable with 2 degrees of freedom, regardless of .
Smoothed periodogram estimators:
-
Bartlett's method: average periodograms from non-overlapping blocks of length . Reduces variance by factor (number of blocks) at the cost of frequency resolution .
-
Welch's method: average periodograms from overlapping windowed blocks. With 50% overlap and blocks: variance reduction , same frequency resolution as Bartlett.
-
Multitaper method (Thomson, 1982): use multiple orthogonal "Slepian" (DPSS) tapers instead of one window. Optimal bias-variance tradeoff for stationary processes.
For AI: Welch's method is used in biomedical signal processing (EEG power spectra), audio analysis, and anomaly detection. Understanding PSD estimation is essential for interpreting spectral features in any time-series ML pipeline.
A.3 The Discrete-Time Fourier Transform (DTFT) Relation
The DTFT of an infinite sequence is:
The DTFT produces a continuous spectrum over the normalized frequency .
DFT as sampled DTFT. If is nonzero only for (or equivalently, if we window to this range), then:
The DFT is obtained by sampling the DTFT at equally-spaced points on the unit circle. Denser sampling (larger or zero-padding) evaluates the DTFT at more points but does not change the underlying DTFT.
The -transform connection. The DTFT evaluates the -transform on the unit circle . The DFT evaluates it at equally-spaced points on the unit circle. Poles of inside the unit circle correspond to stable causal systems.
A.4 Goertzel Algorithm: Single-Frequency DFT
Computing the entire -point DFT costs . If you need only a single DFT coefficient for a specific frequency , the FFT is wasteful. The Goertzel algorithm computes in operations using a second-order IIR filter.
Second-order filter interpretation. Define with . Then (initialized with ).
Applications:
- DTMF (Dual-Tone Multi-Frequency) telephone tone decoding: detect specific frequencies (697, 770, 852, 941, 1209, 1336, 1477, 1633 Hz)
- Musical pitch detection when only octave-frequency analysis is needed
- Frequency-selective filtering in embedded systems with limited memory
Appendix B: Advanced FFT Topics
B.1 In-Place FFT and Memory Efficiency
The butterfly computation in the DIT-FFT can be performed in-place: the two output values of each butterfly can overwrite the two input values, because after the butterfly both inputs are no longer needed. This means the entire -point FFT can be computed using only the complex input/output array (plus twiddle factor storage).
Implementation sketch:
FOR each stage s = 1, 2, ..., log2(N):
stride = N / 2^s
FOR each group g = 0, 1, ..., 2^(s-1) - 1:
twiddle = omega^{-g * stride}
FOR each butterfly within group:
a = x[position]
b = twiddle * x[position + stride]
x[position] = a + b (overwrite)
x[position + stride] = a - b (overwrite)
This avoids allocating a second array of size , halving memory usage - critical for embedded systems and for FFTs of very large signals.
B.2 Multi-Dimensional FFT
The 2D DFT is separable: apply a 1D FFT to each row, then a 1D FFT to each column (or vice versa):
Computational cost: FFTs of length (for rows) plus FFTs of length (for columns) = .
Applications in AI:
- Image processing: 2D FFT used for frequency-domain image filtering, noise removal, and texture analysis
- Convolutional neural networks: image convolution can be computed via 2D FFT for large kernels ( vs for direct convolution with kernel size )
- FNO on 2D domains: the 2D FNO for Navier-Stokes uses 2D DFT with retained modes
B.3 Number-Theoretic Transform (NTT)
The Number-Theoretic Transform replaces complex arithmetic with arithmetic modulo a prime . The NTT uses a primitive -th root of unity modulo - an integer such that and for .
Why NTT matters: unlike the FFT with floating-point arithmetic, the NTT is exact (integer arithmetic modulo ). It is used for:
- Polynomial multiplication modulo a prime: key operation in lattice-based cryptography (NTRU, CRYSTALS-Kyber)
- Large integer multiplication: GNU MP library uses NTT for multiplying large integers
- Post-quantum cryptography: Kyber and Dilithium (NIST post-quantum standards) rely on NTT for efficient polynomial operations
For AI security: language model serving with privacy guarantees (homomorphic encryption) requires NTT-based polynomial multiplications. The efficiency of NTT directly affects the feasibility of private inference for LLMs.
Appendix C: Worked Examples
C.1 Complete DFT Computation: 8-Point Example
Let . Compute the 8-point DFT.
Step 1: Note that is symmetric: for . By conjugate symmetry for real input, . For a symmetric real input, all are real.
Step 2: Even and odd subsequences:
- Even:
- Odd:
Step 3: 4-point DFT of even subsequence ():
Step 4: 4-point DFT of odd subsequence:
Step 5: Combine with twiddle factors :
Computing ... the exact arithmetic is tedious; numerically: .
Verification: PASS. Parseval: ; PASS.
C.2 Leakage Quantification: Rectangular vs Hann
Signal: sampled at Hz for samples. The frequency lies exactly halfway between bins 3 and 4.
Rectangular window: All 16 DFT values are nonzero. The two closest bins (, ) have magnitude each (out of a maximum of 8 for a bin-aligned frequency). The farthest bins () have magnitude . Leakage energy (all bins except 3, 4): of total.
Hann window: . The main lobe is now 4 bins wide (bins 2, 3, 4, 5 have significant energy). Leakage energy outside the main lobe: - a 100 reduction in far-field leakage.
Trade-off: the Hann window "blurs" the frequency axis (wider main lobe), but dramatically reduces interference from distant frequency components. For audio analysis with multiple simultaneous tones, the Hann window is almost always preferred.
C.3 FFT for Image Compression (Preview)
A grayscale image of size has pixel values. The 2D DFT produces complex frequency coefficients.
Low-frequency concentration: natural images have most energy in low spatial frequencies - slowly varying regions (sky, smooth surfaces). Empirically, the top-left corner of the DFT magnitude (the lowest 16 frequencies in each direction) typically captures of total image energy.
Compression idea: retain only DFT coefficients. Setting all others to zero and applying the IDFT gives a low-frequency reconstruction. For : retained coefficients out of (), with visually acceptable reconstruction for most images.
This is the conceptual predecessor of JPEG, which uses the Discrete Cosine Transform (DCT) - the real-valued cousin of the DFT - in blocks, achieving better compression due to avoiding complex arithmetic and reducing boundary artifacts.
Appendix D: Numerical Implementation Notes
D.1 Choosing FFT Size for Maximum Speed
Different values of require dramatically different computation times even with the same asymptotic complexity. FFTW benchmarks (in rough order of efficiency):
| type | Relative speed |
|---|---|
| Powers of 2 () | Fastest |
| Products | Very fast |
| Smooth numbers (all prime factors ) | Fast |
| Prime (uses Bluestein) | Slow - avoid if possible |
| for large prime | Slow |
Rule of thumb: always zero-pad to a highly composite number. scipy.fft.next_fast_len(N) returns the smallest integer that has only small prime factors.
D.2 Avoiding Common Numerical Pitfalls
Precision requirements:
float32(single precision): round-off error per operation. For : accumulated FFT error .float64(double precision): error per operation. FFT error for : .
For audio processing (16-bit integer input -> 32-bit float): single precision is fine. For scientific computing or precision-sensitive applications: use double precision.
Large DFT sizes and memory bandwidth: for , the FFT becomes memory-bandwidth-limited rather than compute-limited. The working set (the data being accessed at each butterfly stage) exceeds the CPU cache, and cache misses dominate runtime. For very large FFTs: consider FFT algorithms with cache-oblivious access patterns (e.g., FFTW's recursive divide-and-conquer).
D.3 GPU FFT Considerations
CUDA FFT (cuFFT) and ROCm FFT achieve peak performance for:
- Power-of-2 sizes on any GPU
- Batch FFTs (many independent FFTs of the same size): significantly faster than sequential single FFTs
- Real-to-complex (rfft) transforms on modern GPUs with Tensor Cores
For ML training: when using FNO or FlashFFTConv, always batch the FFT computation across the mini-batch and channel dimensions simultaneously. torch.fft.fft(x, dim=-1) can process a (batch, channels, N) tensor with a single cuFFT call, achieving near-peak GPU utilization.
Appendix E: Connections to Other Areas
E.1 DFT and Polynomial Multiplication
The DFT has an elegant algebraic interpretation: it converts polynomial multiplication in the ring into pointwise multiplication of coefficient sequences.
Fact. Let and . Their product modulo is the circular convolution . The DFT converts this to (pointwise product). Thus: DFT diagonalizes the cyclic convolution operator.
More precisely, the matrix of circular convolution by (the circulant matrix ) has eigenvectors equal to the Fourier basis vectors , with eigenvalues :
The DFT simultaneously diagonalizes all circulant matrices. This is the algebraic foundation of the Convolution Theorem (Section 04).
E.2 DFT and Number Theory: Quadratic Gauss Sums
The Gauss sum arises naturally in number theory and signal processing. Its magnitude satisfies , which is the basis for several FFT-based tricks.
Bluestein's algorithm uses the identity to rewrite the DFT as a convolution:
This is a convolution of with the chirp kernel , computable via FFT for any .
E.3 DFT and the Cooley-Tukey Prime Factor Algorithm
When with , the Good-Thomas (Prime Factor) Algorithm maps the 1D DFT to a 2D DFT via the Chinese Remainder Theorem (CRT). This gives a different algorithm from Cooley-Tukey that:
- Requires no twiddle-factor multiplications (only additions)
- Is advantageous when has many small coprime factors
The CRT mapping is with . The DFT factors as:
Connection to representation theory: the Good-Thomas algorithm expresses the DFT on a cyclic group in terms of DFTs on subgroups and when is coprime. The general theory of DFT on finite abelian groups is a special case of harmonic analysis on locally compact abelian groups (Pontryagin duality), which is developed in full in Section 12 Functional Analysis.
Appendix F: DFT Properties - Detailed Proofs
F.1 Time Reversal
If , then .
Proof.
Consequence. For real : (conjugate symmetry, Section 3.4). Time reversal in the time domain maps to frequency reversal (conjugation) in the frequency domain.
F.2 Duality
If (i.e., the time-domain signal equals the DFT of another signal), then:
Proof. From the IDFT: . Replace and :
Therefore .
Application. If is a rectangular pulse (1 for , else 0), its DFT is a Dirichlet kernel. By duality, if the input is a Dirichlet kernel, the DFT is (essentially) a rectangular pulse. This is the discrete analog of the rectangle-sinc FT pair.
F.3 DFT of Real and Imaginary Parts
For a complex signal with real parts and :
This allows computing two real DFTs in the time of one complex DFT - an important optimization for processing stereo audio or in-phase/quadrature (IQ) signals.
Appendix G: Windowing Theory - Spectral Analysis Framework
G.1 The Window Design Problem
Given a finite observation of an infinite signal , the DFT gives:
where is the DFT of the window. The true spectrum is "blurred" by .
Ideal window properties (contradictory):
- (no leakage - only possible for infinite observation)
- for (rectangular window: maximum time-domain energy)
- Compact support in both time and frequency (impossible by uncertainty principle)
Any window must trade off between these competing desiderata. The Kaiser window with adjustable offers a continuous tradeoff between resolution and leakage control.
G.2 Sidelobe Rolloff Rate
The rate at which sidelobes decrease away from the main lobe is called the rolloff rate (in dB per octave):
- Rectangular window: discontinuities at and -> -> rolloff
- Hann window: continuous at endpoints (value 0) but derivative discontinuity -> -> rolloff
- Blackman window: zero at endpoints with zero first and second derivatives -> -> rolloff (but lower peak sidelobe)
Generalization. A window with continuous derivatives at the endpoints has sidelobe falloff , corresponding to a rolloff rate of . This is a direct consequence of the Riemann-Lebesgue lemma applied to the windowed Fourier series.
G.3 Optimal Windows: Prolate Spheroidal Wave Functions
The Slepian sequences (discrete prolate spheroidal wave functions, DPSS) are the theoretically optimal windows in the following sense:
Problem. Among all windows with , find the one that maximizes the fraction of energy concentrated in (a specified bandwidth):
The solution is the first Slepian sequence, which is the eigenvector corresponding to the largest eigenvalue of the matrix .
Slepian sequences achieve theoretically optimal concentration - the maximum possible energy fraction in a given bandwidth - and are used in multitaper spectral estimation (Section A.2).
Appendix H: The FFT in Modern Hardware
H.1 Vectorization and SIMD
Modern CPUs provide SIMD (Single Instruction Multiple Data) instructions that process multiple values simultaneously:
- SSE2: 2 double-precision complex numbers per operation
- AVX2: 4 double-precision complex numbers per operation
- AVX-512: 8 double-precision complex numbers per operation
FFTW automatically generates SIMD-optimized code for each detected instruction set. For at double precision, AVX-512 provides approximately 8 speedup over scalar code.
H.2 GPU FFT (cuFFT)
NVIDIA's cuFFT library achieves peak performance by:
- Tiling: decomposing the DFT into tiles that fit in shared memory (SRAM)
- Warp-level butterfly: mapping butterfly computations to warp-level shuffle operations
- Tensor Core utilization: for batch FFTs, reformulating twiddle-factor multiplication as GEMM operations executable on Tensor Cores
Peak throughput: NVIDIA H100 achieves on batch FFTs of power-of-2 size with float16 (half precision).
H.3 Distributed FFT for Very Large Transforms
For transforms exceeding GPU memory (e.g., ), the DFT can be decomposed across multiple GPUs using the row-column algorithm:
- Distribute points across GPUs: each GPU holds rows
- Each GPU applies 1D FFT to its rows (-point FFTs)
- All-to-all communication transposes the data (global shuffle)
- Each GPU applies 1D FFT to its columns (-point FFTs) and applies twiddle factors
- Final all-to-all restores the layout
Total communication: complex numbers per GPU per transpose step. For GPUs and : data movement per step.
Applications: seismic data processing, climate modeling, and cosmological simulations routinely require distributed FFTs of - points.