Discrete convolution implemented by hand
Build multi-channel convolution from correlation, follow padding, stride and dilation, count parameters and operations, and compare direct, im2col and structured-matrix formulations.
After this lesson you can
- Calculate multi-channel convolution outputs and shapes with stride, padding and dilation.
- Count shared parameters and nominal operations including grouped convolution.
- Implement direct correlation and im2col and explain their memory tradeoff.
- Express convolution as a structured matrix and analyze the circular case.
- Compare implementations with PyTorch using appropriate tolerances and timing.
Before you start
A 224×224 image with three channels has 150,528 inputs. A dense neuron looking at all of them learns one weight per input; a local layer can learn the same small template and apply it at every position. That reuse changes the problem’s structure: it does not mean the layer ignores channels or that every position produces the same value.
In the previous lesson you applied hand-chosen filters. Now their coefficients are learned parameters and each filter spans all input channels. Follow a window from the input origin to its output and ask what happens when another full window no longer fits.
The operation and its channels
A mathematical discrete convolution reverses the kernel relative to correlation. Learning layers called convolutional usually implement cross-correlation without that reversal. For free weights both parameterizations describe the same function family by flipping spatial weights, but sign and orientation matter when porting a fixed kernel.
With real input , weights and zero padding, a multichannel layer without groups computes
includes padding and indices are expressed in that extended tensor. Filter has coefficients; it sums responses over channels and produces one map. Another filter learns different coefficients and produces another map. is unique per output channel and shared across positions. Batch size does not increase parameter count.
With groups, both channel counts must be divisible by ; each filter sees only the channels in its group. Weights therefore have shape and there are weights, plus biases if used. Grouping restricts connections; it does not create a bias per pixel. The PyTorch documentation states these shapes and constraints.
Geometry: padding, stride and dilation
On an axis of length , with kernel length , stride , dilation and nonnegative integer padding on the left and right, the effective kernel occupies
Shape arithmetic applies separately to height and width. The first origin is zero in the extended tensor; the last must satisfy . If the effective kernel does not fit, the case is rejected. The floor discards the remainder: with , , and zero padding there are two windows, starting at 0 and 3, and index 6 is unused. Output always has integer size.
Dilation separates samples touched by the filter: looks at offsets 0, 2 and 4. It spans five positions but still has three weights per channel, not five. Stride moves the origin between outputs and can leave inputs unseen. Valid padding means adding no elements; same requires stating the convention. One useful definition takes and adds
zeros in total. If is odd, decide which side gets the extra one. In torch.nn.functional.conv2d, padding='same' supports only stride=1; with another stride the desired padding must be added explicitly. The Dumoulin and Visin guide develops the relationships and diagrams.
Direct computation and counts
For each sample, output channel and position, accumulate products over input channels and the filter’s two coordinates. The explicit version has seven indices: batch, output channel, output row and column, input channel, kernel row and column. Counting all positions, including padding zeros, the number of multiplications is
We use two FLOPs per multiply-accumulate: double that figure and count biases separately. An implementation may omit multiplication by zero or use another algorithm; the formula describes nominal direct work, not measured time. For example, the opening 224×224 RGB input has samples. A dense neuron over it requires as many weights, whereas a local ungrouped filter uses and shares them spatially.
Windows as columns and GEMM
In im2col, each column contains the complete window of all channels in a fixed order. If and , for one example columns form and flattened filters . Then gives all outputs and bias is added afterward. For a batch, stack columns or perform one product per sample. With groups, divide the product by group and respect channel order.
There is a price: neighboring windows repeat values. Materializing all columns occupies extra elements, excluding input, padding, weights and output; multiply by dtype size. NumPy’s sliding_window_view returns a view of overlapping windows, but transposition followed by reshape for GEMM may require a copy. Check np.shares_memory for the specific shape: the first step being a view is not enough. NumPy documentation explains overlap.
The NVIDIA guide describes implicit GEMM and transformed algorithms, including FFT and Winograd. The implicit GEMM matrix can be virtual, without materializing all columns. In , Lavin and Gray count 16 multiplications for four outputs versus 36 directly. This compares multiplications in the algorithm’s core, not a guarantee that total time is 2.25 times lower: transformations, additions, memory and precision also matter.
The same operation as a structured matrix
Fix input size and flatten it as vector . For one channel and no bias there is a matrix such that : each row selects a window and places kernel coefficients where they belong. Unconnected entries are zeros; the same weights reappear in several rows. Bias adds a vector and makes the mapping affine, not linear.
In 1D stride-one correlation with zero extension, the matrix is Toeplitz: diagonals repeat offsets. In 2D with compatible spatial order, the result is a block Toeplitz matrix with Toeplitz blocks. Row selection for stride>1 does not necessarily preserve that simple shape. With circular extension, equal input and output sizes and stride one, the 1D case is circulant; in 2D there are circulant blocks of circulant blocks. If several kernel offsets coincide modulo the size, their coefficients are summed.
The structured matrix shows exactly where parameters are shared, although constructing it for large images is usually impractical. A dense layer producing the same outputs allows different connections per position and, for images and maps with multiple positions, usually has many more parameters. It does not impose convolution’s shared sparse structure; in special cases, such as a single patch covering the full input, that difference can disappear. The DFT diagonalizes the circular case: the correlation convention requires reversing the frequency index, as you will prove below.
One, two and three dimensions
Dimensionality counts axes traversed by the kernel, not channels or batch. In 1D a sequence has shape and weights ; 2D adds height and width; 3D traverses three axes, such as time, height and width of video or three axes of a volume. Conv1d, Conv2d and Conv3d keep batch and channels separate. Effective field and output count apply independently per axis.
Lab: three implementations
Implement correlation using loops, windows and an explicit matrix. Check values, shapes and bias with asymmetric kernels, stride and dilation, as well as grouped cases when the contract permits. Sizes are small so results can be inspected in the browser. Cell execution order matters.
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
def _pair(value, name, minimum):
values = (value, value) if isinstance(value, (int, np.integer)) else tuple(value)
if (len(values) != 2 or any(not isinstance(v, (int, np.integer)) or isinstance(v, (bool, np.bool_))
or v < minimum for v in values)):
raise ValueError(name + ' debe contener dos enteros válidos')
return tuple(int(v) for v in values)
def _validate(x, weights, bias, stride, padding, dilation, groups):
x, weights = np.asarray(x, dtype=float), np.asarray(weights, dtype=float)
if x.ndim != 4 or weights.ndim != 4 or not x.size or not weights.size:
raise ValueError('Se esperan X NCHW y pesos OIHW no vacíos')
if not np.isfinite(x).all() or not np.isfinite(weights).all():
raise ValueError('Datos y pesos deben ser finitos')
if not isinstance(groups, (int, np.integer)) or isinstance(groups, (bool, np.bool_)) or groups < 1:
raise ValueError('groups debe ser un entero positivo')
n, cin, h, w = x.shape
cout, cgroup, kh, kw = weights.shape
if cin % groups or cout % groups or cgroup != cin//groups:
raise ValueError('Canales incompatibles con los grupos')
if bias is None:
bias = np.zeros(cout)
bias = np.asarray(bias, dtype=float)
if bias.shape != (cout,) or not np.isfinite(bias).all():
raise ValueError('Sesgo inválido')
sh, sw = _pair(stride, 'stride', 1)
ph, pw = _pair(padding, 'padding', 0)
dh, dw = _pair(dilation, 'dilation', 1)
effh, effw = dh*(kh-1)+1, dw*(kw-1)+1
oh, ow = (h+2*ph-effh)//sh+1, (w+2*pw-effw)//sw+1
if oh <= 0 or ow <= 0:
raise ValueError('El núcleo efectivo no cabe en la entrada extendida')
return x, weights, bias, (sh,sw), (ph,pw), (dh,dw), (oh,ow), int(groups)
def conv2d_naive(x, weights, bias=None, stride=1, padding=0, dilation=1, groups=1):
x, w, b, (sh,sw), (ph,pw), (dh,dw), (oh,ow), groups = _validate(
x,weights,bias,stride,padding,dilation,groups)
n, cin, _, _ = x.shape
cout, cg, kh, kw = w.shape
padded = np.pad(x, ((0,0),(0,0),(ph,ph),(pw,pw)))
out = np.empty((n,cout,oh,ow))
for batch in range(n):
for oc in range(cout):
group = oc//(cout//groups)
for i in range(oh):
for j in range(ow):
total = b[oc]
for c in range(cg):
for r in range(kh):
for s in range(kw):
total += w[oc,c,r,s]*padded[batch,group*cg+c,i*sh+r*dh,j*sw+s*dw]
out[batch,oc,i,j] = total
return out
def conv2d_im2col(x, weights, bias=None, stride=1, padding=0, dilation=1, groups=1, details=False):
x, w, b, (sh,sw), (ph,pw), (dh,dw), (oh,ow), groups = _validate(
x,weights,bias,stride,padding,dilation,groups)
n, cin, _, _ = x.shape
cout, cg, kh, kw = w.shape
effh, effw = dh*(kh-1)+1, dw*(kw-1)+1
padded = np.pad(x, ((0,0),(0,0),(ph,ph),(pw,pw)))
view = sliding_window_view(padded, (effh,effw), axis=(2,3))
view = view[:,:,::sh,::sw,::dh,::dw][:,:,:oh,:ow,:kh,:kw]
patches = view.reshape(n,groups,cg,oh,ow,kh,kw).transpose(0,1,3,4,2,5,6)
columns = np.ascontiguousarray(patches).reshape(n,groups,oh*ow,cg*kh*kw)
filters = w.reshape(groups,cout//groups,cg*kh*kw)
out = np.einsum('ngpd,god->ngop', columns, filters, optimize=False).reshape(n,cout,oh,ow)
out += b[None,:,None,None]
if details:
return out, {'shape': columns.shape, 'bytes': columns.nbytes,
'windows_share_padded': bool(np.shares_memory(view,padded)),
'columns_share_padded': bool(np.shares_memory(columns,padded))}
return out
print('Conv2D: correlación NCHW, padding cero, pesos OIHW, grupos y sesgo por canal.')from time import perf_counter
rng = np.random.default_rng(16002)
configs = [
# N, Cin, H, W, Cout, kH, kW, stride, padding, dilation, groups
(1,2,5,6,3,3,2,(1,1),(0,0),(1,1),1),
(2,4,8,7,6,2,3,(2,1),(1,2),(2,1),2),
(1,3,7,9,3,3,2,(2,3),(2,1),(2,2),3),
]
for n,ci,h,w,co,kh,kw,stride,padding,dilation,groups in configs:
x = rng.normal(size=(n,ci,h,w))
weight = rng.normal(size=(co,ci//groups,kh,kw))
bias = rng.normal(size=co)
t0=perf_counter(); naive=conv2d_naive(x,weight,bias,stride,padding,dilation,groups); t1=perf_counter()
fast, info=conv2d_im2col(x,weight,bias,stride,padding,dilation,groups,details=True); t2=perf_counter()
err=np.max(np.abs(naive-fast))
assert np.allclose(naive,fast,atol=1e-11,rtol=1e-11)
print('Caso:',(n,ci,h,w,co,kh,kw,stride,padding,dilation,groups),'salida:',naive.shape,'error:',err)
print('Columnas:',info,'tiempos de esta ejecución, bucles y columnas:',t1-t0,t2-t1)
x=np.arange(1,10,dtype=float).reshape(1,1,3,3)
k=np.array([[1.,0.],[0.,-1.]]).reshape(1,1,2,2)
assert np.array_equal(conv2d_naive(x,k),np.full((1,1,2,2),-4.))
print('Núcleo antisimétrico sin invertir y ejemplo manual: correctos.')
noncontig=rng.normal(size=(1,2,6,8))[:,:,::-1,::2]
assert not noncontig.flags.c_contiguous
w=rng.normal(size=(3,2,3,2))
assert np.allclose(conv2d_naive(noncontig,w,padding=1),conv2d_im2col(noncontig,w,padding=1))
for kwargs in ({'stride':0},{'dilation':(1,0)},{'padding':-1},{'groups':3}):
try:
conv2d_naive(noncontig,w,**kwargs)
raise AssertionError('Configuración inválida aceptada')
except ValueError:
pass
try:
conv2d_naive(np.ones((1,1,1,1)),np.ones((1,1,3,3)))
raise AssertionError('Núcleo excesivo aceptado')
except ValueError:
pass
print('Entrada no contigua y configuraciones inválidas: correctas.')def conv2d_matrix(x, weights, bias=None, stride=1, padding=0, dilation=1, groups=1):
"""Construye matriz lineal explícita y suma aparte un sesgo por salida."""
x, w, b, (sh,sw), (ph,pw), (dh,dw), (oh,ow), groups = _validate(
x,weights,bias,stride,padding,dilation,groups)
n, cin, height, width = x.shape
cout, cg, kh, kw = w.shape
rows, cols = cout*oh*ow, cin*height*width
if rows*cols > 2_000_000:
raise ValueError('Ejemplo demasiado grande para construir la matriz explícita')
A = np.zeros((rows,cols))
for oc in range(cout):
group=oc//(cout//groups)
for i in range(oh):
for j in range(ow):
row=(oc*oh+i)*ow+j
for c in range(cg):
channel=group*cg+c
for r in range(kh):
y=i*sh+r*dh-ph
for s in range(kw):
z=j*sw+s*dw-pw
if 0<=y<height and 0<=z<width:
A[row,(channel*height+y)*width+z] += w[oc,c,r,s]
y=(x.reshape(n,-1)@A.T).reshape(n,cout,oh,ow)+b[None,:,None,None]
return y, A
x=rng.normal(size=(2,4,4,5)); weight=rng.normal(size=(6,2,2,3)); bias=rng.normal(size=6)
actual, matrix=conv2d_matrix(x,weight,bias,stride=(1,2),padding=(1,0),dilation=(2,1),groups=2)
expected=conv2d_naive(x,weight,bias,stride=(1,2),padding=(1,0),dilation=(2,1),groups=2)
assert np.allclose(actual,expected,atol=1e-11)
print('Matriz:',matrix.shape,'elementos no nulos:',np.count_nonzero(matrix),
'error frente a bucles:',np.max(np.abs(actual-expected)))
print('La matriz representa la parte lineal; el sesgo se añade después.')def conv_nd(x, weights, bias=None, stride=1, padding=0, dilation=1):
"""Correlación directa N,C,*ejes; grupos=1, hasta 3 ejes espaciales."""
x,w=np.asarray(x,dtype=float),np.asarray(weights,dtype=float)
dims=x.ndim-2
if dims not in (1,2,3) or w.ndim != x.ndim or not x.size or not w.size or x.shape[1]!=w.shape[1]:
raise ValueError('Formas o dimensionalidad inválidas')
if not np.isfinite(x).all() or not np.isfinite(w).all():
raise ValueError('Valores no finitos')
def to_tuple(v,minimum):
result=(v,)*dims if isinstance(v,(int,np.integer)) else tuple(v)
if len(result)!=dims or any(not isinstance(k,(int,np.integer)) or isinstance(k,(bool,np.bool_)) or k<minimum for k in result):
raise ValueError('Parámetro espacial inválido')
return tuple(int(k) for k in result)
st=to_tuple(stride,1); pa=to_tuple(padding,0); di=to_tuple(dilation,1)
cout,cin=w.shape[:2]
b=np.zeros(cout) if bias is None else np.asarray(bias,dtype=float)
if b.shape != (cout,) or not np.isfinite(b).all(): raise ValueError('Sesgo inválido')
outshape=tuple((L+2*p-d*(k-1)-1)//s+1 for L,k,s,p,d in zip(x.shape[2:],w.shape[2:],st,pa,di))
if any(o<=0 for o in outshape): raise ValueError('Núcleo efectivo demasiado grande')
padded=np.pad(x,((0,0),(0,0),*((p,p) for p in pa)))
out=np.empty((x.shape[0],cout,*outshape))
for batch in range(x.shape[0]):
for oc in range(cout):
for pos in np.ndindex(*outshape):
total=b[oc]
for c in range(cin):
for offset in np.ndindex(*w.shape[2:]):
src=tuple(pos[i]*st[i]+offset[i]*di[i] for i in range(dims))
total+=w[(oc,c,*offset)]*padded[(batch,c,*src)]
out[(batch,oc,*pos)]=total
return out
seq=np.arange(8,dtype=float).reshape(1,1,8)
kernel=np.array([1.,2.,3.]).reshape(1,1,3)
print('Ejemplo 1D con stride 2, padding 1 y dilatación 2:',conv_nd(seq,kernel,stride=2,padding=1,dilation=2))
volume=np.arange(27,dtype=float).reshape(1,1,3,3,3)
out3=conv_nd(volume,np.ones((1,1,2,2,2)))
assert out3.shape == (1,1,2,2,2) and out3[0,0,0,0,0] == 52
print('Ejemplo 3D:',out3.shape,'primera salida:',out3[0,0,0,0,0])
smallx=rng.normal(size=(1,2,4,5)); smallw=rng.normal(size=(3,2,2,3))
assert np.allclose(conv_nd(smallx,smallw,padding=(1,0)),conv2d_naive(smallx,smallw,padding=(1,0)))
print('La versión dimensional y la 2D coinciden en un ejemplo.')Local lab: PyTorch and GPU
Compare the same inputs and weights with F.conv2d on CPU and GPU, including a grouped case with stride and dilation. First check equality with appropriate tolerances; then measure. Warm up before timing and synchronize CUDA around each measured region. Compare paired configurations with cudnn.benchmark enabled and disabled and contiguous or channels_last storage; the latter changes physical strides, not logical NCHW shape. Record device, versions and precision. Results depend on shape, hardware, backend and shared load: do not infer the chosen algorithm or extrapolate a universal winner.
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
def _pair(value, name, minimum):
values = (value, value) if isinstance(value, (int, np.integer)) else tuple(value)
if (len(values) != 2 or any(not isinstance(v, (int, np.integer)) or isinstance(v, (bool, np.bool_))
or v < minimum for v in values)):
raise ValueError(name + ' debe contener dos enteros válidos')
return tuple(int(v) for v in values)
def _validate(x, weights, bias, stride, padding, dilation, groups):
x, weights = np.asarray(x, dtype=float), np.asarray(weights, dtype=float)
if x.ndim != 4 or weights.ndim != 4 or not x.size or not weights.size:
raise ValueError('Se esperan X NCHW y pesos OIHW no vacíos')
if not np.isfinite(x).all() or not np.isfinite(weights).all():
raise ValueError('Datos y pesos deben ser finitos')
if not isinstance(groups, (int, np.integer)) or isinstance(groups, (bool, np.bool_)) or groups < 1:
raise ValueError('groups debe ser un entero positivo')
n, cin, h, w = x.shape
cout, cgroup, kh, kw = weights.shape
if cin % groups or cout % groups or cgroup != cin//groups:
raise ValueError('Canales incompatibles con los grupos')
if bias is None:
bias = np.zeros(cout)
bias = np.asarray(bias, dtype=float)
if bias.shape != (cout,) or not np.isfinite(bias).all():
raise ValueError('Sesgo inválido')
sh, sw = _pair(stride, 'stride', 1)
ph, pw = _pair(padding, 'padding', 0)
dh, dw = _pair(dilation, 'dilation', 1)
effh, effw = dh*(kh-1)+1, dw*(kw-1)+1
oh, ow = (h+2*ph-effh)//sh+1, (w+2*pw-effw)//sw+1
if oh <= 0 or ow <= 0:
raise ValueError('El núcleo efectivo no cabe en la entrada extendida')
return x, weights, bias, (sh,sw), (ph,pw), (dh,dw), (oh,ow), int(groups)
def conv2d_naive(x, weights, bias=None, stride=1, padding=0, dilation=1, groups=1):
x, w, b, (sh,sw), (ph,pw), (dh,dw), (oh,ow), groups = _validate(
x,weights,bias,stride,padding,dilation,groups)
n, cin, _, _ = x.shape
cout, cg, kh, kw = w.shape
padded = np.pad(x, ((0,0),(0,0),(ph,ph),(pw,pw)))
out = np.empty((n,cout,oh,ow))
for batch in range(n):
for oc in range(cout):
group = oc//(cout//groups)
for i in range(oh):
for j in range(ow):
total = b[oc]
for c in range(cg):
for r in range(kh):
for s in range(kw):
total += w[oc,c,r,s]*padded[batch,group*cg+c,i*sh+r*dh,j*sw+s*dw]
out[batch,oc,i,j] = total
return out
def conv2d_im2col(x, weights, bias=None, stride=1, padding=0, dilation=1, groups=1, details=False):
x, w, b, (sh,sw), (ph,pw), (dh,dw), (oh,ow), groups = _validate(
x,weights,bias,stride,padding,dilation,groups)
n, cin, _, _ = x.shape
cout, cg, kh, kw = w.shape
effh, effw = dh*(kh-1)+1, dw*(kw-1)+1
padded = np.pad(x, ((0,0),(0,0),(ph,ph),(pw,pw)))
view = sliding_window_view(padded, (effh,effw), axis=(2,3))
view = view[:,:,::sh,::sw,::dh,::dw][:,:,:oh,:ow,:kh,:kw]
patches = view.reshape(n,groups,cg,oh,ow,kh,kw).transpose(0,1,3,4,2,5,6)
columns = np.ascontiguousarray(patches).reshape(n,groups,oh*ow,cg*kh*kw)
filters = w.reshape(groups,cout//groups,cg*kh*kw)
out = np.einsum('ngpd,god->ngop', columns, filters, optimize=False).reshape(n,cout,oh,ow)
out += b[None,:,None,None]
if details:
return out, {'shape': columns.shape, 'bytes': columns.nbytes,
'windows_share_padded': bool(np.shares_memory(view,padded)),
'columns_share_padded': bool(np.shares_memory(columns,padded))}
return out
print('Conv2D: correlación NCHW, padding cero, pesos OIHW, grupos y sesgo por canal.')
def conv_nd(x, weights, bias=None, stride=1, padding=0, dilation=1):
"""Correlación directa N,C,*ejes; grupos=1, hasta 3 ejes espaciales."""
x,w=np.asarray(x,dtype=float),np.asarray(weights,dtype=float)
dims=x.ndim-2
if dims not in (1,2,3) or w.ndim != x.ndim or not x.size or not w.size or x.shape[1]!=w.shape[1]:
raise ValueError('Formas o dimensionalidad inválidas')
if not np.isfinite(x).all() or not np.isfinite(w).all():
raise ValueError('Valores no finitos')
def to_tuple(v,minimum):
result=(v,)*dims if isinstance(v,(int,np.integer)) else tuple(v)
if len(result)!=dims or any(not isinstance(k,(int,np.integer)) or isinstance(k,(bool,np.bool_)) or k<minimum for k in result):
raise ValueError('Parámetro espacial inválido')
return tuple(int(k) for k in result)
st=to_tuple(stride,1); pa=to_tuple(padding,0); di=to_tuple(dilation,1)
cout,cin=w.shape[:2]
b=np.zeros(cout) if bias is None else np.asarray(bias,dtype=float)
if b.shape != (cout,) or not np.isfinite(b).all(): raise ValueError('Sesgo inválido')
outshape=tuple((L+2*p-d*(k-1)-1)//s+1 for L,k,s,p,d in zip(x.shape[2:],w.shape[2:],st,pa,di))
if any(o<=0 for o in outshape): raise ValueError('Núcleo efectivo demasiado grande')
padded=np.pad(x,((0,0),(0,0),*((p,p) for p in pa)))
out=np.empty((x.shape[0],cout,*outshape))
for batch in range(x.shape[0]):
for oc in range(cout):
for pos in np.ndindex(*outshape):
total=b[oc]
for c in range(cin):
for offset in np.ndindex(*w.shape[2:]):
src=tuple(pos[i]*st[i]+offset[i]*di[i] for i in range(dims))
total+=w[(oc,c,*offset)]*padded[(batch,c,*src)]
out[(batch,oc,*pos)]=total
return out
import json
import os
import statistics
import time
from pathlib import Path
import torch
from torch.nn import functional as F
torch.set_num_threads(1)
torch.manual_seed(16002)
SHORT = os.getenv('ORYON_VERIFY_SHORT') == '1'
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
OUTPUT = Path(os.getenv('ORYON_CONV_OUTPUT', 'conv-comparison.json'))
random = np.random.default_rng(16002)
configs = [
(1,2,5,6,3,3,2,(1,1),(0,0),(1,1),1),
(2,4,8,7,6,2,3,(2,1),(1,2),(2,1),2),
(1,3,7,9,3,3,2,(2,3),(2,1),(2,2),3),
]
errors = []
for n,ci,h,w,co,kh,kw,stride,padding,dilation,groups in configs:
x=random.normal(size=(n,ci,h,w))
weight=random.normal(size=(co,ci//groups,kh,kw))
bias=random.normal(size=co)
direct=conv2d_naive(x,weight,bias,stride,padding,dilation,groups)
cols=conv2d_im2col(x,weight,bias,stride,padding,dilation,groups)
cpu=F.conv2d(torch.from_numpy(x),torch.from_numpy(weight),torch.from_numpy(bias),
stride,padding,dilation,groups).numpy()
result={'groups':groups,'shape':list(direct.shape),
'numpy_max_error':float(np.max(np.abs(cols-direct))),
'torch_cpu_max_error':float(np.max(np.abs(cpu-direct)))}
assert np.allclose(direct,cols,rtol=1e-10,atol=1e-10)
assert np.allclose(direct,cpu,rtol=1e-10,atol=1e-10)
if DEVICE.type=='cuda':
gpu=F.conv2d(torch.from_numpy(x).to(DEVICE),torch.from_numpy(weight).to(DEVICE),
torch.from_numpy(bias).to(DEVICE),stride,padding,dilation,groups).cpu().numpy()
result['torch_gpu_max_error']=float(np.max(np.abs(gpu-direct)))
assert np.allclose(direct,gpu,rtol=1e-9,atol=1e-9)
errors.append(result)
print('Paridad:',result,flush=True)
for dims in (1,3):
shape=(1,2,8) if dims==1 else (1,2,4,5,6)
kernel=(3,) if dims==1 else (2,3,2)
x=random.normal(size=shape)
weight=random.normal(size=(3,2,*kernel))
ours=conv_nd(x,weight,stride=2,padding=1,dilation=1)
fun=F.conv1d if dims==1 else F.conv3d
theirs=fun(torch.from_numpy(x),torch.from_numpy(weight),stride=2,padding=1).numpy()
err=float(np.max(np.abs(ours-theirs)))
assert np.allclose(ours,theirs,rtol=1e-10,atol=1e-10)
print('Paridad dimensional:',dims,'error máximo:',err,flush=True)
errors.append({'dimensions':dims,'torch_cpu_max_error':err})
# Mismos pesos y datos en los caminos. Los ratios no implican una tendencia universal.
bench_shape=(4,16,32,32) if SHORT else (16,64,56,56)
bench_out=32 if SHORT else 128
repeats=8 if SHORT else 40
base_x=torch.randn(*bench_shape)
base_w=torch.randn(bench_out,bench_shape[1],3,3)
reference=F.conv2d(base_x,base_w,padding=1)
measurements={}
old_benchmark=torch.backends.cudnn.benchmark
old_tf32=torch.backends.cudnn.allow_tf32
torch.backends.cudnn.allow_tf32=False
try:
for device in (['cpu','cuda'] if DEVICE.type=='cuda' else ['cpu']):
for layout in (['contiguous','channels_last'] if device=='cuda' else ['contiguous']):
for autotune in ([False,True] if device=='cuda' else [False]):
torch.backends.cudnn.benchmark=autotune
xx=base_x.to(device)
ww=base_w.to(device)
if layout=='channels_last':
xx=xx.contiguous(memory_format=torch.channels_last)
ww=ww.contiguous(memory_format=torch.channels_last)
assert xx.is_contiguous(memory_format=torch.channels_last)
with torch.inference_mode():
result=F.conv2d(xx,ww,padding=1)
assert torch.allclose(result.cpu(),reference,rtol=2e-4,atol=5e-5)
for _ in range(3):
F.conv2d(xx,ww,padding=1)
if device=='cuda':
torch.cuda.synchronize()
samples=[]
for _ in range(repeats):
if device=='cuda':
torch.cuda.synchronize()
start=time.perf_counter()
F.conv2d(xx,ww,padding=1)
if device=='cuda':
torch.cuda.synchronize()
samples.append(time.perf_counter()-start)
key=f'{device}_{layout}_autotune_{autotune}'
measurements[key]=statistics.median(samples)
baseline=measurements['cuda_contiguous_autotune_False'] if DEVICE.type=='cuda' else measurements['cpu_contiguous_autotune_False']
ratios={key:value/baseline for key,value in measurements.items()}
print('Medianas relativas a la referencia:',ratios,flush=True)
print('El layout físico cambia sin permutar la forma lógica NCHW. Los ratios dependen de forma y equipo.',flush=True)
payload={'short':SHORT,'device':str(DEVICE),'torch_version':torch.__version__,
'cudnn_version':torch.backends.cudnn.version() if DEVICE.type=='cuda' else None,
'tf32_cudnn':False,'benchmark_shape':list(bench_shape),'benchmark_output_channels':bench_out,
'repetitions':repeats,'baseline':'cuda_contiguous_autotune_False' if DEVICE.type=='cuda' else 'cpu_contiguous_autotune_False',
'median_time_ratios':ratios,'parity':errors}
OUTPUT.parent.mkdir(parents=True,exist_ok=True)
OUTPUT.write_text(json.dumps(payload,indent=2,ensure_ascii=False,allow_nan=False),encoding='utf-8')
print('Resultado:',OUTPUT,flush=True)
finally:
torch.backends.cudnn.benchmark=old_benchmark
torch.backends.cudnn.allow_tf32=old_tf32
if DEVICE.type=='cuda':
torch.cuda.empty_cache()npm run lab and open the connection link.Exercises
import numpy as np
def conv1d(x, w, stride, padding, dilation):
passStep 1 of 3. Let y[j]=Σr k[r]x[(j+r) mod N], with no bias and stride one. Why is the matrix circulant?
import numpy as np
h = (224 + 2*3 - 7)//2 + 1
parameters = 64*(3*7*7 + 1)
flops = 2*h*h*64*3*7*7
elements = 128*56*56*64*3*3
print('Muestras de entrada:', 3*224*224)
print('Altura de salida:', h, '; parámetros con sesgo:', parameters)
print('FLOPs nominales sin sesgo:', flops)
print('im2col, bytes:', elements*4, '; MiB:', elements*4/2**20)
x = np.arange(5, dtype=float)
k = np.array([1., 2., 3., 0., 0.])
direct = sum(k[r]*np.roll(x, -r) for r in range(len(k)))
frequency = np.fft.fft(k)[(-np.arange(len(k))) % len(k)]
spectral = np.fft.ifft(np.fft.fft(x)*frequency)
print('Error máximo de correlación circular por DFT:', np.max(np.abs(direct-spectral)))References
- Dumoulin and Visin, A guide to convolution arithmetic for deep learning.
- Goodfellow, Bengio and Courville, Deep Learning, chapter 9.
- Lavin and Gray, Fast Algorithms for Convolutional Neural Networks.
- PyTorch, torch.nn.functional.conv2d.
- NVIDIA, Convolutional Layers User’s Guide.
- NumPy, sliding_window_view.