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.
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 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 be a circular translation by positions. A mapping is translation equivariant if for the declared input and output actions. It is invariant if output stays unchanged, . 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 , let be a one-position shift and an impulse. If , define . Since ,
This is circular convolution with 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: 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 , an input shift that is a multiple of 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 window, backward sends the max output gradient to the argmax and distributes 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.
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: and each position’s gradient is . 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 channels to classes after GAP has parameters with bias; flattening first and connecting to outputs requires . 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 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.
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.
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 outimport 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 outrng=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.
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_plainLocal 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.
"""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()npm run lab and open the connection link.Exercises
Step 1 of 2. If h=Ae₀, what is column Aeⱼ?
import numpy as np
def blur_pool2d(x,stride):
passimport 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)))