Module contents
Lesson 2 of 25Core 110 min

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.

InteractiveSlide and count

The kernel samples positions separated by dilation; the outer border is zero padding. Output is integer-valued: the remainder shows space between the last complete window and the extended border. Positions visited by no window are faded.

  • Visited input
  • Selected output sample
  • Unvisited input or padding

Input and padding

Output 2×2: choose a position; keyboard arrows or the selector also work.

Per axis: floor((7 + 2·0 − 3) / 3) + 1 = 2. Selected output is (0, 0).

7
3
0
3
1
Effective kernel3
Output per axis2
Remainder discarded per axis1
Unused pixels13
Select an output and inspect its actual samples and padding positions. The remainder indicates space after the final complete window, not a fractional output.

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 X∈RN×Cin×H×WX\in\mathbb R^{N\times C_{\mathrm{in}}\times H\times W}, weights K∈RCout×Cin×kH×kWK\in\mathbb R^{C_{\mathrm{out}}\times C_{\mathrm{in}}\times k_H\times k_W} and zero padding, a multichannel layer without groups computes

Yn,o,i,j=bo+∑c=0Cin−1∑a=0kH−1∑q=0kW−1Ko,c,a,q X~n,c, isH+adH, jsW+qdW.Y_{n,o,i,j}=b_o+\sum_{c=0}^{C_{\mathrm{in}}-1}\sum_{a=0}^{k_H-1}\sum_{q=0}^{k_W-1} K_{o,c,a,q}\,\widetilde X_{n,c,\,is_H+ad_H,\,js_W+qd_W}.

X~\widetilde X includes padding and indices are expressed in that extended tensor. Filter oo has CinkHkWC_{\mathrm{in}}k_Hk_W coefficients; it sums responses over channels and produces one map. Another filter learns different coefficients and produces another map. bob_o is unique per output channel and shared across positions. Batch size does not increase parameter count.

InteractiveOne filter spans channels

Input 2×4×4, 2×2 correlation, stride 1 and no padding. Each filter spans all channels and produces a 3×3 map; there are 2 maps total. The scene shows the selected window in orange, its filter weights in green and map in blue.

Products by channel: c0: 13.000 + c1: 31.000; bias 0.50; sum 44.500. Selected map, by rows: 25.75, 29.50, 33.25, 40.75, 44.50, 48.25, 55.75, 59.50, 63.25.

Explicit model: x[c,y,x]=2(c+1)+4y+x, w[f,c,u,v]=(f+1)(c+1)(2u+v+1)/8 and b[f]=(f+1)/2. There are no groups. Controls and numbers allow the calculation to be followed without WebGL.

2
2
Weights2 × 2 × 2 × 2
Parameters including bias18
Selected map value44.500
Break an output into per-channel contributions and observe the map each filter produces.

With GG groups, both channel counts must be divisible by GG; each filter sees only the Cin/GC_{\mathrm{in}}/G channels in its group. Weights therefore have shape (Cout,Cin/G,kH,kW)(C_{\mathrm{out}},C_{\mathrm{in}}/G,k_H,k_W) and there are Cout(Cin/G)kHkWC_{\mathrm{out}}(C_{\mathrm{in}}/G)k_Hk_W weights, plus CoutC_{\mathrm{out}} 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 LL, with kernel length kk, stride s≥1s\ge1, dilation d≥1d\ge1 and nonnegative integer padding pizq,pderp_{\mathrm{izq}},p_{\mathrm{der}} on the left and right, the effective kernel occupies

kef=d(k−1)+1,Lout=⌊L+pizq+pder−kefs⌋+1.k_{\mathrm{ef}}=d(k-1)+1,\qquad L_{\mathrm{out}}=\left\lfloor\frac{L+p_{\mathrm{izq}}+p_{\mathrm{der}}-k_{\mathrm{ef}}}{s}\right\rfloor+1.

Shape arithmetic applies separately to height and width. The first origin is zero in the extended tensor; the last must satisfy js+kef≤L+pizq+pderjs+k_{\mathrm{ef}}\le L+p_{\mathrm{izq}}+p_{\mathrm{der}}. If the effective kernel does not fit, the case is rejected. The floor discards the remainder: with L=7L=7, k=3k=3, s=3s=3 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: k=3,d=2k=3,d=2 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 Lout=⌈L/s⌉L_{\mathrm{out}}=\lceil L/s\rceil and adds

P=max⁡ ⁣(0,(⌈L/s⌉−1)s+kef−L)P=\max\!\left(0,(\lceil L/s\rceil-1)s+k_{\mathrm{ef}}-L\right)

zeros in total. If PP 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

NHoutWoutCout(Cin/G)kHkW.N H_{\mathrm{out}}W_{\mathrm{out}} C_{\mathrm{out}}(C_{\mathrm{in}}/G)k_Hk_W.

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 3⋅2242=150 5283\cdot224^2=150\,528 samples. A dense neuron over it requires as many weights, whereas a local ungrouped filter uses 3kHkW3k_Hk_W 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 P=HoutWoutP=H_{\mathrm{out}}W_{\mathrm{out}} and D=CinkHkWD=C_{\mathrm{in}}k_Hk_W, for one example columns form A∈RD×PA\in\mathbb R^{D\times P} and flattened filters B∈RCout×DB\in\mathbb R^{C_{\mathrm{out}}\times D}. Then BABA 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.

InteractiveWindows become columns

4×4 input with numbers 1 to 16; 2×2 windows, stride 1 and no padding. Each column contains a window flattened by rows: the matrix is 4×9. Orange links the window to its column.

Input
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Columns, in output order
12356791011
234678101112
56791011131415
678101112141516

The 2×4 filter matrix has rows [1, 0, 0, 1] and [-1, 1, 1, -1]. Their products with this column are 7 and 0. For filter 0: [1, 0, 0, 1] · [1, 2, 5, 6] = 1×1 + 0×2 + 0×5 + 1×6 = 7. Each filter produces one map.

Bytes count only the float32 column copy; they exclude weights, output and padding memory. Windows may be overlapping views; flattening them for matrix multiplication may require a copy. Implicit GEMM can avoid materializing every column.

Selected output7
Materialized float32 columns144 B
float32 input64 B
Element duplication36 / 16 = 2.25
Follow a window to its column and check its products with the filters.

There is a price: neighboring windows repeat values. Materializing all columns occupies NDPNDP 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 F(2×2,3×3)F(2\times2,3\times3), 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 xx. For one channel and no bias there is a matrix AA such that y=Axy=Ax: 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.

InteractiveShared weights inside a matrix

Correlation without bias, stride 1 and centered kernel. Each matrix row represents an output and each column an input, both in row order. Changing a weight highlights every cell it contributes to.

  • Selected weight contribution
2300
1230
0123
0012

Product with x=(1, 2, …): 8, 14, 20, 11.

With zero padding, the matrix is Toeplitz in 1D and block Toeplitz with Toeplitz blocks in 2D. If several offsets reach the same circular index, their coefficients are added. With stride other than 1, rows are selected and simple Toeplitz structure can be lost.

Dimension
Border
1
Matrix shape4 × 4
Highlighted copies3
Change a coefficient and observe all its copies; compare zero and periodic extension.

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 (N,C,L)(N,C,L) and weights (Cout,Cin/G,k)(C_{\mathrm{out}},C_{\mathrm{in}}/G,k); 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.

[ ]Define correlationBrowser
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.')
[ ]Compare loops and columnsBrowser
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.')
[ ]Build the explicit matrixBrowser
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.')
[ ]Extend to one and three dimensionsBrowser
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.

[ ]Parity and local measurementsLocal GPU
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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericConvolution output
Input 3×224×224, 64 filters of 7×7, symmetric padding 3, stride 2, dilation 1 and one group. What is the output height?
NumericShared weights
For the previous layer, how many parameters are there including one bias per output channel?
NumericNominal work
For one image and the same layer, how many nominal direct FLOPs are there if each multiply-accumulate counts as two FLOPs and biases are excluded?
NumericCost of duplicating windows
You materialize columns of a 128×64×56×56 batch with 3×3 kernel, padding 1, stride 1, dilation 1 and float32. How many MiB does that matrix alone occupy? One MiB is 2²⁰ bytes.
Code1D multichannel correlation
Implement conv1d(x,w,stride,padding,dilation). x and w are nonempty finite real arrays of shapes (N,C,L) and (O,C,K). There is no bias or grouping. Parameters are integers, excluding bool: positive stride and dilation and nonnegative padding, applied with zeros on both sides. Raise ValueError for incompatible shapes, invalid parameters or an effective kernel that does not fit. Return float64 correlation without reversing the kernel and using floor for output size.
import numpy as np

def conv1d(x, w, stride, padding, dilation):
  pass
Shift+Enter to run
ProofDiagonalize circular correlation
Prove: Prove circular correlation is circulant and obtain its eigenvalues in the Fourier basis.
0
Work with length N, stride one, zero bias and periodic extension. Group kernel coefficients by offsets modulo N.

Step 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?

QuizA dense layer at each pixel?
An ungrouped 1×1 convolution with stride one and no padding transforms C input channels to C outputs. Which statement is correct?
[ ]Check counts and the DFT signBrowser
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