fft, ifft, rfft, irfft, hfft, and ihfft#
A discrete Fourier transform takes n values to n frequencies:
X_k = sum over j < n of x_j exp(-2 pi i j k / n)
Spectrograms, convolutions of long signals, and models such as FNet compute
one. A fast Fourier transform (FFT) gets there in passes. It factors n into
small radices, such as 4096 = 8 x 8 x 8 x 8, and each pass
combines groups of values in small transforms called butterflies. Between
passes it multiplies values by twiddle factors,
roots of unity such as exp(-2 pi i k / n). Every pass rounds, and the
twiddle factors are rounded too, so two FFT libraries give slightly
different spectra for the same input.
An FFT of length 4096 by four passes of radix 8.
In ExactRef, er.fft.fft(x, n=None, axis=-1, norm=None) and the five
transforms below compute the transform exactly and round it once. Every real
and imaginary part of every output is correctly rounded: the
reference. They are also in er.fft.dft, and are named as
torch.fft names them. To check another implementation's output, use
covers(), as every example below does.
The tolerance, per part how far a correct implementation's output can be from the reference, covers every implementation that computes by radix passes, for any factorization of n, with these boundaries:
butterflies: each pass of radix 2, 3, 4, 5, 7, 8, or 11, or a prime of 13 or more, rounding its outputs in the compute format. A real input, and the real outputs of
irfftandhfft, may instead take real passes, which work on real values directly, or at even n a packed form of n/2 complex values.twiddles: each twiddle factor within
ulpstimes the compute format's unit roundoff of its exact value, and each product by one rounded in the compute format.ulpsis an option oftolerance()andcovers(), by default 2 for float32 and narrower compute formats and 10 for float64.scale: the norm's factor,
1/nor1/sqrt(n), and its product.
pocketfft and DUCC may compute a length with a large prime factor by Bluestein's algorithm instead. For such a length the tolerance is not proven, only measured against these libraries. An FFT algorithm with a Bluestein pass gives a proven bound.
FFT libraries share no order of additions, so the Fourier transforms have no
normal answer: normal() raises NotImplementedError, and
tolerance(standard="any_order") is the same as the default. When you know
a library's plan, its list of passes, an
FFT algorithm gives a tighter
tolerance.
The six transforms#
Transform |
Input |
Output |
Scale by default |
|---|---|---|---|
|
n values |
n complex values |
1 |
|
n values |
n complex values, by |
|
|
n real values |
the half spectrum: |
1 |
|
n real values |
|
|
|
n//2 + 1 complex values, a half spectrum |
the n real values whose half spectrum it is |
|
|
n//2 + 1 complex values, half of a signal whose transform is real |
that real transform's n values |
1 |
What goes in and out of each transform, for n = 8.
A real input's spectrum is symmetric: each value past the middle is the
complex conjugate of one before it. So rfft returns only the first half,
and irfft takes only that half back:
The spectrum of 8 real values. rfft computes X0 to X4; X5, X6, and X7 are
the conjugates of X3, X2, and X1.
A real input to fft or ifft counts as complex with imaginary parts 0, and
integers and bools count by their exact values. The output is complex32 for
float16 and complex32 inputs, complex128 for float64 and complex128 inputs,
and complex64 for bfloat16, float32, complex64, integer, and bool inputs;
float8 inputs are refused. irfft and hfft give the matching real format:
float16, float64, or float32. For complex outputs, tolerance() holds one
bound per part, as a complex128 array.
Arguments#
Argument |
Meaning |
Default |
|---|---|---|
|
the input: an array, a tensor, or an earlier result |
required |
|
the transform's length: |
the input's length; for |
|
the axis to transform, or a tuple of axes, transformed together |
|
|
where the scale goes: |
|
|
the output format |
complex for |
|
the rounding mode of the reference and of a correct implementation's final rounding into the output format |
|
|
what a result past the output format's range becomes: |
each format's own rule |
|
the number of threads the call computes on; no result depends on it |
the performance cores on Apple Silicon, else the physical cores, as PyTorch picks |
Over several axes, the scale uses the product of their lengths, and rfft,
ihfft, irfft, and hfft take the half spectrum on the last axis in
axis. For fft and ifft, axis=() returns the input, rounded to the
output format; the other four need at least one axis.
Examples#
One axis: the frames of a spectrogram#
A spectrogram transforms short frames of a signal: here 64 frames of 4096 audio samples, each multiplied by a Hann window, in float32:
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# 64 frames of 4096 samples, each multiplied by a Hann window
frames = torch.randn(64, 4096, generator=g) * torch.hann_window(4096)
# The half spectrum of each frame: the exact transform, rounded once
r = er.fft.rfft(frames)
print("shape:", r.rounded.shape)
print("dtype:", r.rounded.dtype.name)
# Could a correct FFT produce PyTorch's spectrum, every part of every value?
print("covered:", r.covers(torch.fft.rfft(frames)).all())
shape: (64, 2049)
dtype: complex64
covered: True
Several axes: FNet's token mixing#
FNet mixes tokens with a two-dimensional transform over the sequence and the
features, torch.fft.fft2. In ExactRef that is fft with a tuple of axes:
# A batch of 4 sequences of 512 tokens with 768 features, as in FNet-Base
hidden = torch.randn(4, 512, 768, generator=g)
# The transform over the last two axes at once
r2 = er.fft.fft(hidden, axis=(-2, -1))
print("shape:", r2.rounded.shape)
print("covered:", r2.covers(torch.fft.fft2(hidden)).all())
shape: (4, 512, 768)
covered: True
A transform over two axes runs one axis's passes, then the other's; an implementation may take either axis first.
Padding and chains: a convolution by FFT#
Long-convolution models, such as Hyena, convolve each channel's sequence with a filter as long as the sequence. They do it by FFT. Both are padded to twice the length, so that the transform's circular convolution equals the ordinary one. Their spectra are multiplied, and the product is transformed back. Each step is an operation, and passing one step's result to the next makes a chain, whose bounds cover every value the earlier steps allow:
# 768 channels of a sequence of 4096, and a filter of the same length for each
u = torch.randn(768, 4096, generator=g)
filters = torch.randn(768, 4096, generator=g) / 64
# Both padded to 8192, transformed, multiplied, and transformed back
spectrum = er.multiply(er.fft.rfft(u, n=8192), er.fft.rfft(filters, n=8192))
conv = er.fft.irfft(spectrum, n=8192)
# The same convolution in PyTorch
out = torch.fft.irfft(torch.fft.rfft(u, n=8192) * torch.fft.rfft(filters, n=8192), n=8192)
print("covered:", conv.covers(out).all())
covered: True
Special values#
An input with an infinity or NaN follows IEEE rules on the exact sums,
except that a term whose coefficient, a real or imaginary part of
exp(-2 pi i j k / n), is exactly 0 is left out. A non-finite input can
reach every output, so at every output may_be() is True for each special
value it can produce, and the tolerance is NaN where the reference is not
finite. A clipped sample that overflowed to infinity:
# 16 samples, the fourth of them infinite
clipped = torch.randn(16, generator=g)
clipped[3] = float("inf")
s = er.fft.rfft(clipped)
# The first three values of the reference
print("rounded:", s.rounded.tolist()[:3])
# May a correct FFT give NaN at the first value, in its real and imaginary parts?
print("may be NaN:", s.may_be("nan").tolist()[0])
print("covered:", s.covers(torch.fft.rfft(clipped)).all())
rounded: [(inf+0j), (inf-infj), (-inf-infj)]
may be NaN: [True, True]
covered: True
Checking NumPy#
NumPy computes a float64 input's transform in float64, and a float32 input's in float32:
import numpy as np
# 64 frames of 4096 samples in float64
x = np.random.default_rng(67).standard_normal((64, 4096))
r64 = er.fft.fft(x)
print("dtype:", r64.rounded.dtype.name)
print("NumPy covered:", r64.covers(np.fft.fft(x)).all())
dtype: complex128
NumPy covered: True
NumPy runs pocketfft, as PyTorch's CPU FFT does in builds without MKL, such as its ARM builds. PyTorch's x86-64 builds run MKL's FFT, whose plans are not public. FFT algorithms gives pocketfft's and DUCC's plans, for a tighter check.
JAX's scaled forms#
JAX scales some transforms in two steps, or by a factor above 1, which the
tolerance's one scale step does not include. Check those forms as chains:
the transform at the norm the table gives, then er.multiply by JAX's
factors. JAX's CPU kernels flush subnormals, so pass flush_to_zero=True to
covers().
JAX |
ExactRef |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Here c is JAX's norm factor, computed and rounded in the output format as
JAX computes it (1 for "backward"), inv_n the output format's 1/n for
the last axis's length, and n_r that length as the output format holds it.
The
full specification below gives the gradients' chains.
Backward#
er.fft.fft.backward(x, grad, n=None, axis=-1, norm=None) and the same for
the other five return the gradient with respect to x, in PyTorch's
convention: dL/dRe + i dL/dIm for a complex input, and its real part for a
real one. JAX's vjp at a cotangent t is the conjugate of this gradient at
conj(t). The gradient is named grad_x, or grad_X for ifft and
irfft, whose input is a spectrum.
The gradient has the input's shape: +0 where the forward trimmed the input,
and the gradients of padded entries dropped. A transform is linear, so its
gradient does not depend on the input's values: x gives only its shape and
format. For an integer or bool input, backward raises TypeError. Every
part is correctly rounded once, and the tolerance covers computing grad's
transform the way the forward's tolerance describes.
A loss on the frames' spectra, backpropagated through PyTorch's rfft:
# PyTorch's autograd through rfft, for a gradient of the spectrum
frames_ = frames.clone().requires_grad_()
grad = torch.randn(64, 2049, generator=g, dtype=torch.complex64)
torch.fft.rfft(frames_).backward(grad)
# ExactRef's gradient, read by name as a result of its own
gb = er.fft.rfft.backward(frames, grad)
print("covered:", gb["grad_x"].covers(frames_.grad).all())
covered: True
Full specification#
The transforms#
- fft(x, n: int | tuple | None = None, axis: int | tuple = -1, norm: str | None = None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Discrete Fourier transform along
axis:X_k = s sum_{j<n} x_j exp(-2 pi i j k / n).xis trimmed, or padded with zeros at the end, tonalongaxis(by default its length there). The scalesis 1 fornorm="backward"(or None),1/sqrt(n)for "ortho" and1/nfor "forward".axismay also be a tuple of distinct axes, transformed at once with the phase summed over them, andnthen None or a tuple of the same length (an entry of -1 meaning the axis's length); the scale uses V, the product of the lengths. An intnneeds an intaxis, andaxis=Noneis an error:torch.fft.fftn(x)isfft(x, axis=tuple(range( x.ndim))),fftn(x, s)isfft(x, n=s, axis=...)over the lastlen(s)axes, andfft2takesaxis=(-2, -1). Withaxis=()the output is the input, rounded to the output format. A real input transforms as the complex input with imaginary parts 0, and integers and bools by their exact values. The output is complex: complex32 for float16 and complex32 inputs, complex128 for float64 and complex128 ones, complex64 for bfloat16, float32, complex64, integer, and bool ones, ordtype; a float8 input is a TypeError.Every part of every output is the exact value correctly rounded once: each is enclosed by an interval transform, a part whose enclosure does not decide its rounding is proven exactly zero, exactly rational (and then rounded from its exact value, ties and values on a rounding boundary included), or irrational by number theoretic transforms of the scaled inputs modulo primes, and the irrational ones are refined until they round; no precision cap applies. An exact zero is +0, or -0 when rounding toward -inf. Inputs with infinities or NaN follow IEEE rules on the exact sums, where a coefficient part that is exactly 0 adds no term.
tolerance()bounds every implementation that computes the transform by passes of butterflies for some factorization of n into the radices 2, 3, 4, 5, 7, 8, and 11, and primes of 13 or more (a real input also by real passes, or at even n packed into n/2 complex values and recombined), with each radix's butterflies within its stated accuracy, twiddle factors withinulpsunits of the compute format's unit roundoff (2 by default for float32 and narrower compute formats, 10 for float64), each product by a twiddle computed in the compute format (each part from at most two products and a sum, fused or not), and the scale's factor held within three roundings and its product rounded once in the compute format (proofs/fft.md). Over several axes the implementation runs them one after another, each in one of these forms, with the scale in at most one stage per axis. The bound is the same under both standards: no index-order accumulation is shared by FFT algorithms, so there is nonormal(). A transform with an infinite or NaN input admits an infinity or NaN at every part.xmay also be an earlier result, asResultdescribes.JAX's
jnp.fft.fftandjnp.fft.fftnround as this tolerance allows at every norm, but over three axes or more jnp's factorc, computed from the lengths' product in the output format, may take more than three roundings (partial products whose odd parts pass 2**24 in float32); theremultiply(fft(x, n, axis, "backward"), c), JAX's own sequence at every size, bounds it (the names asifft's docstring gives them). JAX's CPU kernels flush subnormals, so check its outputs withflush_to_zero=True.
- ifft(x, n: int | tuple | None = None, axis: int | tuple = -1, norm: str | None = None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Inverse discrete Fourier transform along
axis:x_k = s sum_{j<n} X_j exp(+2 pi i j k / n).As
fft, with the sign of the exponent reversed and the scale1/nfornorm="backward"(or None),1/sqrt(n)for "ortho" and 1 for "forward".JAX's forms that round where this tolerance does not budget (its
1/n, then its norm factor), as chains of calls whose tolerances bound them:jnp.fft.ifft,jnp.fft.ifftnat "ortho" and "forward":multiply(ifft(x, n, axis, "backward"), c)
The names: the operations as
exactref.fftandexactref.multiplyhave them;nthe lengths (a tuple over several axes);Ntheir product andn_rthe last length, each as the real output format holds it (JAX converts a Python int to the array's format, rounding it past 2**24 in float32), andinv_nthe output format's1/non the last axis;cjnp's norm factor, as its_fft_normcomputes it in the output format (1 for None and "backward");wan array ofg's shape and format, 1 at 0 and, for evenn,n/2on the Hermitian axis, 1/2 elsewhere;conj(g)formed exactly; and for four axes or more JAX's split,innerits last two (three for five or more),outerthe others,n_innerthe inner lengths andN_innertheir product, asNis held. rfft's and ihfft's chains end inirfft, whose output has the transform's lengths: the gradient is that, +0 wherexis longer and cut where it is shorter. JAX's CPU kernels flush subnormals, so check its outputs withflush_to_zero=True(proofs/fft.md, Backward, JAX's forms).
- rfft(x, n: int | tuple | None = None, axis: int | tuple = -1, norm: str | None = None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The half spectrum of a real input along
axis:fft'sX_kfork <= n//2.As
fft(scale, padding, axes, formats, reference, and tolerance), for a real, integer, or bool input; a complex input is a TypeError. The other half is the conjugate of this one. Over several axes the half is taken on the last entry ofaxis. JAX'sjnp.fft.rfftandjnp.fft.rfftnround as this tolerance allows at every norm, but over three axes or more jnp's factorcmay take more than three roundings (asfft's docstring says); theremultiply(rfft(x, n, axis, "backward"), c), JAX's own sequence, bounds it.
- irfft(x, n: int | tuple | None = None, axis: int | tuple = -1, norm: str | None = None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The n real values whose half spectrum is
x, alongaxis:y_j = s Re(sum_{k <= n//2} c_k X_k exp(+2 pi i j k / n)), withc_k = 1atk = 0and (for even n)k = n/2, and 2 otherwise.xis trimmed, or padded with zeros at the end, ton//2 + 1entries alongaxis;ndefaults to2 (m - 1)formentries. Over several axes this holds for the last entry ofaxis(the Hermitian axis), whose weightc_kapplies, and the others transform in full, asfft's axes do. So along one axis the imaginary parts atk = 0andk = n/2add nothing, whatever they are; over several axes only where each other index is 0 or half its axis's length. The scale isifft's. A real input is the complex input with imaginary parts 0, and integers and bools are their exact values. The output is real: float16 for complex32 and float16 inputs, float64 for complex128 and float64 ones, float32 for bfloat16, float32, complex64, integer, and bool ones, ordtype; a float8 input is a TypeError.The reference is that of
ifftof the weighted inputc_k X_k(padded to n), real parts only, so every output is the exact value correctly rounded once.tolerance()bounds every implementation that computes it by complex passes, by the backward real passes, or at even n packed into a complex transform of n/2 (the "butterflies" boundary), asfft's does; the mass is the weighted input's.JAX's forms that round where this tolerance does not budget (its
1/n, then its norm factor), as chains of calls whose tolerances bound them:jnp.fft.irfft,jnp.fft.irfftnat "ortho" and "forward":multiply(irfft(x, n, axis, "backward"), c)
The names: the operations as
exactref.fftandexactref.multiplyhave them;nthe lengths (a tuple over several axes);Ntheir product andn_rthe last length, each as the real output format holds it (JAX converts a Python int to the array's format, rounding it past 2**24 in float32), andinv_nthe output format's1/non the last axis;cjnp's norm factor, as its_fft_normcomputes it in the output format (1 for None and "backward");wan array ofg's shape and format, 1 at 0 and, for evenn,n/2on the Hermitian axis, 1/2 elsewhere;conj(g)formed exactly; and for four axes or more JAX's split,innerits last two (three for five or more),outerthe others,n_innerthe inner lengths andN_innertheir product, asNis held. rfft's and ihfft's chains end inirfft, whose output has the transform's lengths: the gradient is that, +0 wherexis longer and cut where it is shorter. JAX's CPU kernels flush subnormals, so check its outputs withflush_to_zero=True(proofs/fft.md, Backward, JAX's forms).
- hfft(x, n: int | tuple | None = None, axis: int | tuple = -1, norm: str | None = None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The n real values of the forward transform of a Hermitian signal whose half is
x:y_j = s Re(sum_{k <= n//2} c_k X_k exp(-2 pi i j k / n)).As
irfft, with the sign of the exponent reversed andfft's scale.JAX's form, which rounds where this tolerance does not budget (its
1/n, its norm factor, andn), as a chain of calls whose tolerances bound it:jnp.fft.hfftat every norm:multiply(multiply(hfft(x, n, axis, "forward"), c), n_r)
The names: the operations as
exactref.fftandexactref.multiplyhave them;nthe lengths (a tuple over several axes);Ntheir product andn_rthe last length, each as the real output format holds it (JAX converts a Python int to the array's format, rounding it past 2**24 in float32), andinv_nthe output format's1/non the last axis;cjnp's norm factor, as its_fft_normcomputes it in the output format (1 for None and "backward");wan array ofg's shape and format, 1 at 0 and, for evenn,n/2on the Hermitian axis, 1/2 elsewhere;conj(g)formed exactly; and for four axes or more JAX's split,innerits last two (three for five or more),outerthe others,n_innerthe inner lengths andN_innertheir product, asNis held. rfft's and ihfft's chains end inirfft, whose output has the transform's lengths: the gradient is that, +0 wherexis longer and cut where it is shorter. JAX's CPU kernels flush subnormals, so check its outputs withflush_to_zero=True(proofs/fft.md, Backward, JAX's forms).
- ihfft(x, n: int | tuple | None = None, axis: int | tuple = -1, norm: str | None = None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The half spectrum of a real input by the inverse transform:
ifft'sx_kfork <= n//2, the conjugate ofrfftwithifft's scale.As
rfft, with the sign of the exponent reversed andifft's scale.JAX's form that rounds where this tolerance does not budget (its norm factor, then
1/n), as a chain of calls whose tolerances bound it:jnp.fft.ihfftat "ortho" and "forward":multiply(multiply(ihfft(x, n, axis, "forward"), c), inv_n)
The names: the operations as
exactref.fftandexactref.multiplyhave them;nthe lengths (a tuple over several axes);Ntheir product andn_rthe last length, each as the real output format holds it (JAX converts a Python int to the array's format, rounding it past 2**24 in float32), andinv_nthe output format's1/non the last axis;cjnp's norm factor, as its_fft_normcomputes it in the output format (1 for None and "backward");wan array ofg's shape and format, 1 at 0 and, for evenn,n/2on the Hermitian axis, 1/2 elsewhere;conj(g)formed exactly; and for four axes or more JAX's split,innerits last two (three for five or more),outerthe others,n_innerthe inner lengths andN_innertheir product, asNis held. rfft's and ihfft's chains end inirfft, whose output has the transform's lengths: the gradient is that, +0 wherexis longer and cut where it is shorter. JAX's CPU kernels flush subnormals, so check its outputs withflush_to_zero=True(proofs/fft.md, Backward, JAX's forms).
Their backwards#
- backward(x, grad, n: int | tuple | None = None, axis: int | tuple = -1, norm: str | None = None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradient of
fft:grad_x_j = s sum_k grad_k exp(+2 pi i j k / n),fft's scaleswith the opposite sign, as PyTorch's_fft_c2cbackward computes it; for a realxits real part.Over several axes the sums run over every transformed axis, the Hermitian axis the last. The gradient has the input's shape: +0 at the entries the forward trimmed (index
nor more on an axis), and the gradients of the entries it padded are dropped. This is PyTorch's convention,dL/dRe + i dL/dImfor a complex input and the real part for a real one; JAX'svjpat a cotangenttis the conjugate of this gradient atconj(t).The result holds the gradient by name, as every backward's:
grad_x, orgrad_Xfor ifft and irfft (result.rounded.grad_x;coverstakes{"grad_x": output}, andresult["grad_x"]is a result of its own, which can be another operation's input).gradhas the forward output's shape and kind, in any format of that kind. The input gives only its shape and format (a linear map's gradient does not depend on the input's values), and both may be earlier results. The output's format isdtype, by default the input's, of the input's kind. An integer or bool input has no gradient: a TypeError.Every part is the exact value correctly rounded once: the forward's reference applied to
grad's transform, a weighted part doubled exactly before its rounding.tolerance()bounds every implementation that computesgrad's transform as the forward's tolerance describes and then takes real parts or doubles the weighted parts, after the transform or between its axes; a weighted part's bound is twice its transform's (proofs/fft.md, Backward).JAX's gradients in this convention, conj(vjp(conj(g))), that round where this tolerance does not budget, as chains of calls whose tolerances bound them:
jnp.fft.fft,jnp.fft.fftnat "ortho" and "forward":fft.backward(x, multiply(g, c), n, axis)
The names: the operations as
exactref.fftandexactref.multiplyhave them;nthe lengths (a tuple over several axes);Ntheir product andn_rthe last length, each as the real output format holds it (JAX converts a Python int to the array's format, rounding it past 2**24 in float32), andinv_nthe output format's1/non the last axis;cjnp's norm factor, as its_fft_normcomputes it in the output format (1 for None and "backward");wan array ofg's shape and format, 1 at 0 and, for evenn,n/2on the Hermitian axis, 1/2 elsewhere;conj(g)formed exactly; and for four axes or more JAX's split,innerits last two (three for five or more),outerthe others,n_innerthe inner lengths andN_innertheir product, asNis held. rfft's and ihfft's chains end inirfft, whose output has the transform's lengths: the gradient is that, +0 wherexis longer and cut where it is shorter. JAX's CPU kernels flush subnormals, so check its outputs withflush_to_zero=True(proofs/fft.md, Backward, JAX's forms).
- backward(x, grad, n: int | tuple | None = None, axis: int | tuple = -1, norm: str | None = None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradient of
ifft:grad_X_j = s sum_k grad_k exp(-2 pi i j k / n),ifft's scaleswith the opposite sign, as PyTorch's_fft_c2cbackward computes it; for a realXits real part.Over several axes the sums run over every transformed axis, the Hermitian axis the last. The gradient has the input's shape: +0 at the entries the forward trimmed (index
nor more on an axis), and the gradients of the entries it padded are dropped. This is PyTorch's convention,dL/dRe + i dL/dImfor a complex input and the real part for a real one; JAX'svjpat a cotangenttis the conjugate of this gradient atconj(t).The result holds the gradient by name, as every backward's:
grad_x, orgrad_Xfor ifft and irfft (result.rounded.grad_x;coverstakes{"grad_x": output}, andresult["grad_x"]is a result of its own, which can be another operation's input).gradhas the forward output's shape and kind, in any format of that kind. The input gives only its shape and format (a linear map's gradient does not depend on the input's values), and both may be earlier results. The output's format isdtype, by default the input's, of the input's kind. An integer or bool input has no gradient: a TypeError.Every part is the exact value correctly rounded once: the forward's reference applied to
grad's transform, a weighted part doubled exactly before its rounding.tolerance()bounds every implementation that computesgrad's transform as the forward's tolerance describes and then takes real parts or doubles the weighted parts, after the transform or between its axes; a weighted part's bound is twice its transform's (proofs/fft.md, Backward).JAX's gradients in this convention, conj(vjp(conj(g))), that round where this tolerance does not budget, as chains of calls whose tolerances bound them:
jnp.fft.ifft,jnp.fft.ifftnat "ortho" and "forward":ifft.backward(x, multiply(g, c), n, axis)
The names: the operations as
exactref.fftandexactref.multiplyhave them;nthe lengths (a tuple over several axes);Ntheir product andn_rthe last length, each as the real output format holds it (JAX converts a Python int to the array's format, rounding it past 2**24 in float32), andinv_nthe output format's1/non the last axis;cjnp's norm factor, as its_fft_normcomputes it in the output format (1 for None and "backward");wan array ofg's shape and format, 1 at 0 and, for evenn,n/2on the Hermitian axis, 1/2 elsewhere;conj(g)formed exactly; and for four axes or more JAX's split,innerits last two (three for five or more),outerthe others,n_innerthe inner lengths andN_innertheir product, asNis held. rfft's and ihfft's chains end inirfft, whose output has the transform's lengths: the gradient is that, +0 wherexis longer and cut where it is shorter. JAX's CPU kernels flush subnormals, so check its outputs withflush_to_zero=True(proofs/fft.md, Backward, JAX's forms).
- backward(x, grad, n: int | tuple | None = None, axis: int | tuple = -1, norm: str | None = None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradient of
rfft: the real part ofs sum_k grad_k exp(+2 pi i j k / n),gradfilled with zeros fromn//2 + 1tonon the Hermitian axis, as PyTorch's_fft_r2cbackward computes it.Over several axes the sums run over every transformed axis, the Hermitian axis the last. The gradient has the input's shape: +0 at the entries the forward trimmed (index
nor more on an axis), and the gradients of the entries it padded are dropped. This is PyTorch's convention,dL/dRe + i dL/dImfor a complex input and the real part for a real one; JAX'svjpat a cotangenttis the conjugate of this gradient atconj(t).The result holds the gradient by name, as every backward's:
grad_x, orgrad_Xfor ifft and irfft (result.rounded.grad_x;coverstakes{"grad_x": output}, andresult["grad_x"]is a result of its own, which can be another operation's input).gradhas the forward output's shape and kind, in any format of that kind. The input gives only its shape and format (a linear map's gradient does not depend on the input's values), and both may be earlier results. The output's format isdtype, by default the input's, of the input's kind. An integer or bool input has no gradient: a TypeError.Every part is the exact value correctly rounded once: the forward's reference applied to
grad's transform, a weighted part doubled exactly before its rounding.tolerance()bounds every implementation that computesgrad's transform as the forward's tolerance describes and then takes real parts or doubles the weighted parts, after the transform or between its axes; a weighted part's bound is twice its transform's (proofs/fft.md, Backward).JAX's gradients in this convention, conj(vjp(conj(g))), that round where this tolerance does not budget, as chains of calls whose tolerances bound them:
jnp.fft.rfft,jnp.fft.rfftnat every norm:multiply(irfft(multiply(multiply(g, c), w), n, axis), N); with four axes or more:multiply(irfft(multiply(ifft(multiply(g, c), axis=outer, norm="forward"), w), n_inner, inner), N_inner)
The names: the operations as
exactref.fftandexactref.multiplyhave them;nthe lengths (a tuple over several axes);Ntheir product andn_rthe last length, each as the real output format holds it (JAX converts a Python int to the array's format, rounding it past 2**24 in float32), andinv_nthe output format's1/non the last axis;cjnp's norm factor, as its_fft_normcomputes it in the output format (1 for None and "backward");wan array ofg's shape and format, 1 at 0 and, for evenn,n/2on the Hermitian axis, 1/2 elsewhere;conj(g)formed exactly; and for four axes or more JAX's split,innerits last two (three for five or more),outerthe others,n_innerthe inner lengths andN_innertheir product, asNis held. rfft's and ihfft's chains end inirfft, whose output has the transform's lengths: the gradient is that, +0 wherexis longer and cut where it is shorter. JAX's CPU kernels flush subnormals, so check its outputs withflush_to_zero=True(proofs/fft.md, Backward, JAX's forms).
- backward(x, grad, n: int | tuple | None = None, axis: int | tuple = -1, norm: str | None = None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradient of
irfft:grad_X_k = c_k s sum_j grad_j exp(-2 pi i j k / n)fork <= n//2, withirfft's weightsc_kand scales, for the realgrad; for a realXits real part. PyTorch's_fft_c2rbackward computes the transform (_fft_r2c) and then doubles the weighted entries.Over several axes the sums run over every transformed axis, the Hermitian axis the last. The gradient has the input's shape: +0 at the entries the forward trimmed (index
nor more on an axis), and the gradients of the entries it padded are dropped. This is PyTorch's convention,dL/dRe + i dL/dImfor a complex input and the real part for a real one; JAX'svjpat a cotangenttis the conjugate of this gradient atconj(t).The result holds the gradient by name, as every backward's:
grad_x, orgrad_Xfor ifft and irfft (result.rounded.grad_x;coverstakes{"grad_x": output}, andresult["grad_x"]is a result of its own, which can be another operation's input).gradhas the forward output's shape and kind, in any format of that kind. The input gives only its shape and format (a linear map's gradient does not depend on the input's values), and both may be earlier results. The output's format isdtype, by default the input's, of the input's kind. An integer or bool input has no gradient: a TypeError.Every part is the exact value correctly rounded once: the forward's reference applied to
grad's transform, a weighted part doubled exactly before its rounding.tolerance()bounds every implementation that computesgrad's transform as the forward's tolerance describes and then takes real parts or doubles the weighted parts, after the transform or between its axes; a weighted part's bound is twice its transform's (proofs/fft.md, Backward).JAX's gradients in this convention, conj(vjp(conj(g))), that round where this tolerance does not budget, as chains of calls whose tolerances bound them:
jnp.fft.irfft,jnp.fft.irfftnat "ortho" and "forward":irfft.backward(x, multiply(g, c), n, axis)
The names: the operations as
exactref.fftandexactref.multiplyhave them;nthe lengths (a tuple over several axes);Ntheir product andn_rthe last length, each as the real output format holds it (JAX converts a Python int to the array's format, rounding it past 2**24 in float32), andinv_nthe output format's1/non the last axis;cjnp's norm factor, as its_fft_normcomputes it in the output format (1 for None and "backward");wan array ofg's shape and format, 1 at 0 and, for evenn,n/2on the Hermitian axis, 1/2 elsewhere;conj(g)formed exactly; and for four axes or more JAX's split,innerits last two (three for five or more),outerthe others,n_innerthe inner lengths andN_innertheir product, asNis held. rfft's and ihfft's chains end inirfft, whose output has the transform's lengths: the gradient is that, +0 wherexis longer and cut where it is shorter. JAX's CPU kernels flush subnormals, so check its outputs withflush_to_zero=True(proofs/fft.md, Backward, JAX's forms).
- backward(x, grad, n: int | tuple | None = None, axis: int | tuple = -1, norm: str | None = None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradient of
hfft:grad_x_k = c_k s sum_j grad_j exp(+2 pi i j k / n)fork <= n//2, withhfft's weightsc_kand scales, for the realgrad; for a realxits real part. PyTorch's backwards of_fft_c2rand the conjugate compute the transform (_fft_r2c) and then double the weighted entries.Over several axes the sums run over every transformed axis, the Hermitian axis the last. The gradient has the input's shape: +0 at the entries the forward trimmed (index
nor more on an axis), and the gradients of the entries it padded are dropped. This is PyTorch's convention,dL/dRe + i dL/dImfor a complex input and the real part for a real one; JAX'svjpat a cotangenttis the conjugate of this gradient atconj(t).The result holds the gradient by name, as every backward's:
grad_x, orgrad_Xfor ifft and irfft (result.rounded.grad_x;coverstakes{"grad_x": output}, andresult["grad_x"]is a result of its own, which can be another operation's input).gradhas the forward output's shape and kind, in any format of that kind. The input gives only its shape and format (a linear map's gradient does not depend on the input's values), and both may be earlier results. The output's format isdtype, by default the input's, of the input's kind. An integer or bool input has no gradient: a TypeError.Every part is the exact value correctly rounded once: the forward's reference applied to
grad's transform, a weighted part doubled exactly before its rounding.tolerance()bounds every implementation that computesgrad's transform as the forward's tolerance describes and then takes real parts or doubles the weighted parts, after the transform or between its axes; a weighted part's bound is twice its transform's (proofs/fft.md, Backward).JAX's gradients in this convention, conj(vjp(conj(g))), that round where this tolerance does not budget, as chains of calls whose tolerances bound them:
jnp.fft.hfftat every norm:hfft.backward(x, multiply(multiply(g, n_r), c), n, axis, "forward")
The names: the operations as
exactref.fftandexactref.multiplyhave them;nthe lengths (a tuple over several axes);Ntheir product andn_rthe last length, each as the real output format holds it (JAX converts a Python int to the array's format, rounding it past 2**24 in float32), andinv_nthe output format's1/non the last axis;cjnp's norm factor, as its_fft_normcomputes it in the output format (1 for None and "backward");wan array ofg's shape and format, 1 at 0 and, for evenn,n/2on the Hermitian axis, 1/2 elsewhere;conj(g)formed exactly; and for four axes or more JAX's split,innerits last two (three for five or more),outerthe others,n_innerthe inner lengths andN_innertheir product, asNis held. rfft's and ihfft's chains end inirfft, whose output has the transform's lengths: the gradient is that, +0 wherexis longer and cut where it is shorter. JAX's CPU kernels flush subnormals, so check its outputs withflush_to_zero=True(proofs/fft.md, Backward, JAX's forms).
- backward(x, grad, n: int | tuple | None = None, axis: int | tuple = -1, norm: str | None = None, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradient of
ihfft: the real part ofs sum_k grad_k exp(-2 pi i j k / n),gradfilled with zeros fromn//2 + 1tonon the Hermitian axis, as PyTorch's backwards of_fft_r2cand the conjugate compute it.Over several axes the sums run over every transformed axis, the Hermitian axis the last. The gradient has the input's shape: +0 at the entries the forward trimmed (index
nor more on an axis), and the gradients of the entries it padded are dropped. This is PyTorch's convention,dL/dRe + i dL/dImfor a complex input and the real part for a real one; JAX'svjpat a cotangenttis the conjugate of this gradient atconj(t).The result holds the gradient by name, as every backward's:
grad_x, orgrad_Xfor ifft and irfft (result.rounded.grad_x;coverstakes{"grad_x": output}, andresult["grad_x"]is a result of its own, which can be another operation's input).gradhas the forward output's shape and kind, in any format of that kind. The input gives only its shape and format (a linear map's gradient does not depend on the input's values), and both may be earlier results. The output's format isdtype, by default the input's, of the input's kind. An integer or bool input has no gradient: a TypeError.Every part is the exact value correctly rounded once: the forward's reference applied to
grad's transform, a weighted part doubled exactly before its rounding.tolerance()bounds every implementation that computesgrad's transform as the forward's tolerance describes and then takes real parts or doubles the weighted parts, after the transform or between its axes; a weighted part's bound is twice its transform's (proofs/fft.md, Backward).JAX's gradients in this convention, conj(vjp(conj(g))), that round where this tolerance does not budget, as chains of calls whose tolerances bound them:
jnp.fft.ihfftat every norm:multiply(irfft(multiply(multiply(multiply(conj(g), inv_n), c), w), n, axis), n_r)
The names: the operations as
exactref.fftandexactref.multiplyhave them;nthe lengths (a tuple over several axes);Ntheir product andn_rthe last length, each as the real output format holds it (JAX converts a Python int to the array's format, rounding it past 2**24 in float32), andinv_nthe output format's1/non the last axis;cjnp's norm factor, as its_fft_normcomputes it in the output format (1 for None and "backward");wan array ofg's shape and format, 1 at 0 and, for evenn,n/2on the Hermitian axis, 1/2 elsewhere;conj(g)formed exactly; and for four axes or more JAX's split,innerits last two (three for five or more),outerthe others,n_innerthe inner lengths andN_innertheir product, asNis held. rfft's and ihfft's chains end inirfft, whose output has the transform's lengths: the gradient is that, +0 wherexis longer and cut where it is shorter. JAX's CPU kernels flush subnormals, so check its outputs withflush_to_zero=True(proofs/fft.md, Backward, JAX's forms).
See also#
FFT algorithms: tighter tolerances for a library whose plan is known, such as NumPy's.
Check an FFT library: a whole check, from a spectrum to a plan.
PyTorch equivalents: each
torch.fftcall and its ExactRef call.The proofs of the reference, the tolerance, the backward, JAX's forms, and the algorithms.