Module contents
Lesson 23 of 25Advanced 100 min

Structured matrices: Toeplitz, circulant and the Fourier transform

Convolutions, filters, rotary positional encoding and state-space models are structured matrices; exploiting structure turns O(n²) into O(n log n). Study complex spaces and unitary matrices, the DFT as a unitary basis change, Toeplitz and circulant matrices and convolution as diagonalization, then structured families used in modern efficient models.

After this lesson you can

  • Work with Hermitian inner products, adjoints, and unitary and Hermitian matrices.
  • Prove that the DFT is unitary up to scale and diagonalizes all circulant matrices.
  • Represent 1D convolution as a Toeplitz matrix product and compute it with the FFT.
  • Distinguish circular and linear convolution and apply correct zero padding.
  • Recognize semiseparable, butterfly and Monarch structures and their matrix-vector product cost.

Before you start

Motivation: matrices you multiply without writing them down

A dense layer with nn inputs and nn outputs stores n2n^2 weights and spends n2n^2 multiplications on each matrix-vector product. With n=216=65 536n = 2^{16} = 65\,536 that is 4.29×1094.29 \times 10^9 numbers, about 17 GB in float32: more than fits in most consumer GPUs. Yet some matrices of that size are stored in nn numbers and multiplied in a fraction of the time. They are not unusual; they are among the most widely used.

  • Filters and convolutions. Smoothing a signal, differentiating it, detecting image edges or applying a convolutional layer: each output is the same local combination of inputs, shifted by one position. As a matrix, that regularity is called Toeplitz.
  • Rotary positional encoding (RoPE). In a transformer, the score between positions mm and nn is built using rotations so it depends only on n−mn - m (you will see precisely how in the RoPE section and the complete mechanism in RoPE).
  • State-space models and long convolutions. A model that processes a sequence of length TT with a linear recurrence is equivalent to multiplying by a structured triangular matrix. Hyena applies filters as long as the sequence and computes them with the FFT (Poli et al., 2023).
  • Spectral methods. Differentiating a periodic function becomes multiplying each Fourier coefficient by a scalar, so these methods solve partial differential equations with smooth solutions to accuracy finite differences cannot reach (Fourier neural operators).

All four cases share a root. A Toeplitz matrix n×nn \times n is determined by 2n−12n - 1 numbers, not n2n^2, and Euler’s formula together with an idea from this module, diagonalization, turns its product (after embedding it in a circulant matrix of twice the size) into elementwise multiplication between two changes of basis. The change of basis is the discrete Fourier transform, and an algorithm computes it in O(nlog⁡n)\bigO(n \log n) rather than O(n2)\bigO(n^2). For n=216n = 2^{16} the ratio is n2/(nlog⁡2n)=n/log⁡2n=4096n^2/(n\log_2 n) = n/\log_2 n = 4096.

The lesson proceeds from convolution as a matrix, the intuition, to the necessary algebra (complex numbers, adjoints and unitary matrices); the DFT matrix and its factorization into sparse matrices (the FFT); circulant matrices, all diagonalized by the DFT; RoPE rotations as an instance of the same structure; and a map of structured families used by today’s models, through Monarch.

Intuition: a convolution is a matrix

Let x∈Rn\vb{x} \in \R^n be a signal and h∈Rm\vb{h} \in \R^m a filter (the kernel). The convolution of h\vb{h} with x\vb{x} is

(h∗x)j=∑l=0m−1hl xj−l,j=0,1,…,n+m−2,(\vb{h} * \vb{x})_j = \sum_{l=0}^{m-1} h_l\, x_{j-l}, \qquad j = 0, 1, \dots, n + m - 2,

with xk=0x_k = 0 outside 0≤k≤n−10 \le k \le n - 1. In this lesson vector and matrix indices begin at 0, as in the code, so DFT formulas have no offsets. The output has n+m−1n + m - 1 entries. To compute yjy_j, reverse the kernel, place it over the signal with h0h_0 under xjx_j, and sum the products of overlapping entries: the sliding window. This is linear in x\vb{x}, so it is a matrix times x\vb{x}. The figure shows both views at once.

InteractiveConvolution is a matrix
Sliding window: the reversed kernel over the signal
h₀h₁h₂
−4−3−2−1012345678910111213
Products hl xj−lh_l\,x_{j-l} of overlapping pairs: their sum is y0y_{0}
y0=h0 x0+h1 x−1+h2 x−2=(0.25)(0)+(0.5)(0)+(0.25)(0)=0y_{0} = h_{0}\,x_{0} + h_{1}\,x_{-1} + h_{2}\,x_{-2} = (0.25)(0) + (0.5)(0) + (0.25)(0) = 0
j = 0
The same operation: Tx\mat{T}\vb{x}, with row 0 highlighted
0123456789012345678910110.250.500.250.250.500.250.250.500.250.250.500.250.250.500.250.250.500.250.250.500.250.250.500.250.250.500.250.250.500.25y
Each cell is a kernel entry hlh_l (orange if positive, violet if negative); on the right are output y\vb{y} bars by row.
  • signal x\vb{x}
  • reversed kernel h\vb{h}
  • products and output y\vb{y}
  • padding slots (zeros)
Mode
3
Edit h (drag)
012
y0y_{0} by window0.000
y0y_{0} by matrix0.000
Difference0
Shape of T\mat{T}12 × 10
T\mat{T} is 12×1012\times 10 and Toeplitz: every diagonal is constant. Each column is the kernel shifted one position.
On the left, the sliding window: kernel h\vb{h} (orange), reversed and positioned over signal x\vb{x} (blue) to compute output yjy_j. On the right, the same operation as row jj of matrix T\mat{T} times x\vb{x}. Press play or drag the jj slider and observe that the highlighted row is the reversed kernel over the columns touched by the window, and each diagonal of T\mat{T} is constant. Drag the bars of x\vb{x} and h\vb{h}. Then change mode: causal keeps only the first nn outputs and the matrix becomes triangular; in circular mode what the kernel leaves at one end reappears at the other and T\mat{T} becomes a matrix whose columns are cyclic shifts of one another (a circulant).

Entry (j,k)(j, k) of T\mat{T} is hj−kh_{j-k} if 0≤j−k<m0 \le j - k < m and zero otherwise: it depends only on the difference j−kj - k. This is exactly what is called a Toeplitz matrix.

Three qualifications we will use later:

  • Full, causal and circular convolution. The figure’s matrix in full mode has size (n+m−1)×n(n + m - 1) \times n. Keeping only the first nn outputs (what a causal model does: yjy_j depends on x0,…,xjx_0, \dots, x_j) makes it lower triangular. If the signal wraps around in a circle, the result is square with an even stronger structure, which occupies most of the rest of the lesson.
  • Two Toeplitz matrices do not yield a Toeplitz matrix. The product of two general Toeplitz matrices is not Toeplitz, so they do not form an algebra. Lower triangular ones do: if Ta\mat{T}_a and Tb\mat{T}_b are causal matrices of two kernels, their product is the causal matrix of kernel a∗b\vb{a} * \vb{b} (truncated), just as when multiplying polynomials and retaining terms of degree less than nn. And since a∗b=b∗a\vb{a} * \vb{b} = \vb{b} * \vb{a}, these matrices commute.
  • In two dimensions, convolving an image with a kernel is a block Toeplitz matrix with Toeplitz blocks. If the kernel is separable, K=ab⊤\mat{K} = \vb{a}\vb{b}\T, that matrix is a Kronecker product of two small Toeplitz matrices, Ta⊗Tb\mat{T}_a \otimes \mat{T}_b, as you will verify in code.

Direct multiplication by an m×nm \times n Toeplitz matrix costs O(mn)\bigO(mn). For an 3×33 \times 3 pixel kernel that is small, and convolutional layers do just that (convolution as a structured matrix). But for a filter as long as the signal, m≈nm \approx n, it is O(n2)\bigO(n^2), and we want to reduce it. To do so, understand what diagonalizes circulants; for that, some algebra in Cn\C^n.

Complex numbers, adjoints and unitary matrices

Fourier waves e2πimk/ne^{2\pi i mk/n} are complex, so we need to measure lengths and angles in Cn\C^n. The first intuition, copying x⊤y\vb{x}\T\vb{y}, fails. With x=(1,i)\vb{x} = (1, i) it would yield x⊤x=1+i2=0\vb{x}\T\vb{x} = 1 + i^2 = 0 for a nonzero vector. The correction is conjugation.

This generalizes familiar matrix families; lessons 9 and 12 covered their real versions (orthogonal and symmetric).

Proof

(1) is the definition entry by entry: (U∗U)jl=uj∗ul(\mat{U}^*\mat{U})_{jl} = \vb{u}_j^*\vb{u}_l. (2) ⟨Ux,Uy⟩=x∗U∗Uy=x∗y\inner{\mat{U}\vb{x}}{\mat{U}\vb{y}} = \vb{x}^*\mat{U}^*\mat{U}\vb{y} = \vb{x}^*\vb{y}. (3) If Uv=λv\mat{U}\vb{v} = \lambda\vb{v} with v≠0\vb{v} \neq \vb{0}, by (2) ∥v∥=∥Uv∥=∣λ∣∥v∥\norm{\vb{v}} = \norm{\mat{U}\vb{v}} = \abs{\lambda}\norm{\vb{v}}. (4) (UV)∗UV=V∗U∗UV=I(\mat{U}\mat{V})^*\mat{U}\mat{V} = \mat{V}^*\mat{U}^*\mat{U}\mat{V} = \mat{I}, and U∗\mat{U}^* is unitary because UU∗=I\mat{U}\mat{U}^* = \mat{I}. For Hermitian matrices: if Av=λv\mat{A}\vb{v} = \lambda\vb{v}, then λ∥v∥2=v∗Av\lambda\norm{\vb{v}}^2 = \vb{v}^*\mat{A}\vb{v} and this number equals its conjugate, v∗Av‾=v∗A∗v=v∗Av\overline{\vb{v}^*\mat{A}\vb{v}} = \vb{v}^*\mat{A}^*\vb{v} = \vb{v}^*\mat{A}\vb{v}, hence λ∈R\lambda \in \R. With Aw=μw\mat{A}\vb{w} = \mu\vb{w} and λ≠μ\lambda \neq \mu, λ⟨w,v⟩=⟨w,Av⟩=⟨Aw,v⟩=μ⟨w,v⟩\lambda\inner{\vb{w}}{\vb{v}} = \inner{\vb{w}}{\mat{A}\vb{v}} = \inner{\mat{A}\vb{w}}{\vb{v}} = \mu\inner{\vb{w}}{\vb{v}} (with μ\mu real), and then ⟨w,v⟩=0\inner{\vb{w}}{\vb{v}} = 0.

∎

Unitary matrices are rotations of complex space: they change basis without deforming anything. The generalization of the spectral theorem covers a broader class than symmetric matrices and is what we need.

(Prove it by triangularizing with a unitary matrix, the Schur decomposition, and observing that a normal triangular matrix is diagonal.) Normal matrices include Hermitian ones, with real eigenvalues; unitary ones, with eigenvalues on the unit circle; and, as we will see, all circulants, with an eigenvector basis known in advance.

The DFT matrix

Let n≥1n \ge 1 and ω=e−2πi/n\omega = e^{-2\pi i/n}, an nnth root of unity: ωn=1\omega^n = 1 and ∣ω∣=1\abs{\omega} = 1. The numbers 1,ω,…,ωn−11, \omega, \dots, \omega^{n-1} are vertices of a regular polygon inscribed in the unit circle (by Euler’s formula). Everything that follows comes from a property visible in the polygon: when its vertices are summed, the vectors cancel.

Proof

If nn divides kk, each summand is ωjk=1\omega^{jk} = 1. Otherwise ωk≠1\omega^k \neq 1 and the geometric sum gives 1−ωkn1−ωk=1−11−ωk=0\dfrac{1 - \omega^{kn}}{1 - \omega^k} = \dfrac{1 - 1}{1 - \omega^k} = 0, because ωkn=(ωn)k=1\omega^{kn} = (\omega^n)^k = 1.

∎

For n=4n = 4, with ω=−i\omega = -i:

F4=[11111−i−1i1−11−11i−1−i].\mat{F}_4 = \begin{bmatrix} 1 & 1 & 1 & 1 \\ 1 & -i & -1 & i \\ 1 & -1 & 1 & -1 \\ 1 & i & -1 & -i \end{bmatrix}.

This is the NumPy, SciPy and MATLAB convention. The inverse has the opposite sign and factor 1/n1/n; other libraries and books distribute the scale as 1/n1/\sqrt n in both directions or reverse the sign. This is a classic source of errors; changing convention conjugates all the lesson’s results.

Columns are waves

Call wm∈Cn\vb{w}_m \in \C^n the sampled complex exponential of frequency mm (it completes mm turns in nn samples):

(wm)k=e2πi mk/n,k=0,…,n−1.(\vb{w}_m)_k = e^{2\pi i\, mk/n}, \qquad k = 0, \dots, n - 1.

Its real and imaginary parts are sampled cosine and sine. The wm\vb{w}_m are columns of F∗=F‾\mat{F}^* = \overline{\mat{F}}, and the rows of F\mat{F} are their conjugates, so Xm=⟨wm,x⟩X_m = \inner{\vb{w}_m}{\vb{x}}: coefficient XmX_m measures how much of wave mm is in x\vb{x}. If the waves formed an orthogonal basis, their coordinates could be read off as inner products. And they do.

Proof

Entry (j,l)(j, l) of F∗F\mat{F}^*\mat{F} is ∑kωkj‾ ωkl=∑kωk(l−j)\sum_k \overline{\omega^{kj}}\,\omega^{kl} = \sum_k \omega^{k(l-j)}, because ω‾=ω−1\overline{\omega} = \omega^{-1}. By the lemma it equals nn if l=jl = j and 00 otherwise (the difference l−jl - j lies between −(n−1)-(n-1) and n−1n-1 and is a multiple of nn only at 0). The rest follows from the unitary theorem: U−1=U∗\mat{U}\inv = \mat{U}^* gives the inverse and ∥Ux∥=∥x∥\norm{\mat{U}\vb{x}} = \norm{\vb{x}} gives Parseval.

∎

That is the entire content of the DFT. It is a unitary change of basis: signal x\vb{x} is written in the canonical basis, c=Fx/n\vb{c} = \mat{F}\vb{x}/\sqrt n is the same signal written in the wave basis, and its length is unchanged, ∥c∥=∥x∥\norm{\vb{c}} = \norm{\vb{x}}. The energy of x\vb{x} is distributed among frequencies, ∥x∥2=∑m∣cm∣2\norm{\vb{x}}^2 = \sum_m \abs{c_m}^2 (Parseval’s or Plancherel’s theorem, depending on the book). If x\vb{x} is real, also Xn−m=Xm‾X_{n-m} = \overline{X_m}, so frequencies mm and n−mn - m have equal energy and come together.

InteractiveDecompose a signal into frequencies
Signal x\vb{x} (drag the bars), reconstruction x^\hat{\vb{x}} with KK harmonics, and cursor at time tt
0123456789101112131415
Energy ∣cm∣2\abs{c_m}^2 by frequency mm (pink: retained; select to choose)
02.254.50123456789101112131415
For a real signal, ∣cn−m∣=∣cm∣\abs{c_{n-m}} = \abs{c_m}: frequencies mm and n−mn-m come together.
Epicycles: each coefficient is an arrow turning mm times per period
  • signal x\vb{x}
  • reconstruction x^\hat{\vb{x}}
  • counterclockwise (+m+m)
  • clockwise (−m-m)
3 / 9
2.50
∥x∥2\norm{\vb{x}}^2 (in time)10.2400
∥c∥2\norm{\vb{c}}^2 (in frequency)10.2400
Energy retained96.8 %
Error ∥x−x^∥2\norm{\vb{x} - \hat{\vb{x}}}^2 measured in time0.3327
Discarded energy (sum of ∣cm∣2\abs{c_m}^2)0.3327
The error is the energy of discarded coefficients: Parseval, because the DFT (with 1/n1/\sqrt{n}) is unitary.
Draw a 16-sample signal by dragging the bars (or choose a preset). Its energy spectrum ∣cm∣2\abs{c_m}^2 is at lower left, and arrows on the right show coefficients as epicycles: each rotates mm times per period, blue in one direction and orange in the other; the chain's tip is the reconstructed value x^(t)\hat{x}(t) at time tt (the upper slider). Retain only the KK highest-energy harmonics: the error read in time matches the discarded energy read in frequency, by Parseval. Try the pulse (what is its spectrum?), the square wave (how many harmonics capture 90% of energy?) and noise.

Three things to check in the figure. An isolated pulse has a flat spectrum (all frequencies with the same energy, 1/161/16): the opposite of a pure wave, which occupies a single pair m,n−mm, n - m. The square wave has only odd harmonics, with energy distributed approximately as 1/m21/m^2: with K=1K = 1 (the pair m=1,15m = 1, 15) it has 82% of the energy, with K=2K = 2 92%, and with K=4K = 4 100%. With all harmonics, reconstruction passes exactly through the 16 samples whatever the signal. That is what F−1F=I\mat{F}\inv\mat{F} = \mat{I} says.

The FFT: the dense matrix is a product of sparse matrices

Multiplying by F\mat{F} in the obvious way costs n2n^2 complex multiplications. The fast Fourier transform (FFT, Cooley and Tukey, 1965) does it in O(nlog⁡n)\bigO(n \log n). The idea is divide and conquer, and in matrix language says Fn\mat{F}_n is a product of a few very sparse matrices. Only the statement is needed here because the algorithm and its analysis are covered in DFT and FFT.

Proof

Separate the sum of XjX_j into even and odd indices, k=2sk = 2s and k=2s+1k = 2s + 1: Xj=∑sx2s ω2sj+ωj∑sx2s+1 ω2sjX_j = \sum_s x_{2s}\,\omega^{2sj} + \omega^j \sum_s x_{2s+1}\,\omega^{2sj}. Since ω2=e−2πi/m\omega^2 = e^{-2\pi i/m} is the mmth root of unity, each sum is an order-mm DFT of the even (EjE_j) and odd (OjO_j) samples, and they are periodic in jj with period mm. Thus Xj=Ej+ωjOjX_j = E_j + \omega^j O_j, and since ωj+m=−ωj\omega^{j+m} = -\omega^j, Xj+m=Ej−ωjOjX_{j+m} = E_j - \omega^j O_j for 0≤j<m0 \le j < m. This is the matrix formula.

∎

Applying the factorization recursively, Fn\mat{F}_n is the product of log⁡2n\log_2 n factors with two nonzero entries per row, plus a permutation. This factors a dense matrix with n2n^2 entries into matrices with 2nlog⁡2n2n\log_2 n nonzero entries in total, so multiplication costs O(nlog⁡n)\bigO(n\log n): if T(n)T(n) is the cost, T(n)=2 T(n/2)+O(n)T(n) = 2\,T(n/2) + \bigO(n), whose solution is O(nlog⁡n)\bigO(n\log n). This is the first example of an idea that will recur in butterflies and Monarch: structure = product of a few sparse matrices.

Circulants: diagonalizing circular convolution

Turn to periodic signals. Imagine signal x\vb{x} repeats cyclically (index kk is taken modulo nn), as does the kernel of equal length. Circular convolution has no edges.

The product Cx\mat{C}\vb{x} is (Cx)j=∑lcl x(j−l) mod n(\mat{C}\vb{x})_j = \sum_l c_l\,x_{(j-l) \bmod n}, the circular convolution c⊛x\vb{c} \circledast \vb{x}. To understand circulants, look at the simplest one. Let S\mat{S} be the shift matrix, the circulant with first column e1\vb{e}_1: (Sx)k=x(k−1) mod n(\mat{S}\vb{x})_k = x_{(k-1) \bmod n}. Shifting ll times gives Sl\mat{S}^l, the circulant with first column el\vb{e}_l, and Sn=I\mat{S}^n = \mat{I}. Then

C=∑l=0n−1cl Sl.\mat{C} = \sum_{l=0}^{n-1} c_l\,\mat{S}^l.

Every circulant is a polynomial in S\mat{S}. Two facts follow at once: circulants all commute, and any eigenvector basis of S\mat{S} is simultaneously one for all of them. The eigenvectors of S\mat{S} are already familiar. Shifting a pure wave does not deform it, only shifts its phase:

(Swm)k=(wm)k−1=e2πi m(k−1)/n=e−2πi m/n (wm)k=ωm (wm)k.(\mat{S}\vb{w}_m)_k = (\vb{w}_m)_{k-1} = e^{2\pi i\,m(k-1)/n} = e^{-2\pi i\,m/n}\,(\vb{w}_m)_k = \omega^m\,(\vb{w}_m)_k.
Proof

By the formula for C\mat{C} as a polynomial in S\mat{S}: Cwm=∑lcl Slwm=∑lcl ωml wm=(Fc)m wm\mat{C}\vb{w}_m = \sum_l c_l\,\mat{S}^l\vb{w}_m = \sum_l c_l\,\omega^{ml}\,\vb{w}_m = (\mat{F}\vb{c})_m\,\vb{w}_m. The columns of U∗\mat{U}^* are the normalized waves wm/n\vb{w}_m/\sqrt n, an orthonormal basis, so if Λ=diag⁡(λ0,…,λn−1)\mat{\Lambda} = \diag(\lambda_0, \dots, \lambda_{n-1}), the preceding equality says CU∗=U∗Λ\mat{C}\mat{U}^* = \mat{U}^*\mat{\Lambda}, that is, C=U∗ΛU\mat{C} = \mat{U}^*\mat{\Lambda}\mat{U}. Since Λ\mat{\Lambda} and Λ∗\mat{\Lambda}^* are diagonal and commute, CC∗=U∗ΛΛ∗U=C∗C\mat{C}\mat{C}^* = \mat{U}^*\mat{\Lambda}\mat{\Lambda}^*\mat{U} = \mat{C}^*\mat{C}.

∎

That is the complete picture. The figure makes it tangible: the matrix is generated by an editable vector c\vb{c}; choose a wave and the output is the same wave with amplitude multiplied by ∣λm∣\abs{\lambda_m} and phase shift arg⁡λm\arg\lambda_m; when you choose a vector that is not a Fourier wave, its shape does change.

InteractiveFourier waves are not deformed
Circulant matrix C\mat{C} (each column shifts the previous one)
01234567012345671.00.30.60.61.00.30.30.61.00.30.61.00.30.61.00.30.61.00.30.61.00.30.61.0
Eigenvalues λ0,…,λ7\lambda_0, \dots, \lambda_7 in the complex plane (select one)
01234567
Input wm\vb{w}_m: real part of eiφwme^{i\varphi}\vb{w}_m (frequency-mm wave rotating in phase)
01234567
Output Cx\mat{C}\vb{x}. Hollow circles predict “input times a scalar”; the dashed blue line is the input
01234567
C w1=(1.42−0.72 i)⏟λ1 w1\mat{C}\,\vb{w}_{1} = \underbrace{(1.42 - 0.72\,i)}_{\lambda_{1}}\,\vb{w}_{1}
  • input
  • output Cx\mat{C}\vb{x}
  • selected eigenvalue
Edit c (drag bars)
01234567
1
Input
λm=DFT(c)m\lambda_m = \mathrm{DFT}(\vb{c})_m1.42 − 0.72i
∣λm∣\abs{\lambda_m} (amplitude change)1.598
arg⁡λm\arg\lambda_m (phase shift)−27.0°
Deviation from an input multiple0.0 %
The output is the same wave: amplitude ×∣λm∣\times\abs{\lambda_m} and phase shift arg⁡λm\arg\lambda_m. It is an eigenvector of C\mat{C}.
An 8×88\times 8 circulant with first column c\vb{c} (drag its bars). Choose frequency mm with the slider or by clicking an eigenvalue in the complex plane: below, input wm\vb{w}_m and output Cwm\mat{C}\vb{w}_m are the same wave, with amplitude ∣λm∣\abs{\lambda_m} and phase shifted by arg⁡λm\arg\lambda_m; hollow circles show prediction λmwm\lambda_m\vb{w}_m and coincide. Change input to a pulse or random vector: the deviation from a multiple of the input is no longer zero. Try delay (what magnitude do all eigenvalues have?), difference (which wave disappears?) and symmetric averaging (why are eigenvalues real?). Since c\vb{c} is real, eigenvalues appear in conjugate pairs λn−m=λm‾\lambda_{n-m} = \overline{\lambda_m}.

Each figure preset illustrates a reading of the theorem. Delay (circulant S2\mat{S}^2) has λm=ω2m\lambda_m = \omega^{2m}, all magnitude 1: only phase changes, and eigenvalues trace the unit circle (unitary by the earlier theorem). Symmetric averaging is a symmetric circulant, hence Hermitian, so its eigenvalues are real. Difference c=(1,−1,0,… )\vb{c} = (1, -1, 0, \dots) has λm=1−ωm\lambda_m = 1 - \omega^m, with λ0=0\lambda_0 = 0: the constant wave w0\vb{w}_0 lies in its null space, and the fastest wave, m=n/2m = n/2, is amplified by 22. It is a high-pass filter. With n=4n = 4:

C=[100−1−11000−11000−11],λ=(0, 1+i, 2, 1−i).\mat{C} = \begin{bmatrix} 1 & 0 & 0 & -1 \\ -1 & 1 & 0 & 0 \\ 0 & -1 & 1 & 0 \\ 0 & 0 & -1 & 1 \end{bmatrix}, \qquad \lambda = (0,\ 1 + i,\ 2,\ 1 - i).

Consequences

Once C=U∗ΛU\mat{C} = \mat{U}^*\mat{\Lambda}\mat{U} is known, every question about circulants reduces to one about numbers.

  • Product. CaCb=U∗ΛaΛbU\mat{C}_a\mat{C}_b = \mat{U}^*\mat{\Lambda}_a\mat{\Lambda}_b\mat{U} is circulant, with eigenvalues λm(a)λm(b)\lambda^{(a)}_m\lambda^{(b)}_m; they commute. Circulants form a commutative algebra isomorphic to Cn\C^n with elementwise product.
  • Inverse and determinant. C\mat{C} is invertible if and only if no λm\lambda_m is zero; then C−1\mat{C}\inv is circulant with eigenvalues 1/λm1/\lambda_m. Also det⁡C=∏mλm\det\mat{C} = \prod_m \lambda_m.
  • Convolution theorem. Cx=U∗ΛUx\mat{C}\vb{x} = \mat{U}^*\mat{\Lambda}\mat{U}\vb{x} is written F(c⊛x)=(Fc)⊙(Fx)\mat{F}(\vb{c} \circledast \vb{x}) = (\mat{F}\vb{c}) \odot (\mat{F}\vb{x}), with ⊙\odot the elementwise product. Circular convolution becomes a product. This is the discrete analogue of the continuous convolution theorem; a direct proof without diagonalization is the guided derivation in the exercises.
  • Cost. Computing Cx\mat{C}\vb{x} as F−1((Fc)⊙(Fx))\mat{F}\inv\big((\mat{F}\vb{c}) \odot (\mat{F}\vb{x})\big) takes three FFTs and nn products: O(nlog⁡n)\bigO(n \log n) instead of O(n2)\bigO(n^2). Solving Cy=b\mat{C}\vb{y} = \vb{b} is the same with division instead of multiplication, also O(nlog⁡n)\bigO(n\log n).

From circular to linear convolution

Circular and linear convolution do not coincide. With h=(1,2,3)\vb{h} = (1, 2, 3) and x=(4,5,6,7,8)\vb{x} = (4, 5, 6, 7, 8), the linear convolution is (4,13,28,34,40,37,24)(4, 13, 28, 34, 40, 37, 24), of length n+m−1=7n + m - 1 = 7. Circular convolution of length 5 is (41,37,28,34,40)(41, 37, 28, 34, 40): the last two values, 3737 and 2424, wrapped onto the first two (4+37=414 + 37 = 41 and 13+24=3713 + 24 = 37). The linear output does not fit in nn positions, and circular convolution folds it.

Proof

In yj=∑kh(j−k) mod N xky_j = \sum_k h_{(j-k) \bmod N}\,x_k only k≤n−1k \le n - 1 count. If j−k≥0j - k \ge 0 the index is j−kj - k and gives the linear term. If j−k<0j - k < 0, the index is N+(j−k)≥N−(n−1)≥mN + (j - k) \ge N - (n - 1) \ge m, outside the support of h\vb{h} (zero-padded): the term is zero. There is no wraparound.

∎

In practice NN is chosen for a fast FFT: a power of 2 above n+m−1n + m - 1 for the Cooley–Tukey radix-2 FFT, or a product of powers of 2, 3 and 5, as chosen by scipy.signal.fftconvolve (with scipy.fft.next_fast_len).

Toeplitz inside a circulant

An arbitrary Toeplitz matrix is not circulant, but can be embedded in one. Let T∈Cn×n\mat{T} \in \C^{n\times n} with Tjk=tj−kT_{jk} = t_{j-k} (j−kj - k between −(n−1)-(n-1) and n−1n-1), and let C\mat{C} be the 2n×2n2n \times 2n circulant with first column

c=(t0,t1,…,tn−1, 0, t−(n−1),…,t−2,t−1).\vb{c} = (t_0, t_1, \dots, t_{n-1},\ 0,\ t_{-(n-1)}, \dots, t_{-2}, t_{-1}).

The upper-left n×nn \times n block of C\mat{C} is T\mat{T}: if j−k≥0j - k \ge 0 the entry is cj−k=tj−kc_{j-k} = t_{j-k}, and if j−k=−d<0j - k = -d < 0 the index is 2n−d2n - d, where t−dt_{-d} sits. Therefore

Tx=las n primeras entradas de C[x0],\mat{T}\vb{x} = \text{las } n \text{ primeras entradas de } \mat{C}\begin{bmatrix} \vb{x} \\ \vb{0} \end{bmatrix},

and a Toeplitz product costs three FFTs of size 2n2n, O(nlog⁡n)\bigO(n\log n), and O(n)\bigO(n) memory, without ever forming the matrix. You will implement this algorithm in the code exercise. The connection is deep: eigenvalues of large Toeplitz matrices behave asymptotically like those of a circulant, with the DFT of sequence tdt_d (its symbol) playing the role of eigenvalues; this is Szegő theory summarized by Gray (2006).

Block rotations and RoPE

Multiplication by a complex number eiφe^{i\varphi} is a rotation: identify z=a+ibz = a + ib with vector (a,b)(a, b) and the product with rotation matrix R(φ)\mat{R}(\varphi) (Euler’s formula). A plane rotation satisfies R(α)⊤R(β)=R(β−α)\mat{R}(\alpha)\T\mat{R}(\beta) = \mat{R}(\beta - \alpha): rotating α\alpha backward and β\beta forward is a rotation by β−α\beta - \alpha.

Let dd be even and take a list of frequencies θ1,…,θd/2\theta_1, \dots, \theta_{d/2}. The position rotation mm is the block diagonal matrix

Rm=diag⁡(R(mθ1), R(mθ2), …, R(mθd/2))∈Rd×d,\mat{R}_m = \diag\big(\mat{R}(m\theta_1),\ \mat{R}(m\theta_2),\ \dots,\ \mat{R}(m\theta_{d/2})\big) \in \R^{d\times d},

one plane per frequency, each rotated by an angle proportional to position. It is orthogonal and, by the above, Rm⊤Rn=Rn−m\mat{R}_m\T\mat{R}_n = \mat{R}_{n-m}. Identifying Rd\R^d with Cd/2\C^{d/2}, Rm\mat{R}_m is the diagonal unitary matrix diag⁡(eimθ1,…,eimθd/2)\diag(e^{im\theta_1}, \dots, e^{im\theta_{d/2}}): complex exponentials again.

RoPE (rotary position embedding, Su et al., 2021) applies this idea to attention: the query at position mm and key at position nn are rotated, qm=Rmq\vb{q}_m = \mat{R}_m\vb{q} and kn=Rnk\vb{k}_n = \mat{R}_n\vb{k}, with geometrically decreasing frequencies θp=10000−2(p−1)/d\theta_p = 10000^{-2(p-1)/d}. Their score is

qm⊤kn=q⊤Rm⊤Rnk=q⊤Rn−m k.\vb{q}_m\T\vb{k}_n = \vb{q}\T\mat{R}_m\T\mat{R}_n\vb{k} = \vb{q}\T\mat{R}_{n-m}\,\vb{k}.

Positions appear only through n−mn - m. In complex notation, qm⊤kn=Re⁡∑pqp‾ kp ei(n−m)θp\vb{q}_m\T\vb{k}_n = \operatorname{Re}\sum_p \overline{q_p}\,k_p\,e^{i(n-m)\theta_p}, a sum of cosines of distance: td=∑p∣qp∣∣kp∣cos⁡(d θp+φp)t_d = \sum_p \abs{q_p}\abs{k_p}\cos(d\,\theta_p + \varphi_p) with φp=arg⁡kp−arg⁡qp\varphi_p = \arg k_p - \arg q_p.

InteractiveRotations that see only distance
Plane 1: rotates 0.800.80 rad per position, δ1=166.5°\delta_1 = 166.5°
Plane 2: rotates 0.200.20 rad per position, δ2=−38.8°\delta_2 = −38.8°
Scores between positions: row mm, column nn. Each diagonal is constant (Toeplitz matrix; blue positive, orange negative)
0123456789101101234567891011
Score as a function of distance d=n−md = n - m (first Toeplitz row and column)
−8−4048
With q\vb{q} and k\vb{k} fixed at every position, only the angle changes: dθpd\theta_p plus a constant.
  • query qm=Rmq\vb{q}_m = \mat{R}_m\vb{q}
  • key kn=Rnk\vb{k}_n = \mat{R}_n\vb{k}
  • angle δp\delta_p between them
  • current position
2
5
0
0.80
0.20
Positions (m,n)(m, n) and distance n−mn - m(2, 5), 3
Score qm⊤kn\vb{q}_m\T\vb{k}_n−0.533
Plane 1 + plane 2 contributions−1.87 + 1.34
Unshifted score (2,5)(2, 5)−0.533
Same n−mn - m, same score: Rm⊤Rn=Rn−m\mat{R}_m\T\mat{R}_n = \mat{R}_{n-m}.
A four-dimensional vector split into two planes, rotating θ1\theta_1 and θ2\theta_2 radians per position. In each plane, qm\vb{q}_m (blue) and kn\vb{k}_n (red): drag their tips to change content, and move mm and nn to rotate them. The arc is the angle δp\delta_p between them. Now use ‘Shift both at once’ (or automatic shifting): both arrows rotate without changing the angle between them, and the score stays fixed. Below, the score matrix between all positions has constant diagonals (it is Toeplitz), and the score depends only on d=n−md = n - m. Change θ1\theta_1 and θ2\theta_2: fast planes distinguish short distances, slow planes long ones. In the real model θ1=1\theta_1 = 1 and subsequent values decrease to almost 10−410^{-4}; here they are closer together so they can be seen.

Two qualifications about what this does and does not say. If q\vb{q} and k\vb{k} were the same at every position, score matrix Smn=q⊤Rn−mkS_{mn} = \vb{q}\T\mat{R}_{n-m}\vb{k} would be exactly Toeplitz, as in the figure. In real attention q\vb{q} and k\vb{k} come from projections of each token’s content and vary with position, so what is preserved is the positional part: smn=(Wqxm)⊤Rn−m(Wkxn)s_{mn} = (\mat{W}_q\vb{x}_m)\T\mat{R}_{n-m}(\mat{W}_k\vb{x}_n). Content and distance enter separately, with distance entering through a familiar structure. The mechanism, effects of frequencies and context extension methods are covered in the RoPE lesson; here only the algebra matters: block rotations = complex exponentials = the same structure as convolutions.

Other structures: semiseparable matrices, butterflies and Monarch

Current efficient models use more than Toeplitz and circulants. A definition helps organize the landscape.

FamilyParametersProduct Mx\mat{M}\vb{x}Idea
Densen2n^2O(n2)\bigO(n^2)no structure
Rank rr (low rank)2nr2nrO(nr)\bigO(nr)UV⊤\mat{U}\mat{V}\T with rr columns
CirculantnnO(nlog⁡n)\bigO(n\log n)diagonal in the Fourier basis
Toeplitz2n−12n - 1O(nlog⁡n)\bigO(n\log n)embedded in a circulant
Semiseparable of order NNO(nN)\bigO(nN)O(nN)\bigO(nN)submatrices of rank ≤N\le N
ButterflyO(nlog⁡n)\bigO(n\log n)O(nlog⁡n)\bigO(n\log n)product of log⁡2n\log_2 n sparse factors
MonarchO(nn)\bigO(n\sqrt n)O(nn)\bigO(n\sqrt n)two block diagonal factors and a permutation

Semiseparable matrices and state-space models

A linear state-space model processes a sequence x0,…,xT−1x_0, \dots, x_{T-1} with a recurrence st=Ast−1+b xt\vb{s}_t = \mat{A}\vb{s}_{t-1} + \vb{b}\,x_t, yt=c⊤sty_t = \vb{c}\T\vb{s}_t, where st∈RN\vb{s}_t \in \R^N is the state. Unrolling it gives yt=∑s≤tc⊤At−sb  xsy_t = \sum_{s \le t} \vb{c}\T\mat{A}^{t-s}\vb{b}\;x_s: multiplication by lower triangular matrix M\mat{M} with entries Mts=c⊤At−sbM_{ts} = \vb{c}\T\mat{A}^{t-s}\vb{b}. That matrix is Toeplitz (it depends only on t−st - s), giving two algorithms for the same product: the sequential recurrence in O(TN)\bigO(TN) with A\mat{A} diagonal as in practice (O(TN2)\bigO(TN^2) with dense A\mat{A}); or causal convolution with kernel Kl=c⊤AlbK_l = \vb{c}\T\mat{A}^l\vb{b} computed by FFT in O(Tlog⁡T)\bigO(T\log T) and in parallel. This is recurrence-convolution duality (m18) and why long-convolution models use the FFT.

But M\mat{M} has more structure than being Toeplitz. Every submatrix in the lower triangular part (including the diagonal) has rank at most NN: for s≤i≤ts \le i \le t, Mts=(c⊤At−i)(Ai−sb)M_{ts} = (\vb{c}\T\mat{A}^{t-i})(\mat{A}^{i-s}\vb{b}) factors through the state at time ii, which lives in RN\R^N. This is semiseparable of order NN.

If parameters depend on the input, At,bt,ct\mat{A}_t, \vb{b}_t, \vb{c}_t (selective models such as Mamba, m18), then Mts=ct⊤At⋯As+1bsM_{ts} = \vb{c}_t\T\mat{A}_t\cdots\mat{A}_{s+1}\vb{b}_s remains semiseparable and is multiplied by a scan in O(TN)\bigO(TN), but it is no longer Toeplitz and the FFT does not apply. Dao and Gu (2024) show that when At=atI\mat{A}_t = a_t\mat{I}, the matrix is M=L∘(CB⊤)\mat{M} = \mat{L} \circ (\mat{C}\mat{B}\T) with L\mat{L} a rank-1 semiseparable mask (entries as+1⋯ata_{s+1}\cdots a_t), the form of masked causal attention. This is state-space/attention duality (m18); here the point is that both are structured matrices with two different product algorithms.

[ ]Semiseparable matrices, Toeplitz and MonarchBrowser
import numpy as np

rng = np.random.default_rng(0)
T, N = 12, 2

# 1) Espacio de estados invariante en el tiempo: M[t, s] = c^T A^(t-s) b
A = np.diag(rng.uniform(0.5, 0.95, N)); b = rng.normal(size=N); c = rng.normal(size=N)
M = np.array([[c @ np.linalg.matrix_power(A, t - s) @ b if s <= t else 0.0 for s in range(T)] for t in range(T)])
x = rng.normal(size=T)
s, y = np.zeros(N), np.zeros(T)
for t in range(T):                                   # recurrencia: O(T N), secuencial
    s = A @ s + b * x[t]
    y[t] = c @ s
rango = lambda M: max(np.linalg.matrix_rank(M[i:, :i + 1]) for i in range(len(M)))   # bloques bajo la diagonal
es_toeplitz = lambda M: all(np.allclose(np.diag(M, -d), M[d, 0]) for d in range(len(M)))
print("recurrencia = producto por M:", np.allclose(M @ x, y), "| rango máximo:", rango(M), "(N =", N, ") | Toeplitz:", es_toeplitz(M))

# 2) Selectivo: los parámetros cambian con t (a_t escalar, b_t y c_t vectores de R^N)
a = rng.uniform(0.5, 0.99, T); B = rng.normal(size=(T, N)); C = rng.normal(size=(T, N))
s, y2 = np.zeros(N), np.zeros(T)
for t in range(T):
    s = a[t] * s + B[t] * x[t]
    y2[t] = C[t] @ s
L = np.array([[np.prod(a[i + 1:t + 1]) if i <= t else 0.0 for i in range(T)] for t in range(T)])
M2 = L * (C @ B.T)                                   # máscara semiseparable ∘ (C B^T)
print("selectivo: recurrencia = L ∘ (C Bᵀ):", np.allclose(M2 @ x, y2), "| rango máximo:", rango(M2), "| Toeplitz:", es_toeplitz(M2))

# 3) La DFT de orden 16 es una matriz Monarch (salvo una permutación)
m = 4; n = m * m
k = np.arange(n)
F = np.exp(-2j * np.pi * np.outer(k, k) / n)
Fm = np.exp(-2j * np.pi * np.outer(np.arange(m), np.arange(m)) / m)
P = np.eye(n)[np.arange(n).reshape(m, m).T.ravel()]  # permutación «trasponer la cuadrícula m x m»
w = np.exp(-2j * np.pi / n)
Tw = np.diag([w ** (j1 * k2) for j1 in range(m) for k2 in range(m)])      # factores de giro (diagonal)
Lb = np.kron(np.eye(m), Fm)                          # m bloques de F_m
Rb = Tw @ Lb                                         # también diagonal por bloques
print("F_16 P = P L P R con L, R diagonales por bloques:", np.allclose(F @ P, P @ Lb @ P @ Rb))
for n_ in (256, 4096, 65536):
    print(f"n = {n_:6d}: densa {n_**2:>13,d}   Monarch {2 * n_ * int(n_**0.5):>12,d}   cociente {n_ / (2 * int(n_**0.5)):.0f}")

Butterflies and Monarch

The Cooley–Tukey factorization suggests a matrix family. A butterfly is a product of log⁡2n\log_2 n factors, each with two nonzero entries per row in a fixed pattern: the FFT is a butterfly with certain values in those entries. If instead of fixing them they are learned, the result is a family with O(nlog⁡n)\bigO(n\log n) parameters including the DFT, Hadamard transform and many more, multiplied in O(nlog⁡n)\bigO(n\log n). Butterflies are very expressive, but their sparse factors may use modern hardware poorly, which favors dense block multiplication.

Monarch (Dao et al., 2022) replaces the log⁡2n\log_2 n sparse factors with two block diagonal factors hardware multiplies efficiently. With n=m2n = m^2,

M=P L P R,\mat{M} = \mat{P}\,\mat{L}\,\mat{P}\,\mat{R},

where L\mat{L} and R\mat{R} are block diagonal with mm dense blocks of size m×mm\times m each, and P\mat{P} is the permutation transposing an m×mm \times m grid (the vector is reshaped as an m×mm \times m matrix and transposed). It has 2m3=2nn2m^3 = 2n\sqrt n parameters and multiplies in O(nn)\bigO(n\sqrt n), two batched small-matrix multiplications. For n=4096n = 4096, 2nn=524 2882n\sqrt n = 524\,288 versus n2=16 777 216n^2 = 16\,777\,216: 32 times fewer. The code above verifies that the order-m2m^2 DFT is, up to a column permutation, a Monarch matrix: Fm2P=P (Im⊗Fm) P D (Im⊗Fm)\mat{F}_{m^2}\mat{P} = \mat{P}\,(\mat{I}_m \otimes \mat{F}_m)\,\mat{P}\,\mat{D}\,(\mat{I}_m \otimes \mat{F}_m), with D\mat{D} the diagonal of twiddle factors. This is the Cooley–Tukey factorization with n=m⋅mn = m \cdot m instead of 2⋅(n/2)2 \cdot (n/2).

Implementation from scratch

First, Toeplitz and circulant matrices without libraries, and verification that convolution is multiplication by one. With the previous signal, see how the circulant folds what the Toeplitz leaves intact.

[ ]Toeplitz and circulants from scratchBrowser
import numpy as np

def toeplitz(c, r):
    """Matriz de Toeplitz con primera columna c y primera fila r (la diagonal es c[0])."""
    c, r = np.asarray(c), np.asarray(r)
    j, k = np.indices((len(c), len(r)))
    d = j - k
    return np.where(d >= 0, c[np.clip(d, 0, len(c) - 1)], r[np.clip(-d, 0, len(r) - 1)])

def circulant(c):
    """Circulante con primera columna c: C[j, k] = c[(j - k) mod n]."""
    c = np.asarray(c)
    j, k = np.indices((len(c), len(c)))
    return c[(j - k) % len(c)]

h = np.array([1.0, 2.0, 3.0])
x = np.array([4.0, 5.0, 6.0, 7.0, 8.0])
n, m = len(x), len(h)

T = toeplitz(np.r_[h, np.zeros(n - 1)], np.zeros(n))     # (n + m - 1) x n
print(T.astype(int))
print("T @ x     =", T @ x)
print("np.convolve =", np.convolve(h, x))

C = circulant(np.r_[h, np.zeros(n - m)])                 # n x n, el núcleo rellenado con ceros
y = np.convolve(h, x)
plegada = y[:n].copy()
plegada[:len(y) - n] += y[n:]                            # lo que sobra se envuelve sobre el principio
print("\ncirculante @ x =", C @ x, "  convolución lineal plegada =", plegada)

In two dimensions, separable kernel ab⊤\vb{a}\vb{b}\T gives a convolution that is the Kronecker product of two Toeplitz matrices. The convention is ravel (rowwise): TaXTb⊤\mat{T}_a\mat{X}\mat{T}_b\T corresponds to (Ta⊗Tb) vec(X)(\mat{T}_a \otimes \mat{T}_b)\,\mathrm{vec}(\mat{X}).

[ ]2D convolution = Kronecker product of two Toeplitz matricesBrowser
def convolve2d_directa(X, K):
    """Convolución 2D completa: cada entrada del núcleo suma una copia desplazada de la imagen."""
    out = np.zeros((X.shape[0] + K.shape[0] - 1, X.shape[1] + K.shape[1] - 1))
    for i in range(K.shape[0]):
        for j in range(K.shape[1]):
            out[i:i + X.shape[0], j:j + X.shape[1]] += K[i, j] * X
    return out

rng = np.random.default_rng(0)
a, b = np.array([1.0, 2.0, 1.0]), np.array([1.0, 0.0, -1.0])      # núcleo de Sobel: a b^T
X = rng.normal(size=(4, 5))
Ta = toeplitz(np.r_[a, np.zeros(X.shape[0] - 1)], np.zeros(X.shape[0]))
Tb = toeplitz(np.r_[b, np.zeros(X.shape[1] - 1)], np.zeros(X.shape[1]))
G = np.kron(Ta, Tb)
print("forma de la matriz:", G.shape, "para una imagen de", X.shape, "y un núcleo de 3 x 3")
print("(Ta ⊗ Tb) vec(X) = convolución 2D directa:", np.allclose(G @ X.ravel(), convolve2d_directa(X, np.outer(a, b)).ravel()))

Now the DFT. Construct F\mat{F} from its definition; check that it is unitary up to scale, symmetric, agrees with np.fft.fft and diagonalizes a random circulant with eigenvalues fft(c).

[ ]The DFT matrixBrowser
n = 8
k = np.arange(n)
F = np.exp(-2j * np.pi * np.outer(k, k) / n)
x8 = rng.normal(size=n)
print("F* F = n I:", np.allclose(F.conj().T @ F, n * np.eye(n)),
      "| F simétrica:", np.allclose(F, F.T),
      "| F x = fft(x):", np.allclose(F @ x8, np.fft.fft(x8)))
print("Parseval:", np.linalg.norm(F @ x8) ** 2, "=", n * np.linalg.norm(x8) ** 2)

c = rng.normal(size=n)
Cc = circulant(c)
lam = F @ c                                              # autovalores teóricos: la DFT de c
D = F @ Cc @ F.conj().T / n                              # U C U* con U = F / sqrt(n), multiplicado por n/n
print("fuera de la diagonal:", np.abs(D - np.diag(np.diag(D))).max(), "| diagonal = fft(c):", np.allclose(np.diag(D), lam))
w = np.linalg.eigvals(Cc)
print("distancia de cada fft(c)[m] al autovalor más cercano:", max(np.abs(w - l).min() for l in lam))
print("C x = ifft(fft(c) * fft(x)):", np.allclose(Cc @ x8, np.fft.ifft(lam * np.fft.fft(x8)).real))

Next is the FFT. A recursive radix-2 implementation follows the theorem’s factorization. To keep pure Python call overhead from dominating, small subproblems (up to 32 points) use the DFT matrix. We also verify the matrix factorization for n=8n = 8 and count nonzero entries.

[ ]Recursive radix-2 FFTBrowser
_F = {}
def dft_matrix(n):
    if n not in _F:
        k = np.arange(n)
        _F[n] = np.exp(-2j * np.pi * np.outer(k, k) / n)
    return _F[n]

def fft_rec(x, base=32):
    """FFT de Cooley y Tukey: X = [E + D O ; E - D O], con E, O las FFT de las muestras pares e impares."""
    x = np.asarray(x, dtype=complex)
    n = len(x)
    if n <= base:
        return dft_matrix(n) @ x
    par, impar = fft_rec(x[0::2], base), fft_rec(x[1::2], base)
    giro = np.exp(-2j * np.pi * np.arange(n // 2) / n) * impar
    return np.concatenate([par + giro, par - giro])

z = rng.normal(size=1024)
print("fft_rec = np.fft.fft:", np.allclose(fft_rec(z), np.fft.fft(z)))

# la factorización del teorema, con n = 8
n, m = 8, 4
Dm = np.diag(np.exp(-2j * np.pi * np.arange(m) / n))
I, Z = np.eye(m), np.zeros((m, m))
B = np.block([[I, Dm], [I, -Dm]])                        # la «mariposa»
P = np.eye(n)[np.r_[0:n:2, 1:n:2]]                       # pares primero, impares después
F8 = dft_matrix(8)
print("F_8 = B diag(F_4, F_4) P:", np.allclose(F8, B @ np.block([[dft_matrix(m), Z], [Z, dft_matrix(m)]]) @ P),
      "| entradas no nulas de B:", np.count_nonzero(B), "de", n * n)

Using our FFT and NumPy’s, measure when FFT convolution beats direct convolution. The FFT does more constant work per operation: three power-of-two transforms above 2n2n, versus n2n^2 simple multiplications and additions for the direct method. The crossover depends on implementation.

[ ]Direct versus FFT convolutionBrowser
import time

def bench(f, tmin=0.01):
    """Segundos por llamada: dobla las repeticiones hasta acumular tmin segundos (el reloj de Pyodide es grueso)."""
    reps = 1
    while True:
        t0 = time.perf_counter()
        for _ in range(reps):
            f()
        t = time.perf_counter() - t0
        if t >= tmin:
            return t / reps
        reps *= 2

def conv_fft_propia(h, x):
    L = len(h) + len(x) - 1
    N = 1 << (L - 1).bit_length()                        # potencia de 2 >= n + m - 1
    H, X = fft_rec(np.pad(h, (0, N - len(h)))), fft_rec(np.pad(x, (0, N - len(x))))
    return np.conj(fft_rec(np.conj(H * X))).real[:L] / N  # la inversa: conjugar, FFT y conjugar

a, b = rng.normal(size=1000), rng.normal(size=300)
print("FFT propia = convolución directa:", np.allclose(conv_fft_propia(a, b), np.convolve(a, b)))

tiempos = []
for e in range(4, 17, 2):
    n = 2 ** e
    a, b = rng.normal(size=n), rng.normal(size=n)
    t_dir = bench(lambda: np.convolve(a, b)) if e <= 14 else np.nan             # a 2^16 serían 4.3e9 operaciones
    t_own = bench(lambda: conv_fft_propia(a, b)) if e <= 14 else np.nan
    t_np = bench(lambda: np.fft.irfft(np.fft.rfft(a, 2 * n) * np.fft.rfft(b, 2 * n), 2 * n))
    tiempos.append((n, t_dir, t_own, t_np))
    print(f"n = 2^{e:<2d}  directa {t_dir*1e3:9.3f} ms   FFT propia {t_own*1e3:9.3f} ms   np.fft {t_np*1e3:8.3f} ms")

import matplotlib.pyplot as plt
ns, td, to, tf = map(np.array, zip(*tiempos))
plt.loglog(ns, td * 1e3, "o-", label="directa, O(n²)")
plt.loglog(ns, to * 1e3, "s-", label="FFT propia, O(n log n)")
plt.loglog(ns, tf * 1e3, "^-", label="np.fft")
plt.xlabel("longitud n de cada señal"); plt.ylabel("milisegundos"); plt.legend(); plt.show()

The log-log plot tells the story: direct is a straight line of slope 2 and both FFTs nearly straight lines of slope 1. (Direct and our FFT are measured up to 2142^{14}; at 2162^{16} they would take seconds in the browser, while np.fft reaches 2162^{16} in milliseconds.) The FFT written in Python carries a huge constant from interpreter recursion: in our Pyodide tests it is still slightly behind direct at 2122^{12} and clearly ahead at 2142^{14}, as the slopes predict; np.fft, written in C, catches it around 282^{8}. And np.convolve uses a very tight loop underneath: the crossover depends on both implementations. The slope does not, so with 10510^5 or 10610^6 samples there is no contest.

Long causal convolution

Long-convolution models (Hyena, S4) have a filter as long as the sequence, m=Tm = T, and causal: yt=∑s≤tht−s xsy_t = \sum_{s \le t} h_{t-s}\,x_s. This is multiplication by lower triangular Toeplitz T×TT \times T. With the FFT, causality comes from zero-padding to N≥2T−1N \ge 2T - 1 and keeping the first TT outputs; without padding the result’s tail wraps onto the beginning and breaks causality.

[ ]A long causal convolutionBrowser
def causal_directa(h, x):
    """y_t = sum_{s<=t} h[t-s] x[s], O(T^2), para comprobar."""
    return np.array([h[:t + 1][::-1] @ x[:t + 1] for t in range(len(x))])

def causal_fft(h, x, relleno=True):
    T = len(x)
    N = 1 << (2 * T - 1).bit_length() if relleno else T          # N >= 2T - 1: sin envoltura
    return np.fft.irfft(np.fft.rfft(h, N) * np.fft.rfft(x, N), N)[:T]

T = 1000
h = rng.normal(size=T) * 0.99 ** np.arange(T)                    # un filtro largo que decae despacio
x = rng.normal(size=T)
yd = causal_directa(h, x)
print("con relleno N >= 2T - 1: error máximo", np.abs(causal_fft(h, x) - yd).max())
print("sin relleno (circular):  error máximo", np.abs(causal_fft(h, x, relleno=False) - yd).max())

res = []
for T in [2 ** e for e in range(4, 14)]:
    h, x = rng.normal(size=T), rng.normal(size=T)
    t_dir = bench(lambda: np.convolve(h, x)[:T])
    t_fft = bench(lambda: causal_fft(h, x))
    res.append((T, t_dir, t_fft))
    print(f"T = {T:5d}   directa {t_dir*1e3:8.3f} ms   FFT {t_fft*1e3:8.3f} ms   gana {'la FFT' if t_fft < t_dir else 'la directa'}")
cruce = next((T for T, a_, b_ in res if b_ < a_), None)
print("primer T en que gana la FFT:", cruce)

Causality is subtle: circular convolution of length TT computes y0y_0 using contributions from xT−1x_{T-1}, the future, violating causality in a language model. Padding removes that bug and also makes linear convolution correct. In our tests, both in Pyodide and native NumPy, FFT begins to win between T=256T = 256 and T=512T = 512; the exact value depends on the machine, cache size and NumPy compilation, and the cell measures it in the execution environment.

Finally, multiplication by a Toeplitz matrix using circulant embedding uses the same mechanism. For n=30 000n = 30\,000, the dense matrix would occupy 7.2 GB in float64; here it is never formed.

[ ]Toeplitz by circulant embeddingBrowser
def toeplitz_matvec(c, r, x):
    """T x en O(n log n), con T Toeplitz n x n de primera columna c y primera fila r (c[0] = r[0])."""
    n = len(x)
    col = np.concatenate([c, [0.0], r[:0:-1]])                   # primera columna de la circulante 2n x 2n
    y = np.fft.ifft(np.fft.fft(col) * np.fft.fft(x, 2 * n))      # x se rellena con ceros hasta 2n
    return y[:n].real

n = 7
c, r, x = rng.normal(size=n), rng.normal(size=n), rng.normal(size=n)
r[0] = c[0]
print("n = 7, frente a la matriz densa:", np.allclose(toeplitz_matvec(c, r, x), toeplitz(c, r) @ x))

n = 30000
c, r, x = rng.normal(size=n), rng.normal(size=n), rng.normal(size=n)
r[0] = c[0]
t0 = time.perf_counter(); y = toeplitz_matvec(c, r, x); dt = time.perf_counter() - t0
j = 12345
fila = np.r_[c[j:0:-1], r[:n - j]]                               # la fila j de T, sin formar la matriz
print(f"n = {n}: y[{j}] por producto escalar = {fila @ x:.8f}   por FFT = {y[j]:.8f}   ({dt * 1e3:.0f} ms)")

The professional version

FunctionWhat it doesWhen to use it
np.fft.fft, ifftDFT with sign −- and inverse scale 1/n1/ncomplex signals
np.fft.rfft, irfftonly the n/2+1n/2 + 1 nonnegative frequencies of a real signalreal signals (half the cost)
np.fft.fft(x, norm="ortho")unitary DFT, scale 1/n1/\sqrt n in both directionsto preserve the norm
scipy.signal.fftconvolve, oaconvolvelinear FFT convolution with padding (and overlap-add)long kernels
scipy.signal.convolve(..., method="auto")chooses direct or FFT by sizedefault
scipy.linalg.toeplitz, circulant, dftdense matricestesting, small sizes
scipy.linalg.solve_toeplitzsolves Toeplitz systems with Levinson recursion, O(n2)\bigO(n^2)Toeplitz systems (autocovariances)
torch.fft.rfft, irfftsame with autograd, on GPUlong convolutions inside a network
[ ]The above with SciPy and NumPyBrowser
from scipy.linalg import toeplitz as sp_toeplitz, circulant as sp_circulant, dft, solve_toeplitz

rng = np.random.default_rng(1)
n = 6
c = rng.normal(size=n); r = np.r_[c[0], rng.normal(size=n - 1)]; x = rng.normal(size=n)
print("circulant = nuestra circulante:", np.allclose(sp_circulant(c), circulant(c)),
      "| toeplitz = nuestra toeplitz:", np.allclose(sp_toeplitz(c, r), toeplitz(c, r)))
print("dft(n) = fft de la identidad:", np.allclose(dft(n), np.fft.fft(np.eye(n))),
      "| norma conservada con norm='ortho':", np.isclose(np.linalg.norm(np.fft.fft(x, norm="ortho")), np.linalg.norm(x)))
print("solve_toeplitz resuelve T y = x:", np.allclose(sp_toeplitz(c, r) @ solve_toeplitz((c, r), x), x))

h, s = rng.normal(size=50), rng.normal(size=400)
y_fft = np.fft.irfft(np.fft.rfft(h, 512) * np.fft.rfft(s, 512), 512)[:449]       # lo que hace fftconvolve por dentro
print("irfft(rfft(h) * rfft(s)) con relleno = np.convolve:", np.allclose(y_fft, np.convolve(h, s)))

# lo que hacen las capas convolucionales: correlación cruzada, es decir, convolución con el núcleo invertido
w = np.array([1.0, 2.0, 3.0]); senal = np.arange(8.0) ** 2
print("correlación = convolución con el núcleo invertido:", np.allclose(np.correlate(senal, w, "valid"), np.convolve(senal, w[::-1], "valid")))
print("rfft de 400 muestras reales:", np.fft.rfft(s).shape, "frente a fft:", np.fft.fft(s).shape,
      "| ida y vuelta:", np.allclose(np.fft.irfft(np.fft.rfft(s), len(s)), s))

For linear convolutions there is no need to write padding by hand: scipy.signal.fftconvolve(h, s) does it (and oaconvolve uses overlap-add for very long signals), while scipy.signal.convolve(h, s, method="auto") chooses direct or FFT by size; both give the same result as np.convolve(h, s). PyTorch has the same interface, with a difference that matters when training:

import torch

def conv_larga_causal(h, x):
    """h, x: (..., T). Convolución causal por FFT; diferenciable respecto de las dos entradas."""
    T = x.shape[-1]
    N = 1 << (2 * T - 1).bit_length()
    y = torch.fft.irfft(torch.fft.rfft(h, N) * torch.fft.rfft(x, N), N)
    return y[..., :T]

# nn.Conv1d NO calcula la convolución: calcula la correlación cruzada (no invierte el núcleo)
w = torch.tensor([[[1.0, 2.0, 3.0]]])             # (canales_sal, canales_ent, longitud)
x = torch.arange(8.0).reshape(1, 1, 8)
y_corr = torch.nn.functional.conv1d(x, w)          # y_j = 1 x_j + 2 x_{j+1} + 3 x_{j+2}

PyTorch functions propagate gradients through the FFT, so kernel h\vb{h} can be a learned parameter of length TT, exactly what implicit long convolutions do.

Common mistakes

Exercises

NumericA transform's norm
Let x=(3,0,4,0,0,0,0,0)∈R8\vb{x} = (3, 0, 4, 0, 0, 0, 0, 0) \in \R^8 and F\mat{F} be the order-8 DFT matrix. Compute ∥Fx∥2\norm{\mat{F}\vb{x}}_2.
QuizWhat complex matrices preserve
Which statements are true for complex matrices?

More than one answer may be correct.

NumericA circulant's second eigenvalue
Let C\mat{C} be the 4×44\times 4 circulant with first column c=(1,2,3,4)\vb{c} = (1, 2, 3, 4). Compute ∣λ1∣\abs{\lambda_1}, the magnitude of the eigenvalue associated with the frequency-m=1m = 1 wave.
NumericThe smallest eigenvalue
Compute the smallest eigenvalue of the symmetric circulant matrix with first column c=(2,1,0,1)\vb{c} = (2, 1, 0, 1).
NumericHow much padding is needed?
You want the full linear convolution of a signal of 10001000 samples and a filter of 200200 using a radix-2 FFT (power-of-2 length). What is the smallest possible length NN?
QuizThe cost of a Toeplitz matrix
An n×nn\times n Toeplitz matrix is embedded in a circulant of size 2n2n. What is the cost of the product Tx\mat{T}\vb{x} using that embedding?
QuizThe matrix of a Conv1d layer
A single-channel nn.Conv1d layer with no padding or bias and kernel w=(w0,w1,w2)\vb{w} = (w_0, w_1, w_2) computes yj=w0xj+w1xj+1+w2xj+2y_j = w_0 x_j + w_1 x_{j+1} + w_2 x_{j+2} for j=0,…,n−3j = 0, \dots, n - 3. Which (n−2)×n(n-2) \times n matrix represents it?
QuizPositions giving the same score
With RoPE, query vector q\vb{q} and key vector k\vb{k} are fixed, the query is at position mm and the key at nn. The score at (m,n)=(7,3)(m, n) = (7, 3) is ss. Which other position pairs necessarily give the same score?

More than one answer may be correct.

ProofF divided by the square root of n is unitary
Prove: Let ω=e−2πi/n\omega = e^{-2\pi i/n} and F∈Cn×n\mat{F} \in \C^{n\times n} with Fjk=ωjkF_{jk} = \omega^{jk}. Then U=F/n\mat{U} = \mat{F}/\sqrt n is unitary: U∗U=I\mat{U}^*\mat{U} = \mat{I}.
0
Use the roots-of-unity sum lemma: ∑k=0n−1ωkp=n\sum_{k=0}^{n-1}\omega^{kp} = n if nn divides pp and 00 otherwise.

Step 1 of 4. What is entry (j,l)(j, l) of F∗F\mat{F}^*\mat{F}?

ProofThe DFT diagonalizes circulants
Prove: Let C\mat{C} be a circulant with first column c\vb{c}, Cjk=c(j−k) mod nC_{jk} = c_{(j-k) \bmod n}, and let wm=(e2πi mk/n)k=0n−1\vb{w}_m = (e^{2\pi i\,mk/n})_{k=0}^{n-1}. Then Cwm=(Fc)m wm\mat{C}\vb{w}_m = (\mat{F}\vb{c})_m\,\vb{w}_m, and hence C=U∗ diag⁡(Fc) U\mat{C} = \mat{U}^*\,\diag(\mat{F}\vb{c})\,\mat{U} with U=F/n\mat{U} = \mat{F}/\sqrt n.
0
Compute entry jj of Cwm\mat{C}\vb{w}_m directly from the definition.

Step 1 of 4. What is (Cwm)j(\mat{C}\vb{w}_m)_j by the definition of matrix-vector multiplication?

The convolution theorem without diagonalization. F(c⊛x)=(Fc)⊙(Fx)\mat{F}(\vb{c} \circledast \vb{x}) = (\mat{F}\vb{c}) \odot (\mat{F}\vb{x}) can be proved directly using only definitions and a change of index. Try to predict each step before revealing it:

(c⊛x)j=∑k=0n−1c(j−k) mod n xk(\vb{c}\circledast\vb{x})_j = \sum_{k=0}^{n-1} c_{(j-k)\bmod n}\,x_k
Circular convolution by definition.
1/5
CodeCirculants and Toeplitz with the FFT
Implement circulant_matvec(c, x), returning Cx\mat{C}\vb{x} for circulant C\mat{C} with first column c, and toeplitz_matvec(c, r, x), returning Tx\mat{T}\vb{x} for the n×nn\times n Toeplitz matrix with first column c and first row r (with c[0] == r[0]). Both must cost O(nlog⁡n)\bigO(n\log n) and never form an n×nn\times n matrix: tests include n=30000n = 30000. For real inputs, output must be real (no residual imaginary part). Hint: embed the Toeplitz matrix in a circulant of size 2n2n.
import numpy as np

def circulant_matvec(c, x):
  """C x, con C circulante de primera columna c, en O(n log n)."""
  # tu código: teorema de convolución
  return np.zeros(len(x))

def toeplitz_matvec(c, r, x):
  """T x, con T de Toeplitz n x n de primera columna c y primera fila r (c[0] == r[0]), en O(n log n)."""
  # tu código: inmersión en una circulante de tamaño 2n
  return np.zeros(len(x))
Shift+Enter to run

Summary

Key idea
A structured matrix (constant diagonals, rotated blocks, small rank by blocks) is described with few numbers and multiplied in fewer than n2n^2 operations. Toeplitz and circulant matrices, used for convolutions, multiply in O(nlog⁡n)\bigO(n\log n) because the Fourier transform, a unitary basis change, diagonalizes all circulants at once and the FFT computes it as a product of sparse matrices.
  • Convolution is multiplication by a Toeplitz matrix (Tjk=tj−kT_{jk} = t_{j-k}); if the signal wraps around, by a circulant (Cjk=c(j−k) mod nC_{jk} = c_{(j-k) \bmod n}). Every circulant is a polynomial in shift matrix S\mat{S}.
  • In Cn\C^n we use inner product x∗y\vb{x}^*\vb{y} (with conjugation) and adjoint A∗\mat{A}^*. Unitary matrices (U∗U=I\mat{U}^*\mat{U} = \mat{I}) preserve inner products and norms and have eigenvalues of magnitude 1. Normal matrices are those diagonalizable in an orthonormal basis.
  • The DFT matrix Fjk=e−2πi jk/nF_{jk} = e^{-2\pi i\,jk/n} satisfies F∗F=nI\mat{F}^*\mat{F} = n\mat{I}: a unitary basis change to wave basis e2πi mk/ne^{2\pi i\,mk/n}. It preserves energy (Parseval), and for real signals frequencies mm and n−mn - m are paired.
  • The FFT factors F2m\mat{F}_{2m} into sparse matrices with Fm\mat{F}_m on the block diagonal, giving cost O(nlog⁡n)\bigO(n\log n).
  • The DFT diagonalizes every circulant, with eigenvalues λm=(Fc)m\lambda_m = (\mat{F}\vb{c})_m: the convolution theorem, F(c⊛x)=Fc⊙Fx\mat{F}(\vb{c}\circledast\vb{x}) = \mat{F}\vb{c}\odot\mat{F}\vb{x}. Linear convolution requires zero-padding to N≥n+m−1N \ge n + m - 1, and a Toeplitz matrix is multiplied by embedding it in a circulant of size 2n2n.
  • RoPE rotates each query and key plane by an angle proportional to position, and Rm⊤Rn=Rn−m\mat{R}_m\T\mat{R}_n = \mat{R}_{n-m} makes the score depend only on distance: Toeplitz structure.
  • Fast structured families include low-rank, Toeplitz and circulant, semiseparable matrices (state-space models, with recurrence-convolution and attention duality), butterflies and Monarch (products of sparse or block diagonal factors).