convolution#
A convolution slides a small kernel over an input. At each position it adds up the products of the kernel's weights with the input values under it, over every input channel. It is the working layer of image and audio models: ResNet's 3 by 3 layers, a vision transformer's patch embedding, and a speech model's first layer.
In ExactRef, er.convolution(input, weight, bias=None, *, stride=1, padding=0, dilation=1, groups=1, transposed=False, output_padding=0), also
er.nn.conv.convolution, is torch.nn.functional.conv1d, conv2d, and
conv3d in one function, for any number of spatial dimensions. With
transposed=True it is their conv_transpose forms. input is (batch,
channels, spatial dimensions), and weight is (output channels, input
channels per group, kernel). It takes real floating-point formats.
Each output element is the exact sum of its products plus its bias, rounded once: the reference. A position in the padding is an exact zero.
The tolerance covers an implementation that adds an output's products one at a time in the compute format. Each product is rounded on its own or fused into its addition, as a fused multiply-add does, and the bias is added first or last. Kernels take the products in different orders. The two common orders, a channel at a time or a kernel position at a time, both count as normal accumulation here:
One output's products, as a grid of input channels by kernel positions.
tolerance(standard="any_order") covers any order at all, which blocked,
transposed, and some grouped kernels need. normal() returns the channel-major answer,
the order of the weight's own layout.
Arguments#
Argument |
Meaning |
Default |
|---|---|---|
|
(batch, channels, spatial dimensions), a real floating-point format |
required |
|
(output channels, input channels / groups, kernel); for the transposed form (input channels, output channels / groups, kernel) |
required |
|
one value per output channel, or None |
|
|
the step between outputs: an int, or one per spatial dimension |
|
|
the zeros added on both sides of each spatial dimension: an int, or one per spatial dimension |
|
|
the spacing between kernel positions: an int, or one per spatial dimension |
|
|
the number of groups the channels are split into; as many groups as channels is a depthwise convolution |
|
|
the transposed convolution |
|
|
the transposed form's extra size on the far side: an int, or one per spatial dimension |
|
|
the output format, a floating-point format |
the operands' promoted format |
|
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 |
PyTorch's padding="valid" is padding=0. Its padding="same" is
dilation * (kernel - 1) / 2 on each side, where that is a whole number.
Otherwise, and for padding modes other than zeros (reflect, replicate, and
circular), pad the input first and pass padding=0.
With flush_to_zero=True, an operand promoted to a wider format is read by
its own format: its values below that format's smallest normal number, or
float32's for a narrower format, may be zeros
(flushing).
Examples#
A 3 by 3 layer of ResNet-50's first stage takes 64 channels to 64 on a 56 by 56 feature map. Each output is a sum of 576 products:
import torch
import torch.nn.functional as F
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The layer's input after a ReLU, and its weight at He initialization's scale
x = torch.relu(torch.randn(1, 64, 56, 56, generator=g))
w = torch.randn(64, 64, 3, 3, generator=g) * (2 / 576) ** 0.5
# ExactRef's result for the layer, which has no bias
r = er.convolution(x, w, padding=1)
print("shape:", r.rounded.shape)
# Could a correct implementation produce PyTorch's output?
print("covered:", r.covers(F.conv2d(x, w, padding=1)).all())
shape: (1, 64, 56, 56)
covered: True
Stride and one dimension#
A speech model's first layer is a strided 1-D convolution. wav2vec 2.0 takes one channel of 16 kHz audio to 512 channels with a kernel of 10 and a stride of 5:
# One second of 16 kHz audio, and the layer's 512 filters
audio = torch.randn(1, 1, 16000, generator=g)
filters = torch.randn(512, 1, 10, generator=g) * (1 / 10) ** 0.5
ra = er.convolution(audio, filters, stride=5)
print("shape:", ra.rounded.shape)
print("covered:", ra.covers(F.conv1d(audio, filters, stride=5)).all())
shape: (1, 512, 3199)
covered: True
Transposed convolutions#
A transposed convolution upsamples. A U-Net decoder doubles a 64 by 64 map
of 128 channels into a 128 by 128 map of 64 channels, with a 2 by 2 kernel
and a stride of 2. Its kernels add the products in an order of their own,
so check it with standard="any_order":
# The decoder's input, and the up-convolution's weight and bias
low = torch.randn(1, 128, 64, 64, generator=g)
up = torch.randn(128, 64, 2, 2, generator=g) * (1 / 512) ** 0.5
up_bias = torch.randn(64, generator=g) * 0.1
rt = er.convolution(low, up, up_bias, stride=2, transposed=True)
print("shape:", rt.rounded.shape)
out = F.conv_transpose2d(low, up, up_bias, stride=2)
print("covered in any order:", rt.covers(out, standard="any_order").all())
shape: (1, 64, 128, 128)
covered in any order: True
Kernels that do not sum the products#
Winograd's method and FFT convolutions transform the input and the kernel, multiply the transformed values, and transform back. They round the transformed values, which no order of the sum does, so a few of their outputs can lie outside even the any-order tolerance. No tolerance here allows for that. PyTorch's macOS builds for Apple silicon compute a float32 depthwise 3 by 3 layer without stride or dilation by Winograd's method when no gradient is needed.
Special values#
Infinities and NaN follow IEEE rules on each exact sum, and a padded position is a product with an exact zero. So an infinite weight gives NaN at the outputs where it meets the padding:
inf = float("inf")
# A 4 by 4 input of ones, and a 3 by 3 kernel of ones with an infinite corner
ones = torch.ones(1, 1, 4, 4)
corner = torch.ones(1, 1, 3, 3)
corner[0, 0, 0, 0] = inf
rs = er.convolution(ones, corner, padding=1).rounded.tolist()[0][0]
# The corner tap reads the padding in the first row and in the first column
print("first row:", rs[0])
print("second row:", rs[1])
first row: [nan, nan, nan, nan]
second row: [nan, inf, inf, inf]
Backward#
er.convolution.backward(input, weight, bias, grad, *, stride=1, ...), or
r.backward(grad), takes the forward's arguments and returns grad_input,
grad_weight, and, with a bias, grad_bias. Each element is one exact sum
rounded once. PyTorch's backward kernels add each gradient's terms in
orders of their own, so check them with standard="any_order":
# The gradient of the layer's output
gy = torch.randn(1, 64, 56, 56, generator=g)
# PyTorch's autograd, on copies that record gradients
x_, w_ = x.clone().requires_grad_(), w.clone().requires_grad_()
F.conv2d(x_, w_, padding=1).backward(gy)
# ExactRef's gradients, held by name
gb = er.convolution.backward(x, w, None, gy, padding=1)
print("outputs:", list(gb.rounded))
print("grad_input covered:", gb["grad_input"].covers(x_.grad, standard="any_order").all())
print("grad_weight covered:", gb["grad_weight"].covers(w_.grad, standard="any_order").all())
outputs: ['grad_input', 'grad_weight']
grad_input covered: True
grad_weight covered: True
Full specification#
er.convolution#
- convolution(input, weight, bias=None, *, stride=1, padding=0, dilation=1, groups: int = 1, transposed: bool = False, output_padding=0, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The convolution of
input(batch, channels, then any number of spatial dimensions) withweight(output channels, input channels per group, then the kernel), plusbiasper output channel:torch.nn.functional.conv1d,conv2dandconv3d, and withtransposedtheirconv_transposeforms, whose weight is (input channels, output channels per group, kernel).stride,padding(with zeros, on both sides),dilationandoutput_padding(the transposed form's) are an int or one int per spatial dimension. Each output element is the exact sum of its products plus its bias, rounded once todtype(default: the operands' promoted format). Real floating-point formats. An exact zero output is +0 (-0 when rounding toward -inf).tolerance()bounds an implementation that adds an output's products one at a time in the compute format, each rounded or fused into its addition, and the bias first or last. By default the products are added in either nesting of the loops, over the input channels and then the kernel positions or the other way round, and the tolerance is the wider of the two at each output;standard="any_order"allows any order, as blocked and transposed kernels need.normal()adds them channel by channel, in the weight's own layout. A padded position is a product with an exact zero. The operands may also be earlier results. Another padding mode, or padding that differs between the two sides, is a pad first. Proof:proofs/convolution.md.
er.convolution.backward#
- backward(input, weight, bias, grad, *, stride=1, padding=0, dilation=1, groups: int = 1, transposed: bool = False, output_padding=0, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradients of
convolution(input, weight, bias, ...)for the output gradientgrad.grad_inputisgradspread back through the weights (the transposed contraction, or for a transposed convolution the plain one),grad_weighteach input window timesgradsummed over the batch and the positions, andgrad_bias(with a bias)gradsummed over the batch and the positions; each element is one exact sum rounded once, in its operand's shape and dtype.gradmust have the output's shape.
See also#
PyTorch equivalents:
conv1d,conv2d,conv3d, and their transposed forms.