Module contents
Lesson 4 of 25Core 95 min

Why convolutions: locality, weight sharing, equivariance and pooling

Study locality, shared weights, translation equivariance and invariance, pooling gradients and aliasing, with controlled browser and local experiments.

After this lesson you can

  • Distinguish locality and shared weights and compare parameter counts.
  • Characterize linear translation-equivariant operators on a circular grid.
  • Implement pooling and derive its backward pass, including overlapping windows and ties.
  • Explain how stride and boundaries affect equivariance and how filtering changes aliasing.
  • Measure classification consistency and accuracy under shifts separately.

Before you start

An object can move in an image without changing category. If a layer detects an edge, we want to understand whether its response moves with it; if a classifier chooses a label, we also care when the decision remains unchanged. These are different properties, and neither is guaranteed for a complete CNN merely by using convolutions.

Compare the two paths in the figure: translate the input and then apply the operator, or apply the operator and translate its result. Also change the boundary rule and observe where a difference appears.

InteractiveTwo paths for the same shift

A synthetic 5×5 image shifts by whole pixels. Blue and orange represent positive and negative values; all images use the same intensity scale. The frame marks the same coordinate in each.

Preparing paths…

Box and Sobel are 3×3 correlations with stride 1. Dense uses A[i,j]=(((7i+11j) mod 17)−8)/425, without bias; this fixed example is not a property of all dense matrices. RMS compares all 25 positions including edges. With circular extension, correlations commute with translation; zero padding can break equality near edges.

1
0
Border
Difference RMS0.00000
Apply after shifting0.2778
Shift after applying0.2778
Equality depends on the operator, shift and boundary treatment.

Locality and shared parameters

Locality and weight sharing are distinct constraints. A local layer connects each output to a patch but could learn a different filter at each position. Convolution uses the same filter at every position for each output channel. A dense matrix can express those same sparse repeated weights, but also many other connections. Restricting the function family is an inductive bias: it helps when the symmetry matches the data, but does not by itself guarantee generalization.

When comparing counts, always include biases, groups and boundary treatment. In an unshared local layer, an output location with Cink2C_{\mathrm{in}}k^2 inputs has that many weights plus a bias; each location and output channel has separate parameters. An ungrouped convolution has only one set per output channel, regardless of position count. A dense layer from an image to a full output map learns one weight for every input-output pair. In the exercises you will calculate a concrete example of all three counts.

What commuting with a translation means

Let TaT_a be a circular translation by aa positions. A mapping FF is translation equivariant if F(Tax)=TaF(x)F(T_a x)=T_a F(x) for the declared input and output actions. It is invariant if output stays unchanged, F(Tax)=F(x)F(T_a x)=F(x). A layer that shifts its map is not therefore invariant. Transformations on an infinite or circular domain avoid losing boundary pixels; with zero padding and cropping equality can fail there.

Circular convolution is equivariant because changing the order of summation and translation does not change relative positions. The converse also holds for linear operators on a finite circular grid. In Z/nZ\mathbb Z/n\mathbb Z, let TT be a one-position shift and e0e_0 an impulse. If AT=TAA T=T A, define h=Ae0h=Ae_0. Since ej=Tje0e_j=T^j e_0,

Aej=ATje0=TjAe0=Tjh,Ax=∑jxjTjh.Ae_j=AT^j e_0=T^jAe_0=T^j h,\qquad Ax=\sum_j x_j T^j h.

This is circular convolution with hh and proves the characterization in both directions. The argument extends to a two-dimensional circular grid and multiple channels with one kernel per channel pair. Locality does not follow from the theorem: hh can occupy the whole domain. An equivariant affine mapping can add a spatially constant bias for each channel. In other groups the action convention and composition order matter.

ReLU applied equally at each position commutes with a spatial permutation. Stride-one max pooling also commutes with translations under compatible boundaries. With stride ss, an input shift that is a multiple of ss corresponds to an integer shift on the output grid; for one pixel that same integer shift generally does not exist. Per-channel BatchNorm also commutes with spatial permutations if statistics and state are handled consistently; this does not extend the conclusion to zero-filled crops.

Pooling: values and derivatives

Pooling summarizes each window without learning a filter. Max retains the largest value and average retains the mean. Without padding and with a k×kk\times k window, backward sends the max output gradient to the argmax and distributes δ/k2\delta/k^2 to each input for average pooling. If windows overlap, their contributions must be summed. With padding, separately state whether it enters the average divisor and how fictitious positions are excluded from max: an added zero must not beat all negative values in a window.

InteractiveTrace the pooling gradient

2×2 pooling without padding, δ=1 at every output. Orange shows gradient destinations for the selected window; the final grid accumulates contributions from all windows. Select an input or output by clicking it.

Input
Output
Accumulated gradient
0
1
1
0
0
0
0
0
0
0
1
0
0
1
0
0

Window (0, 0): [1, 4, 3, 4]. Contributes 1.00 to (0, 1).

For maximum, a tie selects the first maximum in row order: a valid subgradient, not a unique derivative. Average distributes 1/4 to each input. At stride 1 windows overlap and their contributions add.

Pooling
Stride
1
Selected output4.00
Total gradient of selected input0.00
Destinations of this window1
Edit the input and follow distribution for max and average, including overlaps and ties.

At a tie, the maximum has no unique derivative. For the maximum itself, assigning coefficient one to one maximum is a valid subgradient; distributing nonnegative coefficients summing to one among them is also valid but represents another policy. Backward multiplies the chosen coefficients by the incoming gradient, which may be negative. Our implementation chooses the first argmax in reading order and checks it separately. Centered finite differences check derivatives where the maximum is unique; they do not justify a unique derivative at a tie.

Global average pooling averages each entire map: (N,C,H,W)→(N,C)(N,C,H,W)\to(N,C) and each position’s gradient is δ/(HW)\delta/(HW). If the map is circularly permuted, its mean does not change: output has trivial action and is invariant to that permutation. The preceding architecture may already have lost equivariance at boundaries or subsampling. GAP discards position and order, useful for a global label but potentially harmful for object localization. Network In Network uses global average pooling as part of its architecture.

A dense layer from CC channels to KK classes after GAP has CK+KCK+K parameters with bias; flattening H×W×CH\times W\times C first and connecting to KK outputs requires HWCK+KHWCK+K. The latter can assign different weights to positions. Averaging does not make a network invariant to arbitrary rotations, scales or crops.

Stride, aliasing and filtering

Subsampling takes one phase of a signal and can confuse high frequencies with low ones. A one-pixel shift changes which phase is retained. To filter before reducing, Zhang separates, for example, a dense sliding maximum from reduction and places a low-pass filter between them: MaxBlurPool. The 2D binomial filter with three coefficients per axis is the outer product of [1,2,1]/4[1,2,1]/4 with itself. Boundary and sampling phase must be stated.

Filtering reduces certain variations and also attenuates detail. It does not exactly eliminate all aliasing or restore perfect equivariance for every input; the cell presents one circular example. To evaluate a classifier, Zhang’s consistency compares whether predictions of two shifted crops of the same image agree. It is not accuracy against the label and does not automatically equal probability of the correct class.

In Zhang’s table 6, baseline ResNet18 achieves 69.74% accuracy and 85.11% consistency; Bin-5 achieves 71.38% and 88.25% respectively under that work’s protocol. The antialias architecture is trained as such: inserting a filter into a checkpoint without retuning asks a different comparison. Figures from a small local sample, other weights or other preprocessing do not directly replicate that table.

InteractivePrediction and shift

Real ImageNet validation image: toy poodle, class 265, record 20473. The browser shows prerecorded data; it does not run the network. The 224×224 crop shifts horizontally over the 256×256 image.

Preparing curves…

The vertical scale fits the three image curves. These are independently pretrained checkpoints: standard torchvision ResNet18 and Zhang repository antialias ResNet18. The third arm adds a filter to the antialias checkpoint’s first stride without retuning; it is not retrained.

Short run: 10 images and 80 crop pairs; the same eight shift pairs are reused for each image, so these are not 80 independent observations. Pair top-1 consistency in legend order: 88.75 %, 90.00 %, 85.00 %. Mean true-label probability deviation: 0.0186, 0.0217, 0.0168. These are different metrics; these samples do not guarantee smoothing or universal improvement.

0
Model for readouts
True-label probability50.08 %
Top-1 index265
Does top-1 match label?Yes
Deviation across 9 crops0.0426
Compare predictions and true-label probabilities on shifted crops; curves come from an identified run.

In our short run, ten images were selected without replacement from the first half of the ImageNet validation set, served by a mirror with images resized to 256×256. Baseline ResNet18 and Bin-5 use independently pretrained weights and are compared on the same eight pairs of shifted crops per image. The eight shift pairs are generated once and reused across all images: 80 comparisons are not 80 independent observations. Consistency was 88.75% for baseline and 90% for Bin-5; center-crop accuracy was 50% and 60% respectively. Mean standard deviation of true-label probability across nine horizontal crops rose from 0.018623 to 0.021700: it increased for this particular measure. The official Bin-5 checkpoint does not filter the first stride of the initial convolution; we added a third arm that filters it too, using the same checkpoint without retuning. That arm achieved 85% consistency, 50% center accuracy and 0.016776 deviation. These are ten images, not evidence of a universal trend. Mirror, prior resizing, weights and crops differ from the paper table’s protocol and results.

Beyond translations, equivariance to rotation or reflection is not guaranteed by standard convolution. Augmentation supplies transformed examples during training but does not force exact equality for all inputs; Cohen and Welling’s G-CNNs construct equivariant layers for declared symmetry groups. Group, domain and boundary choices still matter.

Browser lab

We reproduce the current Tensor engine definition from m15-l09 and add MaxPool2d, AvgPool2d and GlobalAvgPool without padding. Each cell needs the preceding ones. Forward saves the maximum selection; backward accumulates in leaves, so clear them before 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
[ ]Build pooling layersBrowser
import numpy as np

def pool2d(x, kernel, stride, mode):
    """NCHW sin padding; máximo toma el primer argmax de cada ventana."""
    if mode not in ('max','avg') or not isinstance(kernel,int) or not isinstance(stride,int) or min(kernel,stride)<1:
        raise ValueError('configuración inválida')
    n,c,h,w = x.data.shape
    oh=(h-kernel)//stride+1; ow=(w-kernel)//stride+1
    if min(oh,ow)<1: raise ValueError('ventana no cabe')
    source=x.data.copy()
    values=np.empty((n,c,oh,ow))
    indices=np.empty((n,c,oh,ow),dtype=int) if mode=='max' else None
    for i in range(oh):
        for j in range(ow):
            patch=source[:,:,i*stride:i*stride+kernel,j*stride:j*stride+kernel].reshape(n,c,-1)
            if mode=='max':
                indices[:,:,i,j]=patch.argmax(axis=-1)
                values[:,:,i,j]=patch.max(axis=-1)
            else:
                values[:,:,i,j]=patch.mean(axis=-1)
    out=Tensor(values,(x,))
    def backward():
        dx=np.zeros_like(source)
        for i in range(oh):
            for j in range(ow):
                if mode=='avg':
                    dx[:,:,i*stride:i*stride+kernel,j*stride:j*stride+kernel] += out.grad[:,:,i,j,None,None]/(kernel*kernel)
                else:
                    for a in range(n):
                        for b in range(c):
                            u,v=divmod(indices[a,b,i,j],kernel)
                            dx[a,b,i*stride+u,j*stride+v] += out.grad[a,b,i,j]
        x.grad += dx
    out._backward=backward
    return out

class MaxPool2d:
    def __init__(self,kernel,stride): self.kernel,self.stride=kernel,stride
    def forward(self,x): return pool2d(x,self.kernel,self.stride,'max')

class AvgPool2d:
    def __init__(self,kernel,stride): self.kernel,self.stride=kernel,stride
    def forward(self,x): return pool2d(x,self.kernel,self.stride,'avg')

class GlobalAvgPool:
    def forward(self,x):
        if x.data.ndim!=4 or x.data.shape[2]==0 or x.data.shape[3]==0:
            raise ValueError('se requiere NCHW con espacio no vacío')
        n,c,h,w=x.data.shape
        out=Tensor(x.data.mean(axis=(2,3)),(x,))
        def backward(): x.grad += np.broadcast_to(out.grad[:,:,None,None]/(h*w),(n,c,h,w))
        out._backward=backward
        return out
[ ]Check gradients and tiesBrowser
rng=np.random.default_rng(72)
source=rng.normal(size=(2,2,4,5))
seed=rng.normal(size=(2,2,3,4))
for cls in (MaxPool2d,AvgPool2d):
    x=Tensor(source); y=cls(2,1).forward(x); y.backward(seed)
    numerical=np.zeros_like(source); eps=1e-6
    for idx in np.ndindex(source.shape):
        a=source.copy(); b=source.copy(); a[idx]+=eps; b[idx]-=eps
        numerical[idx]=(np.sum(cls(2,1).forward(Tensor(a)).data*seed)-np.sum(cls(2,1).forward(Tensor(b)).data*seed))/(2*eps)
    error=float(np.max(np.abs(x.grad-numerical)))
    print(cls.__name__,'gradcheck error máximo:',error)
    assert error < 1e-7
    y.backward(seed)
    assert np.allclose(x.grad,2*numerical,atol=1e-7)

x=Tensor(np.array([[[[4.,4.],[1.,0.]]]]))
y=MaxPool2d(2,2).forward(x); y.backward(np.array([[[[3.]]]]))
assert np.array_equal(x.grad,np.array([[[[3.,0.],[0.,0.]]]]))
print('empate: primer máximo recibe gradiente',x.grad.ravel())

x=Tensor(source); y=GlobalAvgPool().forward(x)
seed=rng.normal(size=y.data.shape); y.backward(seed)
assert np.allclose(x.grad,seed[:,:,None,None]/20)
print('GAP: forma',y.data.shape,'y gradiente uniforme comprobados')

The following cell checks circular commutation and compares max pooling with and without filtering for one signal. The distance compares two phases on the same output grid; it does not aim to establish a universal bound.

[ ]One translation and two phasesBrowser
import numpy as np
rng=np.random.default_rng(53)
x=rng.normal(size=(8,8)); kernel=rng.normal(size=(3,3))
def corr_circular(a,k):
    return sum(k[i,j]*np.roll(a,(1-i,1-j),axis=(0,1)) for i in range(3) for j in range(3))
shift=lambda a: np.roll(a,(1,2),axis=(0,1))
y=corr_circular(x,kernel)
err=np.max(np.abs(corr_circular(shift(x),kernel)-shift(y)))
print('error equivariancia circular stride 1:',err)
assert err<1e-12

def dense_max(a):
    return np.maximum.reduce([a,np.roll(a,-1,0),np.roll(a,-1,1),np.roll(a,(-1,-1),(0,1))])
def blur(a):
    return sum(q*r*np.roll(a,(i-1,j-1),(0,1))/16 for i,q in enumerate((1,2,1)) for j,r in enumerate((1,2,1)))
# Repetición horizontal de la señal de Zhang: ejemplo definido, no teorema universal.
one=np.array([0.,0.,1.,1.,0.,0.,1.,1.])
image=np.tile(one,(8,1)); shifted=np.roll(image,1,axis=1)
plain=[dense_max(a)[::2,::2] for a in (image,shifted)]
filtered=[blur(dense_max(a))[::2,::2] for a in (image,shifted)]
err_plain=float(np.linalg.norm(plain[0]-plain[1])); err_blur=float(np.linalg.norm(filtered[0]-filtered[1]))
print('distancia fase max:',err_plain,'max+blur:',err_blur)
assert err_blur < err_plain

Local lab: consistency and accuracy

The lab uses a baseline and Bin-5 variant with independently pretrained weights, plus a third arm modifying the Bin-5 checkpoint’s first stride without retuning. It applies the same images and crop pairs to all three and calculates pair consistency and center accuracy separately. Consistency can rise while accuracy falls, or vice versa. Record weights, transform, image source, offsets and example count: a small diagnostic does not demonstrate superiority on the full distribution.

[ ]Measure shifts with ResNet18Local GPU
"""Consistencia por pares de recortes, usando validación ImageNet etiquetada.

Requisitos: torch, torchvision, antialiased-cnns==0.3, huggingface_hub,
pyarrow, pillow y numpy. Descargas en las cachés habituales de Torch/HF.
ORYON_VERIFY_SHORT=1 usa 10 imágenes; el modo lector usa 100.
"""
import base64
import copy
import hashlib
import io
import json
import os
from pathlib import Path
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
from PIL import Image
import torch
from torchvision.models import ResNet18_Weights, resnet18
from torchvision.transforms import functional as TF
import antialiased_cnns

torch.set_num_threads(1)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
short=os.environ.get('ORYON_VERIFY_SHORT')=='1'
count=10 if short else 100
rng=np.random.default_rng(20261102)
path=hf_hub_download(repo_id='benjamin-paine/imagenet-1k-256x256',repo_type='dataset',
    filename='data/validation-00000-of-00002.parquet',revision='1bd0400450249a7fe90c0aece37d0d03e7ea956a')
table=pq.read_table(path)
metadata=json.loads(table.schema.metadata[b'huggingface'])
names=metadata['info']['features']['label']['names']
labels=table.column('label').to_numpy()
indices=rng.choice(np.flatnonzero(labels<1000),size=count,replace=False).tolist()
selected=table.take(pa.array(indices)).to_pylist()
categories=ResNet18_Weights.IMAGENET1K_V1.meta['categories']
# El espejo usa el orden canónico de 1000 clases de ImageNet; el índice 1000 es «none».
assert len(names)==1001 and names[0].startswith('tench') and categories[0]=='tench'
assert names[217].startswith('English springer') and categories[217]=='English springer'

baseline=resnet18(weights=ResNet18_Weights.IMAGENET1K_V1).to(device).eval()
antialias=antialiased_cnns.resnet18(pretrained=True,filter_size=5).to(device).eval()
# La versión oficial deja conv1 con stride 2. Este tercer brazo inserta
# también un filtro en ese primer submuestreo, sin reajustar sus pesos.
antialias_all=copy.deepcopy(antialias)
antialias_all.conv1.stride=(1,1)
antialias_all.maxpool=torch.nn.Sequential(
    antialiased_cnns.BlurPool(64,filt_size=5,stride=2).to(device),antialias_all.maxpool)
models={'baseline':baseline,'antialias_bin5':antialias,'antialias_todos_sin_reajuste':antialias_all}
mean=torch.tensor([.485,.456,.406],device=device)[None,:,None,None]
std=torch.tensor([.229,.224,.225],device=device)[None,:,None,None]
offsets=[(0,d) for d in range(-4,5)]
# Dos recortes independientes por imagen para cada uno de los ocho pares.
pair_offsets=rng.integers(-4,5,size=(8,2,2))
extra=[tuple(pair_offsets[p,k]) for p in range(8) for k in range(2)]
all_offsets=offsets+extra
records=[]
with torch.inference_mode():
    for row_index,row in zip(indices,selected):
        raw=row['image']['bytes']; original=Image.open(io.BytesIO(raw))
        mime=Image.MIME.get(original.format,'application/octet-stream'); image=original.convert('RGB')
        resized=TF.resize(image,256,interpolation=TF.InterpolationMode.BILINEAR,antialias=True)
        w,h=resized.size; cy=(h-224)//2; cx=(w-224)//2
        crops=torch.stack([TF.pil_to_tensor(TF.crop(resized,cy+int(dy),cx+int(dx),224,224)) for dy,dx in all_offsets]).to(device=device,dtype=torch.float32)/255
        crops=(crops-mean)/std
        true_class=int(row['label'])
        entry={'index':int(row_index),'label':names[true_class],'imagenet_class':true_class,
               'image_sha256':hashlib.sha256(raw).hexdigest(),
               'image_mime':mime,'image_base64':base64.b64encode(raw).decode('ascii'),'models':{}}
        for key,model in models.items():
            logits=model(crops); probs=logits.softmax(dim=1)
            top=probs.argmax(dim=1).cpu().tolist()
            true_prob=probs[:,true_class].cpu().tolist()
            agreements=[int(top[9+2*p]==top[10+2*p]) for p in range(8)]
            entry['models'][key]={'offset_top1':top[:9],'offset_true_prob':true_prob[:9],
                                  'pair_top1':top[9:],'pair_agreement':agreements}
        records.append(entry)
summary={}
for name in models:
    s=[r['models'][name] for r in records]
    summary[name]={'pair_consistency':float(np.mean([v for e in s for v in e['pair_agreement']])),
                   'center_accuracy':float(np.mean([e['offset_top1'][4]==r['imagenet_class'] for r,e in zip(records,s)])),
                   'true_probability_shift_std_mean':float(np.mean([np.std(e['offset_true_prob']) for e in s]))}
result={'dataset':'benjamin-paine/imagenet-1k-256x256, primera mitad del split oficial de validación',
        'dataset_revision':'1bd0400450249a7fe90c0aece37d0d03e7ea956a','seed':20261102,
        'short':short,'device':str(device),'offsets':offsets,'pair_offsets':pair_offsets.tolist(),
        'preprocess':'resize lado menor a 256 bilineal; recorte 224 desplazado, normalización ImageNet',
        'weights':{'baseline':'torchvision IMAGENET1K_V1',
                   'antialias_bin5':'antialiased-cnns 0.3 resnet18_lpf5-c1eed0a1, preentrenado independiente, primer stride sin filtro',
                   'antialias_todos_sin_reajuste':'mismo checkpoint antialias con filtro añadido al primer stride, sin reajuste'},
        'summary':summary,'records':records}
out=Path(os.environ.get('ORYON_SHIFT_OUTPUT','m16-l04-shifts.json'))
out.write_text(json.dumps(result,ensure_ascii=False,allow_nan=False),encoding='utf-8')
print(json.dumps({'device':str(device),'images':len(records),'summary':summary,'output':str(out)},ensure_ascii=False,indent=2))
del baseline,antialias,antialias_all,models
if device.type=='cuda': 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

ProofA matrix respecting translations
Prove: Prove that a linear operator A on length-n vectors commuting with circular shift T is a circular convolution.
0
T is a cyclic permutation of n positions, e₀ is the first impulse and eⱼ=Tʲe₀.

Step 1 of 2. If h=Ae₀, what is column Aeⱼ?

NumericThe full dense layer
An affine layer connects each value of a 32×32×3 input to each value of a 32×32×16 output. How many parameters does it have including one bias per output?
NumericShared convolution
For the same input and spatial output, how many parameters does a 3×3 convolution with 16 filters, three channels, one group and one bias per output channel have?
NumericQuantify the constraint
What is the ratio between parameter counts of the previous dense layer and convolution?
QuizEquivariance and invariance
For integer circular translations and appropriate spatial actions, which statement is correct?
CodeFilter and choose a phase
Implement blur_pool2d(x,stride) for a nonempty finite real NCHW input. Use circular extension, separable correlation with [1,2,1]/4 on each axis, then retain indices 0,stride,2·stride,... per axis. stride is a positive integer excluding bool. Convert to float and reject invalid input, shape or stride with ValueError. This operation filters and reduces; it does not include prior max pooling.
import numpy as np

def blur_pool2d(x,stride):
  pass
Shift+Enter to run
QuizA clue at the boundary
Why can zero padding reveal absolute position to a CNN?
[ ]Check counts and boundary effectBrowser
import numpy as np
inp=32*32*3; out=32*32*16
dense=inp*out+out; local=32*32*16*(3*3*3+1); conv=16*(3*3*3+1)
print('Entrada:',inp,'salidas:',out,'densa:',dense,'local sin compartir:',local,'conv:',conv,'cociente:',dense/conv)
def shift_zero(x): return np.r_[0.,x[:-1]]
def corr_zero(x):
    p=np.pad(x,1)
    return np.array([p[i:i+3]@np.ones(3) for i in range(len(x))])
x=np.array([1.,0.,0.,0.])
print('C(Tx):',corr_zero(shift_zero(x)),'T(Cx):',shift_zero(corr_zero(x)))

References