Module contents
Lesson 3 of 25Core 100 min

Convolution backward pass and transposed convolution

Derive convolution weight and input gradients, implement col2im as the adjoint of patch extraction, and study transposed convolutions, overlap and alternative upsampling.

After this lesson you can

  • Derive weight, bias and input gradients for multichannel correlation.
  • Implement im2col and its col2im adjoint and check gradients numerically.
  • Connect a convolution layer to a tensor autograd engine.
  • Calculate transposed-convolution output shapes and distinguish an adjoint from an inverse.
  • Analyze uneven overlap and compare upsampling approaches.

Before you start

A convolutional output reads a small input patch. In the backward pass, its gradient sends a contribution to each weight and each element of that patch. Two outputs may have read the same pixel: their contributions must be summed. This overlap is central to backward propagation and to patterns a transposed convolution can produce.

In the multichannel layer we fixed correlation without reversing the kernel. We keep that convention and, to build a layer for our tensor engine, derive the adjoint operation before comparing with PyTorch.

InteractiveFollow a contribution backward

4×4 input with x=1,…,16, correlation with w=[[1,2],[3,4]], zero bias and δ[i]=1+(i mod 3) in row order. Orange cells participate in selected connections; padding contributes zero and is not a trainable input.

Input x
Weights w
Output gradient δ
Input gradient
1
4
7
6
4
14
24
18
4
14
24
18
3
10
17
12
Weight gradient
114
132
186
204
View 4 selected contributions
  • δ[0,0]=1: to dx[0,0] adds 1×1=1; to dw[0,0] adds 1×1=1.
  • δ[0,0]=1: to dx[0,1] adds 1×2=2; to dw[0,1] adds 1×2=2.
  • δ[0,0]=1: to dx[1,0] adds 1×3=3; to dw[1,0] adds 1×5=5.
  • δ[0,0]=1: to dx[1,1] adds 1×4=4; to dw[1,1] adds 1×6=6.

For stride 1, padding 0 and dilation 1, dx is also obtained by correlating δ with the kernel flipped on both axes and using full padding. The original kernel is shown above; its reversal is:

Flipped kernel
4
3
2
1

Each connection scatters δ·w to the input and accumulates δ·x in the weight. Displayed gradients sum all outputs, not only highlighted cells; changing stride or dilation changes connections and coverage.

Select
Selectionδ[0,0] = 1
Selected forward output44
Actual connections4
Bias gradient18
Select an output or input position and trace all accumulated contributions.

What changes when a weight moves

Input XX has shape (N,Cin,H,W)(N,C_{\mathrm{in}},H,W), kernel WW has shape (Cout,Cin,kH,kW)(C_{\mathrm{out}},C_{\mathrm{in}},k_H,k_W) and XpX_p includes zero padding. For one sample, output channel and position,

Yn,o,i,j=bo+∑c,u,vWo,c,u,vXp,n,c,isH+udH,jsW+vdW.Y_{n,o,i,j}=b_o+\sum_{c,u,v} W_{o,c,u,v}X_{p,n,c,is_H+ud_H,js_W+vd_W}.

Assume a real scalar loss and write δ=∂L/∂Y\delta=\partial L/\partial Y. The chain rule sums one contribution for every use of the same parameter. Thus the filter gradient and bias gradient are

∂L∂Wo,c,u,v=∑n,i,jδn,o,i,jXp,n,c,isH+udH,jsW+vdW,∂L∂bo=∑n,i,jδn,o,i,j.\frac{\partial L}{\partial W_{o,c,u,v}}=\sum_{n,i,j}\delta_{n,o,i,j}X_{p,n,c,is_H+ud_H,js_W+vd_W},\qquad \frac{\partial L}{\partial b_o}=\sum_{n,i,j}\delta_{n,o,i,j}.

The filter is shared across positions and examples, so all are summed. Each weight’s formula can be read as correlation between input and output gradient, with spacing and dilation specified by the indices: changing stride does not permit omitting windows or inventing new weights. With groups, each filter and its sums include only channels in its group.

Toward the input: scatter and accumulate

The input gradient receives, for each forward use, the contribution

∂L∂Xp,n,c,isH+udH,jsW+vdW+=δn,o,i,jWo,c,u,v.\frac{\partial L}{\partial X_{p,n,c,is_H+ud_H,js_W+vd_W}}\mathrel{+}=\delta_{n,o,i,j}W_{o,c,u,v}.

The sum covers every output and filter coinciding at that position. Padding is a constant extension, not a parameter: afterward, crop the gradient of XpX_p to the original region. In particular, when padding is zero use explicit bounds; the slice 0:-0 is empty.

To see the reversal, take one dimension, one channel, stride one, no padding and kernel length kk:

yi=∑r=0k−1wrxi+r,∂L∂xt=∑rwr δt−r,y_i=\sum_{r=0}^{k-1}w_r x_{i+r},\qquad \frac{\partial L}{\partial x_t}=\sum_r w_r\,\delta_{t-r},

where δ\delta is zero outside its domain. This is full correlation of δ\delta with the reversed kernel under the previous lesson’s convention. With channels, each input channel sums contributions from all output channels. In an implementation expressing that correlation through another layer, channel roles are exchanged; weights must not be reversed again when passing the same tensor directly to F.conv_transpose2d, since that API already implements the adjoint of conv2d under its conventions.

If stride is greater than one, s−1s-1 zeros are inserted between consecutive samples of δ\delta in the equivalent representation, then appropriate expansion and cropping are applied. The scatter above gets the same result without constructing that intermediate tensor. Kernel dilation still determines which positions are reached.

The adjoint of patch extraction

With fixed weights and no bias, forward can be written y=Mxy=Mx. If loss changes in direction δ\delta, the identity ⟨Mx,δ⟩=⟨x,M⊤δ⟩\langle Mx,\delta\rangle=\langle x,M^\top\delta\rangle identifies input backward as M⊤δM^\top\delta. The transpose here is a property of the linear operator with fixed shapes and boundaries: bias is treated separately and does not change MM.

In the im2col representation, each column is a patch. If P=im2col⁡(X)P=\operatorname{im2col}(X) and Ymat=WmatPY_{\mathrm{mat}}=W_{\mathrm{mat}}P, then ∂L/∂P=Wmat⊤δmat\partial L/\partial P=W_{\mathrm{mat}}^\top\delta_{\mathrm{mat}} and ∂L/∂Wmat=δmatP⊤\partial L/\partial W_{\mathrm{mat}}=\delta_{\mathrm{mat}}P^\top. The col2im operation is the adjoint of patch extraction: it puts each entry of ∂L/∂P\partial L/\partial P in position and sums overlaps.

Do not confuse adjoint and inverse. Applying col2im(im2col(X)) returns the visit count multiplied elementwise by XX; an unvisited position has count zero. The inner-product test detects shape and accumulation errors without requiring a particular loss. Central differences separately check input, weight and bias gradients; use float64 and an appropriate tolerance because a tiny step in float32 can be dominated by rounding.

Lab: backward and a micro framework

The first cell defines im2col, col2im, forward and VJP. The contract uses symmetric padding, stride and dilation per axis and one group. The finite-difference test uses a linear loss on output with fixed seed; the second cell checks the adjoint identity in three geometries, including one with unvisited positions.

[ ]Backward with columnsBrowser
import numpy as np

def pair(v):
    return (v, v) if isinstance(v, int) else tuple(v)

def geometry(shape, kernel, stride=1, padding=0, dilation=1):
    n, c, h, w = shape
    kh, kw = pair(kernel); sh, sw = pair(stride)
    ph, pw = pair(padding); dh, dw = pair(dilation)
    if min(n, c, h, w, kh, kw, sh, sw, dh, dw) <= 0 or min(ph, pw) < 0:
        raise ValueError('dimensiones inválidas')
    oh = (h + 2*ph - dh*(kh-1) - 1)//sh + 1
    ow = (w + 2*pw - dw*(kw-1) - 1)//sw + 1
    if min(oh, ow) <= 0:
        raise ValueError('el núcleo no cabe')
    return n, c, h, w, kh, kw, sh, sw, ph, pw, dh, dw, oh, ow

def im2col(x, kernel, stride=1, padding=0, dilation=1):
    n,c,h,w,kh,kw,sh,sw,ph,pw,dh,dw,oh,ow = geometry(x.shape, kernel, stride, padding, dilation)
    xp = np.pad(x, ((0,0),(0,0),(ph,ph),(pw,pw)))
    cols = np.empty((c*kh*kw, n*oh*ow), dtype=x.dtype)
    for i in range(oh):
        for j in range(ow):
            patch = xp[:,:,i*sh:i*sh+dh*(kh-1)+1:dh,j*sw:j*sw+dw*(kw-1)+1:dw]
            cols[:, i*ow+j::oh*ow] = patch.reshape(n, -1).T
    return cols

def col2im(cols, shape, kernel, stride=1, padding=0, dilation=1):
    n,c,h,w,kh,kw,sh,sw,ph,pw,dh,dw,oh,ow = geometry(shape, kernel, stride, padding, dilation)
    if cols.shape != (c*kh*kw, n*oh*ow):
        raise ValueError('forma de columnas incorrecta')
    xp = np.zeros((n,c,h+2*ph,w+2*pw), dtype=cols.dtype)
    for i in range(oh):
        for j in range(ow):
            patch = cols[:, i*ow+j::oh*ow].T.reshape(n,c,kh,kw)
            xp[:,:,i*sh:i*sh+dh*(kh-1)+1:dh,j*sw:j*sw+dw*(kw-1)+1:dw] += patch
    return xp[:,:,ph:ph+h,pw:pw+w]

def conv_forward(x, weight, bias, stride=1, padding=0, dilation=1):
    out_channels, channels, kh, kw = weight.shape
    if channels != x.shape[1] or bias.shape != (out_channels,):
        raise ValueError('canales o sesgo incompatibles')
    g = geometry(x.shape, (kh,kw), stride, padding, dilation)
    n, oh, ow = g[0], g[-2], g[-1]
    cols = im2col(x, (kh,kw), stride, padding, dilation)
    out = (weight.reshape(out_channels,-1) @ cols + bias[:,None]).reshape(out_channels,n,oh,ow).transpose(1,0,2,3)
    cache = (x.shape, weight.copy(), cols.copy(), pair(stride), pair(padding), pair(dilation))
    return out, cache

def conv_backward(grad, cache):
    shape, weight, cols, stride, padding, dilation = cache
    n, cout, oh, ow = grad.shape
    expected = geometry(shape, weight.shape[2:], stride, padding, dilation)
    if (n,cout,oh,ow) != (shape[0],weight.shape[0],expected[-2],expected[-1]):
        raise ValueError('forma del gradiente incorrecta')
    g = grad.transpose(1,0,2,3).reshape(cout,-1)
    dw = (g @ cols.T).reshape(weight.shape)
    db = g.sum(axis=1)
    dx = col2im(weight.reshape(cout,-1).T @ g, shape, weight.shape[2:], stride, padding, dilation)
    return dx, dw, db

rng = np.random.default_rng(73)
x = rng.normal(size=(2,2,4,5)); w = rng.normal(size=(2,2,2,3)); b = rng.normal(size=2)
config = dict(stride=(2,1), padding=(1,0), dilation=(1,2))
y, cache = conv_forward(x,w,b,**config)
seed = rng.normal(size=y.shape)
dx,dw,db = conv_backward(seed,cache)

def finite_difference(array, evaluate, eps=1e-6):
    result = np.empty_like(array)
    for idx in np.ndindex(array.shape):
        old = array[idx]
        array[idx] = old+eps; plus = evaluate()
        array[idx] = old-eps; minus = evaluate()
        array[idx] = old
        result[idx] = (plus-minus)/(2*eps)
    return result

loss = lambda: np.sum(conv_forward(x,w,b,**config)[0]*seed)
errors = [float(np.max(np.abs(a-finite_difference(v,loss)))) for v,a in ((x,dx),(w,dw),(b,db))]
print('forma salida:', y.shape, 'errores máximos x, W, b:', errors)
assert max(errors) < 1e-7
[ ]The adjoint testBrowser
rng = np.random.default_rng(91)
for shape, kernel, stride, padding, dilation in [
    ((1,1,3,4),(2,2),1,0,1),
    ((2,2,4,5),(2,3),(2,1),(1,0),(1,2)),
    ((1,2,3,3),(1,1),2,0,1),
]:
    x = rng.normal(size=shape)
    patches = im2col(x,kernel,stride,padding,dilation)
    z = rng.normal(size=patches.shape)
    lhs = np.sum(patches*z)
    rhs = np.sum(x*col2im(z,shape,kernel,stride,padding,dilation))
    counts = col2im(np.ones_like(patches),shape,kernel,stride,padding,dilation)
    assert np.allclose(lhs,rhs,rtol=1e-12,atol=1e-12)
    assert np.allclose(col2im(patches,shape,kernel,stride,padding,dilation),counts*x)
    print('forma',shape,'diferencia adjunta',abs(lhs-rhs),'cuentas mín./máx.',counts.min(),counts.max())

The next block reproduces the full current Tensor definition from m15-l09, making this lesson self-contained. As there, backward clears intermediate gradients and accumulates in leaves: zero leaves when starting another independent evaluation.

[ ]Tensor and its vector-Jacobian productsBrowser
import numpy as np
from copy import deepcopy

def unbroadcast(grad, shape):
    grad = np.asarray(grad)
    while grad.ndim > len(shape):
        grad = grad.sum(axis=0)
    for axis, size in enumerate(shape):
        if size == 1 and grad.shape[axis] != 1:
            grad = grad.sum(axis=axis, keepdims=True)
    if grad.shape != tuple(shape):
        raise ValueError('formas incompatibles')
    return grad

class Tensor:
    def __init__(self, data, parents=(), backward=None):
        self.data = np.array(data, dtype=np.float64, copy=True)
        self.grad = np.zeros_like(self.data)
        self.parents = tuple(parents)
        self._backward = backward or (lambda: None)

    @staticmethod
    def wrap(x): return x if isinstance(x, Tensor) else Tensor(x)

    def __add__(self, other):
        other = Tensor.wrap(other)
        a_shape, b_shape = self.data.shape, other.data.shape
        out = Tensor(self.data + other.data, (self, other))
        def backward():
            self.grad += unbroadcast(out.grad, a_shape)
            other.grad += unbroadcast(out.grad, b_shape)
        out._backward = backward
        return out
    __radd__ = __add__

    def __mul__(self, other):
        other = Tensor.wrap(other)
        a, b = self.data.copy(), other.data.copy()
        out = Tensor(a*b, (self, other))
        def backward():
            self.grad += unbroadcast(out.grad*b, a.shape)
            other.grad += unbroadcast(out.grad*a, b.shape)
        out._backward = backward
        return out
    __rmul__ = __mul__
    def __neg__(self): return self * -1
    def __sub__(self, other): return self + (-Tensor.wrap(other))
    def __rsub__(self, other): return Tensor.wrap(other) - self

    def __matmul__(self, other):
        other = Tensor.wrap(other)
        a, b = self.data.copy(), other.data.copy()
        if a.ndim != 2 or b.ndim != 2:
            raise ValueError('matmul admite matrices 2D')
        out = Tensor(a @ b, (self, other))
        def backward():
            self.grad += out.grad @ b.T
            other.grad += a.T @ out.grad
        out._backward = backward
        return out

    def tanh(self):
        y = np.tanh(self.data)
        out = Tensor(y, (self,))
        out._backward = lambda: self._accumulate(out.grad*(1-y*y))
        return out
    def sigmoid(self):
        x = self.data
        y = np.exp(-np.logaddexp(0, -x))
        out = Tensor(y, (self,))
        out._backward = lambda: self._accumulate(out.grad*y*(1-y))
        return out
    def relu(self):
        mask = self.data > 0
        out = Tensor(np.maximum(self.data, 0), (self,))
        out._backward = lambda: self._accumulate(out.grad*mask)
        return out
    def exp(self):
        y = np.exp(self.data)
        out = Tensor(y, (self,))
        out._backward = lambda: self._accumulate(out.grad*y)
        return out
    def log(self):
        x = self.data.copy()
        if np.any(x <= 0): raise ValueError('log exige entrada positiva')
        out = Tensor(np.log(x), (self,))
        out._backward = lambda: self._accumulate(out.grad/x)
        return out
    def _accumulate(self, value): self.grad += value

    def sum(self, axis=None, keepdims=False):
        shape = self.data.shape
        axes = tuple(range(len(shape))) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
        axes = tuple(a % len(shape) for a in axes) if shape else ()
        out = Tensor(self.data.sum(axis=axis, keepdims=keepdims), (self,))
        def backward():
            g = out.grad
            if not keepdims:
                for a in sorted(axes): g = np.expand_dims(g, a)
            self.grad += np.broadcast_to(g, shape)
        out._backward = backward
        return out
    def mean(self, axis=None, keepdims=False):
        axes = tuple(range(self.data.ndim)) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
        count = int(np.prod([self.data.shape[a] for a in axes]))
        return self.sum(axis, keepdims) * (1.0/count)
    def max(self, axis=None, keepdims=False):
        shape = self.data.shape
        axes = tuple(range(len(shape))) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
        axes = tuple(a % len(shape) for a in axes) if shape else ()
        maxima = self.data.max(axis=axis, keepdims=True)
        mask = self.data == maxima
        counts = mask.sum(axis=axis, keepdims=True)
        out = Tensor(self.data.max(axis=axis, keepdims=keepdims), (self,))
        def backward():
            g = out.grad
            if not keepdims:
                for a in sorted(axes): g = np.expand_dims(g, a)
            self.grad += mask * (g/counts)
        out._backward = backward
        return out
    def reshape(self, *shape):
        original = self.data.shape
        out = Tensor(self.data.reshape(*shape), (self,))
        out._backward = lambda: self._accumulate(out.grad.reshape(original))
        return out
    def transpose(self, *axes):
        perm = (tuple(axes[0]) if len(axes) == 1 and isinstance(axes[0], (tuple, list))
                else tuple(axes) if axes else tuple(reversed(range(self.data.ndim))))
        transposed = self.data.transpose(perm)  # NumPy valida la permutación.
        normalized = tuple(a % self.data.ndim for a in perm) if self.data.ndim else ()
        inverse = np.argsort(normalized)
        out = Tensor(transposed, (self,))
        out._backward = lambda: self._accumulate(out.grad.transpose(inverse))
        return out
    def __getitem__(self, index):
        # También pueden mutarse listas o estructuras anidadas de índices.
        index = deepcopy(index)
        out = Tensor(self.data[index], (self,))
        def backward(): np.add.at(self.grad, index, out.grad)
        out._backward = backward
        return out
    @staticmethod
    def concat(tensors, axis=0):
        tensors = tuple(tensors)
        cuts = np.cumsum([t.data.shape[axis] for t in tensors])[:-1]
        out = Tensor(np.concatenate([t.data for t in tensors], axis=axis), tensors)
        def backward():
            for tensor, g in zip(tensors, np.split(out.grad, cuts, axis=axis)):
                tensor.grad += g
        out._backward = backward
        return out

    def backward(self, seed=None):
        if seed is None:
            if self.data.size != 1: raise ValueError('salida no escalar: proporciona semilla')
            seed = np.ones_like(self.data)
        seed = np.asarray(seed, dtype=float)
        if seed.shape != self.data.shape: raise ValueError('forma de semilla incorrecta')
        topo, seen, stack = [], set(), [(self, False)]
        while stack:
            node, done = stack.pop()
            if done: topo.append(node)
            elif node not in seen:
                seen.add(node)
                stack.append((node, True))
                stack.extend((p, False) for p in reversed(node.parents))
        for node in topo:
            if node.parents: node.grad.fill(0)
        self.grad += seed
        for node in reversed(topo): node._backward()
        return len(topo)

def cross_entropy(logits, labels):
    z = logits.data.copy()
    labels = np.asarray(labels)
    if (z.ndim != 2 or z.shape[0] == 0 or z.shape[1] == 0 or
            labels.ndim != 1 or labels.shape[0] != z.shape[0] or
            not np.issubdtype(labels.dtype, np.integer) or
            np.any(labels < 0) or np.any(labels >= z.shape[1])):
        raise ValueError('formas o etiquetas incorrectas')
    shifted = z - np.max(z, axis=1, keepdims=True)
    exp = np.exp(shifted)
    probabilities = exp/exp.sum(axis=1, keepdims=True)
    loss = np.mean(np.log(exp.sum(axis=1))-shifted[np.arange(len(labels)), labels])
    delta = probabilities.copy()
    delta[np.arange(len(labels)), labels] -= 1
    delta /= len(labels)
    out = Tensor(loss, (logits,))
    out._backward = lambda: logits._accumulate(out.grad*delta)
    return out

The layer saves copies of forward weights and columns, so the VJP refers to that calculation even if leaves are later mutated. The test compares each derivative, two calls to backward and two branches sharing parameters. In a real application, mutation between forward and backward requires an explicit policy; do not assume all frameworks automatically save complete copies.

[ ]Connect Conv2d to the engineBrowser
# La celda anterior define im2col, col2im, conv_forward y conv_backward.
# Antes de esta celda ejecuta la definición íntegra de Tensor de m15-l09.
def conv_tensor(x, weight, bias, stride=1, padding=0, dilation=1):
    y, cache = conv_forward(x.data, weight.data, bias.data, stride, padding, dilation)
    out = Tensor(y, (x,weight,bias))
    def backward():
        dx,dw,db = conv_backward(out.grad,cache)
        x.grad += dx; weight.grad += dw; bias.grad += db
    out._backward = backward
    return out

class Conv2d:
    def __init__(self, weight, bias, stride=1, padding=0, dilation=1):
        self.weight = Tensor(weight)
        self.bias = Tensor(bias)
        self.stride, self.padding, self.dilation = stride, padding, dilation

    def forward(self, x):
        return conv_tensor(x,self.weight,self.bias,self.stride,self.padding,self.dilation)

    def parameters(self):
        return [self.weight,self.bias]

rng = np.random.default_rng(14)
tx = Tensor(rng.normal(size=(1,2,4,5)))
layer = Conv2d(rng.normal(size=(2,2,2,3)),rng.normal(size=2),stride=(2,1),padding=(1,0),dilation=(1,2))
tw,tb = layer.parameters()
ty = layer.forward(tx)
seed = rng.normal(size=ty.data.shape)
_, cache = conv_forward(tx.data,tw.data,tb.data,(2,1),(1,0),(1,2))
expected = conv_backward(seed,cache)
ty.backward(seed)
for actual, target in zip((tx.grad,tw.grad,tb.grad),expected):
    assert np.allclose(actual,target)
ty.backward(seed)
for actual, target in zip((tx.grad,tw.grad,tb.grad),expected):
    assert np.allclose(actual,2*target)
for leaf in (tx,tw,tb): leaf.grad.fill(0)
left,right = layer.forward(tx),layer.forward(tx)
(left+right).backward(seed)
for actual,target in zip((tx.grad,tw.grad,tb.grad),expected):
    assert np.allclose(actual,2*target)
# El backward usa las copias del forward, incluso si se modifican las hojas.
for leaf in (tx,tw,tb): leaf.grad.fill(0)
old = layer.forward(tx)
tw.data[...] += 3
tx.data[...] -= 4
old.backward(seed)
for actual,target in zip((tx.grad,tw.grad,tb.grad),expected):
    assert np.allclose(actual,target)
print('VJP integrada, hojas compartidas y caché de forward: comprobadas')

Transposing does not mean inverting

A transposed convolution applies the transpose of the forward matrix for fixed shapes. It can increase resolution, but M⊤MM^\top M is not generally the identity. If correlation with kernel [1][1] and stride 2 transforms [a,b,c,d][a,b,c,d] into [a,c][a,c], its adjoint returns [a,0,c,0][a,0,c,0]: removed samples do not reappear.

Per axis, with symmetric padding pp, dilation dd, kernel kk, stride ss and output_padding qq, transposed length is

Lout=(Lin−1)s−2p+d(k−1)+q+1.L_{\mathrm{out}}=(L_{\mathrm{in}}-1)s-2p+d(k-1)+q+1.

The same forward output can come from several original lengths when s>1s>1: with k=3,s=2,p=1k=3,s=2,p=1, both 29 and 30 produce length 15. In the ordinary case, choosing qq between 0 and s−1s-1 selects one compatible shape; it does not recover lost samples. In PyTorch, output_padding resolves shape ambiguity and does not physically add a zero border; some dilation combinations allow values beyond that interval. The ConvTranspose2d documentation describes the operation and its shapes.

InteractiveTransposed footprints

3×3 input of ones, kernel of ones, zero padding and dilation 1. Each input adds a 3×3 footprint; each cell counts overlapping footprints. The orange border marks the selected input footprint.

Selected input
Coverage counts
1121211112121122424221121211224242211212111121211

The interior excludes k−1 cells at each border and may be empty. Uniform interior coverage does not imply uniform values with arbitrary weights, and boundaries can differ. This is overlap geometry, not an image-quality measurement.

3
2
Output side7
Minimum and maximum coverage1; 4
Cropped interior1 to 4
Count geometric contributions while changing kernel size and stride; distinguish interior and boundaries.

Overlap and checkerboards

With an all-ones kernel and constant input, each pixel’s value reflects how many footprints reach it. For k=3,s=2k=3,s=2 interior coverage values 1, 2 and 4 appear; for k=4,s=2k=4,s=2 interior coverage is uniform, though boundaries need not be. The figure counts footprints; it does not by itself predict a layer’s value with arbitrary weights.

Checkerboard artifacts can arise from uneven coverage, but uniform coverage does not force weights of different phases to produce the same response either. Odena, Dumoulin and Olah analyze both mechanisms and show patterns can also appear before training. To detect them, compare phase means in an interior region for constant input; this is a diagnostic for the example, not a complete visual-quality evaluation.

One alternative interpolates and then applies a convolution. Another computes r2r^2 channels per final channel and uses pixel shuffle to distribute them spatially:

Yn,c,ri+a,rj+b=Xn,cr2+ar+b,i,j,0≤a,b<r.Y_{n,c,ri+a,rj+b}=X_{n,cr^2+ar+b,i,j},\quad 0\le a,b<r.

The permutation creates no information and has no weights of its own; preceding filters learn. Shi and colleagues apply subpixel convolution to super-resolution and report improvements of 0.15 dB on images and 0.39 dB on video over earlier CNN methods in their published evaluations. Those results do not describe our random experiment. Bilinear interpolation requires declaring coordinate and boundary conventions. None of these options automatically removes every periodic pattern: different weights and boundary conditions can yield different responses.

InteractiveThree ways to increase resolution

Input 3×3, same pattern for all three outputs and seed 1. Blue represents positive values, orange negative; intensity uses a common scale and the selected position is outlined in black or white depending on theme.

Preparing outputs…

Model with reproducible uniform weights in [−1,1], no bias: transpose k=3, stride 2, padding 1 and output_padding 1; bilinear with align_corners=False and edge extension followed by 3×3 correlation with zero padding; pixel shuffle rearranges four channels produced by 1×1 weights. Shared 3×3 weights for the first two: [0.254, −0.995, 0.055, 0.962, 0.937, −0.438, 0.226, 0.441, −0.148]; expansion weights: [0.990, −0.089, −0.022, −0.722]. Rounded for display; calculations use full precision.

The four means use phases (row mod 2, column mod 2) in the interior, excluding one pixel per border; spread is their population standard deviation. With constant input it examines phase variation; with an impulse it also reflects spatial signal shape and does not by itself diagnose a checkerboard. The architectures have different parameterizations and one seed does not establish general superiority.

1
3
Input
Selected output0.9368
Spread of phase means0.5451
Output per method6 × 6
Compare methods on the same input and examine their responses and phase diagnostic; each method's weights and configuration are stated.

The figure uses its own model with reproducible uniform weights and a 1×1 expansion before pixel shuffle. The next lab uses different Gaussian weights and a 3×3 convolution before pixel shuffle: its results are another experiment. To interpret the figure’s phase diagnostic, start with constant input; with an impulse, dispersion also reflects input shape and does not by itself demonstrate an artifact.

Local lab: adjoint and decoders

Compare the custom scatter with autograd.grad and F.conv_transpose2d, selecting the original shape with output_padding. The code also evaluates three untrained decoders with the same input and different random weights; for the constant signal it measures dispersion of the four phase means in an interior region. Initialization and architectures do not have equal parameter counts, so the result does not universally rank methods.

[ ]Compare with PyTorch and phasesLocal GPU
import json
import numpy as np
import torch
import torch.nn.functional as F

torch.manual_seed(43)
torch.set_num_threads(1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

def transpose_from_input_vjp(delta, weight, shape, stride, padding, dilation):
    """Adjunta por dispersión; weight tiene forma (Cout, Cin, kh, kw)."""
    n, cin, h, w = shape
    cout, wc, kh, kw = weight.shape
    assert wc == cin and delta.shape[:2] == (n,cout)
    sh,sw = stride; ph,pw = padding; dh,dw = dilation
    out = np.zeros(shape,dtype=delta.dtype)
    for i in range(delta.shape[2]):
        for j in range(delta.shape[3]):
            for u in range(kh):
                for v in range(kw):
                    iy,ix = i*sh-ph+u*dh,j*sw-pw+v*dw
                    if 0 <= iy < h and 0 <= ix < w:
                        out[:,:,iy,ix] += delta[:,:,i,j] @ weight[:,:,u,v]
    return out

gen = np.random.default_rng(19)
x = gen.normal(size=(2,2,6,7))
weight = gen.normal(size=(3,2,3,2))
stride,padding,dilation = (2,2),(1,0),(1,1)
xt = torch.tensor(x,device=device,requires_grad=True)
wt = torch.tensor(weight,device=device)
y = F.conv2d(xt,wt,stride=stride,padding=padding,dilation=dilation)
delta = gen.normal(size=tuple(y.shape))
dt = torch.tensor(delta,device=device)
dx_autograd, = torch.autograd.grad(y,xt,dt)
# 6 y 7 son las dimensiones originales que selecciona este output_padding.
base = tuple((y.shape[2+i]-1)*stride[i]-2*padding[i]+dilation[i]*(weight.shape[2+i]-1)+1 for i in range(2))
output_padding = tuple(x.shape[2+i]-base[i] for i in range(2))
dx_torch = F.conv_transpose2d(dt,wt,stride=stride,padding=padding,dilation=dilation,output_padding=output_padding)
dx_own = transpose_from_input_vjp(delta,weight,x.shape,stride,padding,dilation)
err_own = float(np.max(np.abs(dx_own-dx_autograd.cpu().numpy())))
err_torch = float((dx_torch-dx_autograd).abs().max().item())
assert err_own < 1e-11 and err_torch < 1e-11
dot_error = abs(float(np.sum(y.detach().cpu().numpy()*delta)-np.sum(x*dx_own)))
assert dot_error < 1e-10

# Decodificadores distintos, aleatorios y sin entrenar: misma imagen y misma
# desviación de inicialización, sin afirmar igualdad de parámetros ni calidad.
torch.manual_seed(73)
image = torch.ones((1,1,8,8),device=device)
image[0,0,2:6,2:6] = 0.5
constant = torch.ones_like(image)
wt_trans = torch.randn((1,1,3,3),device=device)*0.2
wt_resize = torch.randn((1,1,3,3),device=device)*0.2
wt_shuffle = torch.randn((4,1,3,3),device=device)*0.2
def decode(z):
    return {
        'transpuesta': F.conv_transpose2d(z,wt_trans,stride=2,padding=1,output_padding=1),
        'bilineal_conv': F.conv2d(F.interpolate(z,scale_factor=2,mode='bilinear',align_corners=False),wt_resize,padding=1),
        'pixel_shuffle': F.pixel_shuffle(F.conv2d(z,wt_shuffle,padding=1),2),
    }
def phase_score(z):
    # El borde se excluye; puntuación absoluta, no dividida por una media casi cero.
    core = z[0,0,2:-2,2:-2]
    means = torch.stack([core[a::2,b::2].mean() for a in range(2) for b in range(2)])
    return float(((means-means.mean())**2).mean().sqrt().item()), means.cpu().tolist()

scores = {}
for name, output in decode(constant).items():
    score, means = phase_score(output)
    scores[name] = {'contraste_fases_constante':score,'medias_fase':means}
assert all(v.shape == (1,1,16,16) and torch.isfinite(v).all() for v in decode(image).values())
# Mismo reordenamiento que el ejercicio; contraste con las clases de PyTorch.
sample = np.arange(2*12*4*10, dtype=np.float64).reshape(2,12,4,10)[:,:,:,::2]
n, ch, h, w = sample.shape
r = 2
shuffled = sample.reshape(n,ch//(r*r),r,r,h,w).transpose(0,1,4,2,5,3).reshape(n,ch//(r*r),h*r,w*r)
torch_shuffled = torch.nn.PixelShuffle(r)(torch.from_numpy(sample)).numpy()
assert np.array_equal(shuffled,torch_shuffled)
view = np.asfortranarray(shuffled)
n, ch, h, w = view.shape
unshuffled = view.reshape(n,ch,h//r,r,w//r,r).transpose(0,1,3,5,2,4).reshape(n,ch*r*r,h//r,w//r)
torch_unshuffled = torch.nn.PixelUnshuffle(r)(torch.from_numpy(view)).numpy()
assert np.array_equal(unshuffled,torch_unshuffled) and np.array_equal(unshuffled,sample)
print('PixelShuffle/PixelUnshuffle: paridad exacta y vistas no contiguas;', sample.shape, 'a', shuffled.shape)
print(json.dumps({'device':str(device),'output_padding':output_padding,
                  'error_own':err_own,'error_torch':err_torch,'error_adjunto':dot_error,
                  'semilla_decoder':73,'scores':scores},ensure_ascii=False,indent=2,allow_nan=False))
if device.type == 'cuda':
    del xt,wt,y,dt,dx_autograd,dx_torch,image,constant,wt_trans,wt_resize,wt_shuffle
    torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofDerive the input gradient
Prove: Prove that the input gradient of valid 1D correlation with stride one is full correlation with the reversed kernel.
0
Take x of length L, w of length k≤L, yᵢ=Σᵣwᵣxᵢ₊ᵣ and δᵢ=∂L/∂yᵢ; extend δ with zeros outside its indices.

Step 1 of 2. What does yᵢ contribute to the gradient of xₜ?

CodeSum the patches
Implement col2im(cols, input_shape, k, stride, padding), the adjoint of NCHW patch extraction with symmetric zero padding, square k×k kernel, equal stride per axis and dilation one. input_shape=(N,C,H,W) contains positive integers; k and stride are positive integers and padding a nonnegative integer, none bool. Matrix cols has integer or real dtype and shape (C·k·k, N·Hout·Wout); within each column the order is channel, row, column and columns traverse batch, output row and column. Reject invalid parameters, dtype, shape or a kernel that does not fit with ValueError. Sum, do not overwrite, coincident contributions and return NCHW with the dtype of cols; integers may overflow according to that dtype.
import numpy as np

def col2im(cols, input_shape, k, stride, padding):
  pass
Shift+Enter to run
NumericShape with kernel four
Per axis, what is the output length of a transpose with input 16, kernel 4, stride 2, padding 1, dilation 1 and output_padding 0?
NumericA second compatible shape
Per axis, what is the output length if input is 16, kernel 3, stride 2, padding 1, dilation 1 and output_padding 1?
QuizDoes the checkerboard disappear?
With constant input, an all-ones kernel, dilation one and stride 2 on both axes, what can be said about interior geometric coverage?
CodeReorder and invert
Implement pixel_shuffle(x,r) and pixel_unshuffle(y,r) for nonempty 4D NCHW arrays and positive integer r, excluding bool. For shuffle require C divisible by r²; for unshuffle require H and W divisible by r. Use order Y[n,c,r·i+a,r·j+b]=X[n,c·r²+a·r+b,i,j]. Preserve dtype and reject invalid inputs with ValueError. It must also work with noncontiguous views.
import numpy as np

def pixel_shuffle(x, r):
  pass

def pixel_unshuffle(y, r):
  pass
Shift+Enter to run
[ ]Check the example calculationsBrowser
import numpy as np
x=np.array([1.,2.,3.,4.]); w=np.array([2.,-1.,3.]); delta=np.array([4.,5.])
y=np.array([x[i:i+3]@w for i in range(2)])
dx=np.zeros_like(x)
for i in range(2): dx[i:i+3]+=delta[i]*w
dw=np.array([sum(delta[i]*x[i+r] for i in range(2)) for r in range(3)])
print('y:',y,'dx:',dx,'dw:',dw,'db:',delta.sum())
print('Producto escalar, error:',abs(y@delta-x@dx))
print('Dos longitudes de entrada para la misma salida:', [(n,(n+2-3)//2+1) for n in (29,30)])
print('Formas transpuestas:',(16-1)*2-2+4,(16-1)*2-2+3+1)
for k in (3,4):
    coverage=np.zeros(((4-1)*2+k,)*2,dtype=int)
    for i in range(4):
        for j in range(4): coverage[2*i:2*i+k,2*j:2*j+k]+=1
    print('Coberturas interiores k=',k,':',np.unique(coverage[2:-2,2:-2]))

References