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.
What changes when a weight moves
Input has shape , kernel has shape and includes zero padding. For one sample, output channel and position,
Assume a real scalar loss and write . The chain rule sums one contribution for every use of the same parameter. Thus the filter gradient and bias gradient are
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
The sum covers every output and filter coinciding at that position. Padding is a constant extension, not a parameter: afterward, crop the gradient of 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 :
where is zero outside its domain. This is full correlation of 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, zeros are inserted between consecutive samples of 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 . If loss changes in direction , the identity identifies input backward as . The transpose here is a property of the linear operator with fixed shapes and boundaries: bias is treated separately and does not change .
In the im2col representation, each column is a patch. If and , then and . The col2im operation is the adjoint of patch extraction: it puts each entry of in position and sums overlaps.
Do not confuse adjoint and inverse. Applying col2im(im2col(X)) returns the visit count multiplied elementwise by ; 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.
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-7rng = 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.
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 outThe 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.
# 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 is not generally the identity. If correlation with kernel and stride 2 transforms into , its adjoint returns : removed samples do not reappear.
Per axis, with symmetric padding , dilation , kernel , stride and output_padding , transposed length is
The same forward output can come from several original lengths when : with , both 29 and 30 produce length 15. In the ordinary case, choosing between 0 and 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.
Overlap and checkerboards
With an all-ones kernel and constant input, each pixel’s value reflects how many footprints reach it. For interior coverage values 1, 2 and 4 appear; for 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 channels per final channel and uses pixel shuffle to distribute them spatially:
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.
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.
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()npm run lab and open the connection link.Exercises
Step 1 of 2. What does yᵢ contribute to the gradient of xₜ?
import numpy as np
def col2im(cols, input_shape, k, stride, padding):
passimport numpy as np
def pixel_shuffle(x, r):
pass
def pixel_unshuffle(y, r):
passimport 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]))