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 inputs and outputs stores weights and spends multiplications on each matrix-vector product. With that is numbers, about 17 GB in float32: more than fits in most consumer GPUs. Yet some matrices of that size are stored in 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 and is built using rotations so it depends only on (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 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 is determined by numbers, not , 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 rather than . For the ratio is .
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 be a signal and a filter (the kernel). The convolution of with is
with outside . In this lesson vector and matrix indices begin at 0, as in the code, so DFT formulas have no offsets. The output has entries. To compute , reverse the kernel, place it over the signal with under , and sum the products of overlapping entries: the sliding window. This is linear in , so it is a matrix times . The figure shows both views at once.
Entry of is if and zero otherwise: it depends only on the difference . 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 . Keeping only the first outputs (what a causal model does: depends on ) 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 and are causal matrices of two kernels, their product is the causal matrix of kernel (truncated), just as when multiplying polynomials and retaining terms of degree less than . And since , 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, , that matrix is a Kronecker product of two small Toeplitz matrices, , as you will verify in code.
Direct multiplication by an Toeplitz matrix costs . For an 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, , it is , and we want to reduce it. To do so, understand what diagonalizes circulants; for that, some algebra in .
Complex numbers, adjoints and unitary matrices
Fourier waves are complex, so we need to measure lengths and angles in . The first intuition, copying , fails. With it would yield 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: . (2) . (3) If with , by (2) . (4) , and is unitary because . For Hermitian matrices: if , then and this number equals its conjugate, , hence . With and , (with real), and then .
∎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 and , an th root of unity: and . The numbers 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 divides , each summand is . Otherwise and the geometric sum gives , because .
∎For , with :
This is the NumPy, SciPy and MATLAB convention. The inverse has the opposite sign and factor ; other libraries and books distribute the scale as 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 the sampled complex exponential of frequency (it completes turns in samples):
Its real and imaginary parts are sampled cosine and sine. The are columns of , and the rows of are their conjugates, so : coefficient measures how much of wave is in . If the waves formed an orthogonal basis, their coordinates could be read off as inner products. And they do.
Proof
Entry of is , because . By the lemma it equals if and otherwise (the difference lies between and and is a multiple of only at 0). The rest follows from the unitary theorem: gives the inverse and gives Parseval.
∎That is the entire content of the DFT. It is a unitary change of basis: signal is written in the canonical basis, is the same signal written in the wave basis, and its length is unchanged, . The energy of is distributed among frequencies, (Parseval’s or Plancherel’s theorem, depending on the book). If is real, also , so frequencies and have equal energy and come together.
Three things to check in the figure. An isolated pulse has a flat spectrum (all frequencies with the same energy, ): the opposite of a pure wave, which occupies a single pair . The square wave has only odd harmonics, with energy distributed approximately as : with (the pair ) it has 82% of the energy, with 92%, and with 100%. With all harmonics, reconstruction passes exactly through the 16 samples whatever the signal. That is what says.
The FFT: the dense matrix is a product of sparse matrices
Multiplying by in the obvious way costs complex multiplications. The fast Fourier transform (FFT, Cooley and Tukey, 1965) does it in . The idea is divide and conquer, and in matrix language says 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 into even and odd indices, and : . Since is the th root of unity, each sum is an order- DFT of the even () and odd () samples, and they are periodic in with period . Thus , and since , for . This is the matrix formula.
∎Applying the factorization recursively, is the product of factors with two nonzero entries per row, plus a permutation. This factors a dense matrix with entries into matrices with nonzero entries in total, so multiplication costs : if is the cost, , whose solution is . 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 repeats cyclically (index is taken modulo ), as does the kernel of equal length. Circular convolution has no edges.
The product is , the circular convolution . To understand circulants, look at the simplest one. Let be the shift matrix, the circulant with first column : . Shifting times gives , the circulant with first column , and . Then
Every circulant is a polynomial in . Two facts follow at once: circulants all commute, and any eigenvector basis of is simultaneously one for all of them. The eigenvectors of are already familiar. Shifting a pure wave does not deform it, only shifts its phase:
Proof
By the formula for as a polynomial in : . The columns of are the normalized waves , an orthonormal basis, so if , the preceding equality says , that is, . Since and are diagonal and commute, .
∎That is the complete picture. The figure makes it tangible: the matrix is generated by an editable vector ; choose a wave and the output is the same wave with amplitude multiplied by and phase shift ; when you choose a vector that is not a Fourier wave, its shape does change.
Each figure preset illustrates a reading of the theorem. Delay (circulant ) has , 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 has , with : the constant wave lies in its null space, and the fastest wave, , is amplified by . It is a high-pass filter. With :
Consequences
Once is known, every question about circulants reduces to one about numbers.
- Product. is circulant, with eigenvalues ; they commute. Circulants form a commutative algebra isomorphic to with elementwise product.
- Inverse and determinant. is invertible if and only if no is zero; then is circulant with eigenvalues . Also .
- Convolution theorem. is written , with 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 as takes three FFTs and products: instead of . Solving is the same with division instead of multiplication, also .
From circular to linear convolution
Circular and linear convolution do not coincide. With and , the linear convolution is , of length . Circular convolution of length 5 is : the last two values, and , wrapped onto the first two ( and ). The linear output does not fit in positions, and circular convolution folds it.
Proof
In only count. If the index is and gives the linear term. If , the index is , outside the support of (zero-padded): the term is zero. There is no wraparound.
∎In practice is chosen for a fast FFT: a power of 2 above 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 with ( between and ), and let be the circulant with first column
The upper-left block of is : if the entry is , and if the index is , where sits. Therefore
and a Toeplitz product costs three FFTs of size , , and 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 (its symbol) playing the role of eigenvalues; this is Szegő theory summarized by Gray (2006).
Block rotations and RoPE
Multiplication by a complex number is a rotation: identify with vector and the product with rotation matrix (Euler’s formula). A plane rotation satisfies : rotating backward and forward is a rotation by .
Let be even and take a list of frequencies . The position rotation is the block diagonal matrix
one plane per frequency, each rotated by an angle proportional to position. It is orthogonal and, by the above, . Identifying with , is the diagonal unitary matrix : complex exponentials again.
RoPE (rotary position embedding, Su et al., 2021) applies this idea to attention: the query at position and key at position are rotated, and , with geometrically decreasing frequencies . Their score is
Positions appear only through . In complex notation, , a sum of cosines of distance: with .
Two qualifications about what this does and does not say. If and were the same at every position, score matrix would be exactly Toeplitz, as in the figure. In real attention and come from projections of each token’s content and vary with position, so what is preserved is the positional part: . 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.
| Family | Parameters | Product | Idea |
|---|---|---|---|
| Dense | no structure | ||
| Rank (low rank) | with columns | ||
| Circulant | diagonal in the Fourier basis | ||
| Toeplitz | embedded in a circulant | ||
| Semiseparable of order | submatrices of rank | ||
| Butterfly | product of sparse factors | ||
| Monarch | two block diagonal factors and a permutation |
Semiseparable matrices and state-space models
A linear state-space model processes a sequence with a recurrence , , where is the state. Unrolling it gives : multiplication by lower triangular matrix with entries . That matrix is Toeplitz (it depends only on ), giving two algorithms for the same product: the sequential recurrence in with diagonal as in practice ( with dense ); or causal convolution with kernel computed by FFT in and in parallel. This is recurrence-convolution duality (m18) and why long-convolution models use the FFT.
But has more structure than being Toeplitz. Every submatrix in the lower triangular part (including the diagonal) has rank at most : for , factors through the state at time , which lives in . This is semiseparable of order .
If parameters depend on the input, (selective models such as Mamba, m18), then remains semiseparable and is multiplied by a scan in , but it is no longer Toeplitz and the FFT does not apply. Dao and Gu (2024) show that when , the matrix is with a rank-1 semiseparable mask (entries ), 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.
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 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 parameters including the DFT, Hadamard transform and many more, multiplied in . 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 sparse factors with two block diagonal factors hardware multiplies efficiently. With ,
where and are block diagonal with dense blocks of size each, and is the permutation transposing an grid (the vector is reshaped as an matrix and transposed). It has parameters and multiplies in , two batched small-matrix multiplications. For , versus : 32 times fewer. The code above verifies that the order- DFT is, up to a column permutation, a Monarch matrix: , with the diagonal of twiddle factors. This is the Cooley–Tukey factorization with instead of .
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.
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 gives a convolution that is the Kronecker product of two Toeplitz matrices. The convention is ravel (rowwise): corresponds to .
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 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).
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 and count nonzero entries.
_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 , versus simple multiplications and additions for the direct method. The crossover depends on implementation.
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 ; at they would take seconds in the browser, while np.fft reaches 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 and clearly ahead at , as the slopes predict; np.fft, written in C, catches it around . And np.convolve uses a very tight loop underneath: the crossover depends on both implementations. The slope does not, so with or samples there is no contest.
Long causal convolution
Long-convolution models (Hyena, S4) have a filter as long as the sequence, , and causal: . This is multiplication by lower triangular Toeplitz . With the FFT, causality comes from zero-padding to and keeping the first outputs; without padding the result’s tail wraps onto the beginning and breaks causality.
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 computes using contributions from , 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 and ; 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 , the dense matrix would occupy 7.2 GB in float64; here it is never formed.
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
| Function | What it does | When to use it |
|---|---|---|
np.fft.fft, ifft | DFT with sign and inverse scale | complex signals |
np.fft.rfft, irfft | only the nonnegative frequencies of a real signal | real signals (half the cost) |
np.fft.fft(x, norm="ortho") | unitary DFT, scale in both directions | to preserve the norm |
scipy.signal.fftconvolve, oaconvolve | linear FFT convolution with padding (and overlap-add) | long kernels |
scipy.signal.convolve(..., method="auto") | chooses direct or FFT by size | default |
scipy.linalg.toeplitz, circulant, dft | dense matrices | testing, small sizes |
scipy.linalg.solve_toeplitz | solves Toeplitz systems with Levinson recursion, | Toeplitz systems (autocovariances) |
torch.fft.rfft, irfft | same with autograd, on GPU | long convolutions inside a network |
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 can be a learned parameter of length , exactly what implicit long convolutions do.
Common mistakes
Exercises
More than one answer may be correct.
nn.Conv1d layer with no padding or bias and kernel computes for . Which matrix represents it?More than one answer may be correct.
Step 1 of 4. What is entry of ?
Step 1 of 4. What is by the definition of matrix-vector multiplication?
The convolution theorem without diagonalization. can be proved directly using only definitions and a change of index. Try to predict each step before revealing it:
circulant_matvec(c, x), returning for circulant with first column c, and toeplitz_matvec(c, r, x), returning for the Toeplitz matrix with first column c and first row r (with c[0] == r[0]). Both must cost and never form an matrix: tests include . For real inputs, output must be real (no residual imaginary part). Hint: embed the Toeplitz matrix in a circulant of size .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))Summary
- Convolution is multiplication by a Toeplitz matrix (); if the signal wraps around, by a circulant (). Every circulant is a polynomial in shift matrix .
- In we use inner product (with conjugation) and adjoint . Unitary matrices () preserve inner products and norms and have eigenvalues of magnitude 1. Normal matrices are those diagonalizable in an orthonormal basis.
- The DFT matrix satisfies : a unitary basis change to wave basis . It preserves energy (Parseval), and for real signals frequencies and are paired.
- The FFT factors into sparse matrices with on the block diagonal, giving cost .
- The DFT diagonalizes every circulant, with eigenvalues : the convolution theorem, . Linear convolution requires zero-padding to , and a Toeplitz matrix is multiplied by embedding it in a circulant of size .
- RoPE rotates each query and key plane by an angle proportional to position, and 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).