Module contents
Lesson 6 of 25Core 110 min

Your first CNN from scratch: LeNet in NumPy

Build and train a modernized LeNet in NumPy, verify its backward pass, track validation and compare a CNN with a parameter-matched MLP under shifted inputs.

After this lesson you can

  • Calculate shapes, parameters and operations of a modernized LeNet.
  • Assemble convolution, activation, pooling and dense layers in a tensor engine.
  • Check gradients and diagnose learning on a fixed batch.
  • Train with separate validation and test and record a reproducible result.
  • Compare a CNN and parameter-matched MLP under controlled shifts.

Before you start

Learning filters

In the HOG and SVM baseline you chose features before fitting the classifier. Now classification loss also adjusts filters extracting features. A wrong prediction produces a gradient for the classifier and, by the chain rule, for each filter involved. The question is not only whether a CNN is correct: can you reconstruct every shape, derivative and update producing that result?

InteractiveTraining you can control

Real training in a separate process: a reduced CNN for 8×8 digits, with a six-filter 3×3 convolution, ReLU, 2×2 max pooling and a ten-output linear layer. This is not the complete LeNet from the lab.

Intensities are normalized by dividing by 16, using the stratified splits from lesson 1: 1078 training, 359 validation and 360 test examples. Curve points are measured over the full sets at the end of each epoch; the matrix uses validation data. Training stops at 100 epochs. Repeatedly querying the test set makes it no longer an independent final evaluation.

Preparing data and reproducible initial weights...

0.030
Epoch0
Updates0
Validation accuracyCalculating
Exploratory testNot queried
Pause and change the learning rate; compare filters and metrics calculated during training.

To allow interaction without blocking the page, this figure trains a reduced CNN on 8×8 images in a worker: one convolution, six filters, pooling and a linear layer. This lesson’s full LeNet appears below. The figure’s curves and confusion matrix measure current state with separate validation; repeated test inspection is exploratory and ceases to be an independent final evaluation.

From LeNet to the network you will build

Fukushima’s neocognitron organized units in hierarchical stages with unsupervised learning. LeCun and colleagues studied gradient-trained convolutional networks for document recognition and described a check-reading system. Original LeNet-5 takes 32×32 images and uses subsampling with learned parameters, partial connections in one layer and a distance-based output. This lesson’s network is a modernization, not a historical reproduction: it uses ReLU, max pooling, full channel connections and logits with cross-entropy.

The modernized LeNet architecture follows this path, omitting batch and ordering channels, height and width:

1×28×28→6×28×28→6×14×14→16×10×10→16×5×5→400→120→84→10.1\times28\times28 \to 6\times28\times28 \to 6\times14\times14 \to 16\times10\times10 \to 16\times5\times5 \to 400 \to 120 \to 84 \to 10.

Convolutions use 5×5 kernels; the first has padding 2 and the second adds none. Both are followed by ReLU and 2×2 max pooling with stride 2. The final ten values are logits: apply softmax to inspect probabilities, but not before cross-entropy that already accepts logits. Convolutional weights have shape output × input × height × width and are spatially shared, as in multichannel convolution.

The convolution, activation and reduction block separates three functions: mixing a neighborhood with learned weights, introducing nonlinearity and reducing resolution. Locality and sharing are different constraints. A common rule doubles channels when halving each spatial dimension: keeping the kernel and doubling input and output channels quadruples products per position while positions fall to a quarter. This is a useful approximation, not a cost law or architectural requirement; dimensions can differ at network endpoints.

For ungrouped convolution, k2CinCout+Coutk^2C_{\mathrm{in}}C_{\mathrm{out}}+C_{\mathrm{out}} counts weights and biases; a dense layer counts (din+1)dout(d_{\mathrm{in}}+1)d_{\mathrm{out}}. Parameters are shared across positions, but multiplications repeat at each output position. The final check cell counts parameters and operations separately: a MAC is a multiply-accumulate and, counting multiplication and addition separately, approximates two FLOPs. That convention excludes biases, ReLU, pooling and backward.

To count convolution compute, multiply spatial output positions by k2CinCoutk^2C_{\mathrm{in}}C_{\mathrm{out}}. The first layer has six one-channel filters, each with 25 coefficients and a bias: 6(25+1)6(25+1) parameters, although those filters are used at all 28×28 positions. A dense layer does not share weights across positions of its flattened input. Thus architectures with the same parameter count can perform different amounts of computation and have different inductive biases.

Data and checks before training

We use the same load_digits indices as the first lesson: 8×8 images divided by 16 and separate stratified splits. For this network we enlarge them to 28×28 by bilinear interpolation using the same rule for training, validation and test. Interpolation creates no new observations. The first lesson’s HOG classifier uses original images; a comparison must state that difference and each method’s split.

Before trusting a curve, test a fixed batch. If you cannot even reduce its loss, check labels, shapes, gradients, rate and update; passing does not prove generalization. With ten exactly equal logits, softmax assigns 1/101/10 to each class and cross-entropy is log⁡10\log 10. Ordinary initialization may yield different logits, so initial loss need not be exactly that number. Also inspect finite norms per layer: one zero gradient can be legitimate, but all zero throughout training deserves investigation. These are sanity checks, not complete correctness proofs.

In an SGD update with momentum, state v\vb{v} accumulates gradients and parameters follow its direction:

vt+1=μvt+∇θLt,θt+1=θt−ηvt+1.\vb{v}_{t+1}=\mu\vb{v}_t+\grad_\theta \Loss_t, \qquad \theta_{t+1}=\theta_t-\eta\vb{v}_{t+1}.

Here v0=0\vb{v}_0=0, without additional dampening or Nesterov correction. Before each backward pass clear leaf gradients: the engine accumulates them because one tensor can participate in several graph paths. In max pooling a window’s gradient goes to its maximum; at a tie this implementation selects the first position. At a tie or ReLU kink, a central finite difference may measure a combination of slopes different from the chosen subgradient. The numerical check uses continuous input and perturbed biases to avoid these cases and compares one informative component of each tensor: it does not replace an exhaustive test of all components.

For diagnosis, compare fixed-batch loss with training and validation loss separately. If training improves and validation worsens, the pattern is consistent with overfitting, though a noisy measurement does not prove it. If both losses are high, capacity, training or a suitable rate may be lacking. Nonfinite loss requires stopping and checking data, scale and rate. A graph alone cannot reliably distinguish broken backward from an excessively small rate: inspect gradients and verify parameters change.

Follow a prediction

InteractiveDraw and follow activations

The initial state shows an interpolated image from lesson 1 validation, subsequently used to train these models. You can erase it and draw on the grid. The input panel includes shifting without wraparound and thickening; both models receive exactly that tensor. A freehand drawing may differ from the digits used in training.

Draw here
Model input
Conv1 after ReLU, six channels
Conv2 after ReLU, sixteen channels
CNN
00.0 %
10.0 %
2100.0 %
30.0 %
40.0 %
50.0 %
60.0 %
70.0 %
80.0 %
90.0 %
MLP
00.0 %
10.0 %
2100.0 %
30.0 %
40.0 %
50.0 %
60.0 %
70.0 %
80.0 %
90.0 %

Weights from the short run with seed 16011 and 1437 examples. Each map is scaled separately to show its structure; brightness does not compare magnitudes across channels. Probabilities do not guarantee calibration.

0
0
0
CNN predicts2
MLP predicts2
Draw, shift or thicken the stroke and compare both models trained with the same number of parameters.

CNN maps are shown after ReLU. Their brightness is normalized per channel to show shape, so it cannot compare magnitudes across channels. Free drawing does not come from the digits dataset distribution: a confident prediction does not guarantee correctness. Shifting uses zeros outside the image without wrapping content around the opposite edge.

CNN and MLP with the same budget

Comparative sample efficiency asks how generalization changes as example count varies under an explicit training and evaluation protocol. Matching parameters does not match compute, depth, optimization or function family. Convolution shares the detector across positions, a useful assumption for some visual data; padding, subsampling and the final classifier mean a particular CNN is not automatically invariant to every shift.

InteractiveExamples and shifts

Accuracy on the same 360 test images. Images are not shifted. Both networks receive the same shifts. Small circles represent individual seeds and lines join their means.

0 %25 %50 %75 %100 %CNN, 128 examples, seed 16011: 61.7 %CNN, 128 examples, seed 16012: 86.9 %CNN, 128 examples, seed 16013: 40.3 %CNN, 512 examples, seed 16011: 96.1 %CNN, 512 examples, seed 16012: 96.7 %CNN, 512 examples, seed 16013: 96.9 %CNN, 1437 examples, seed 16011: 97.2 %CNN, 1437 examples, seed 16012: 98.1 %CNN, 1437 examples, seed 16013: 98.6 %MLP, 128 examples, seed 16011: 86.4 %MLP, 128 examples, seed 16012: 89.2 %MLP, 128 examples, seed 16013: 87.5 %MLP, 512 examples, seed 16011: 94.7 %MLP, 512 examples, seed 16012: 96.7 %MLP, 512 examples, seed 16013: 95.0 %MLP, 1437 examples, seed 16011: 96.9 %MLP, 1437 examples, seed 16012: 97.5 %MLP, 1437 examples, seed 16013: 97.8 %1285121437Training examples
  • CNN, mean
  • MLP, mean

Short run: three seeds, 15 epochs and batches of 64. Each model has 61,706 parameters; subsets are nested within each seed. The test set is from the HOG and SVM lesson; images are interpolated from 8×8 to 28×28. Matching parameters and epochs does not match functions, cost or the number of updates across sizes. An observed difference does not guarantee invariance or an advantage in other settings.

0 px
CNN, mean of three seeds98.0 %
MLP, mean of three seeds97.4 %
CNN minus MLP+0.6 points
Compare real CNN and MLP runs and observe variation between seeds.

The graph alone does not identify a cause for each difference: changing dataset size also changes update count if epochs are fixed. Interpret a learning curve alongside splits, budget and seeds, not as a universal architecture property.

In this short run each seed orders the training and validation set and takes nested prefixes; test remains separate. CNN and MLP receive the same indices and per-image shifts, and both use 15 epochs. Each position shifted outside the frame is discarded and the gap filled with zero. To interpret the figure, first compare both networks with zero shift, then change amplitude and inspect each seed as well as the mean. In particular, if a network receives fewer total updates with little data, the observed difference combines data, optimization and architecture. Matching epochs is an experimental choice to declare, not a guarantee of equal compute budget.

Lab: build, train and check

The autograd engine, layers and parameters, convolution weight gradient, input gradient, col2im and max pooling were developed in previous lessons. The following cells bring them together in a self-contained implementation. He initialization controls initial scale but does not itself guarantee correct training.

The first two cells load data and gather the engine already built. Then instantiate both networks, check one component of each parameter tensor with finite differences and train a short batch of updates. Keep the Python session: train_steps(20) continues from current weights, optimizer and generator. Each call is a batch of updates, not an epoch or complete training.

[ ]Data and splitsBrowser
# Laboratorio autocontenido: cada sección marcada # %% es una celda Python independiente.
# Ejecuta en orden, conserva la sesión y repite solo las funciones de tanda.

from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
import numpy as np

digits=load_digits()
images=digits.images.astype(np.float64)/16.0
labels=digits.target.astype(int)
ids=np.arange(len(labels))
train_ids,rest_ids=train_test_split(ids,test_size=.4,random_state=16001,stratify=labels)
valid_ids,test_ids=train_test_split(rest_ids,test_size=.5,random_state=16002,stratify=labels[rest_ids])
assert len(set(train_ids)&set(valid_ids))==len(set(train_ids)&set(test_ids))==len(set(valid_ids)&set(test_ids))==0

def resize28(batch):
    """Bilineal con centros de píxel, bordes extendidos; equivale a align_corners=False."""
    x=np.asarray(batch,dtype=np.float64)
    if x.ndim!=3 or x.shape[1:]!=(8,8): raise ValueError('Se espera N×8×8')
    coord=np.clip((np.arange(28)+.5)*8/28-.5,0,7)
    lo=np.floor(coord).astype(int);hi=np.minimum(lo+1,7); t=coord-lo
    vertical=x[:,lo,:]*(1-t)[None,:,None]+x[:,hi,:]*t[None,:,None]
    up=vertical[:,:,lo]*(1-t)[None,None,:]+vertical[:,:,hi]*t[None,None,:]
    return up[:,None,:,:]

X=resize28(images)
print('Particiones de l01:',len(train_ids),len(valid_ids),len(test_ids),'y datos:',X.shape)
assert X.shape==(1797,1,28,28) and np.isfinite(X).all()

The first figure uses these same 8×8 images, encoded with one character per intensity, and their split indices. This cell regenerates content received by the worker: its hash permits comparing the export without downloading data from an external service. Free drawing in the second interactive uses 28×28 models trained by the local lab, not this reduced model.

[ ]Interactive trainer dataBrowser
import hashlib
import json
alphabet='0123456789ABCDEFG'
export={'images':''.join(alphabet[int(value)] for value in digits.images.ravel()),
        'labels':''.join(str(value) for value in labels),
        'train':train_ids.tolist(),'valid':valid_ids.tolist(),'test':test_ids.tolist()}
payload=json.dumps(export,separators=(',',':')).encode('utf-8')
print('Imágenes, etiquetas y particiones:',len(export['images'])//64,len(export['labels']),
      len(export['train']),len(export['valid']),len(export['test']))
print('SHA-256 del JSON:',hashlib.sha256(payload).hexdigest())
[ ]Engine and layers from scratchBrowser
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

class Linear:
    def __init__(self, nin, nout, generator):
        self.weight = Tensor(generator.normal(0, np.sqrt(2/nin), (nin, nout)))
        self.bias = Tensor(np.zeros(nout))
    def __call__(self, x):
        return x @ self.weight + self.bias
    def parameters(self):
        return [self.weight, self.bias]

class MLP:
    def __init__(self, generator):
        self.hidden = Linear(64, 128, generator)
        self.output = Linear(128, 10, generator)
    def __call__(self, x):
        return self.output(self.hidden(x).relu())
    def parameters(self):
        return self.hidden.parameters() + self.output.parameters()

class SGD:
    def __init__(self, parameters, learning_rate, momentum):
        self.parameters = list(parameters)
        self.learning_rate = learning_rate
        self.momentum = momentum
        self.velocity = [np.zeros_like(p.data) for p in self.parameters]
    def zero_grad(self):
        for p in self.parameters:
            p.grad.fill(0)
    def step(self):
        for p, v in zip(self.parameters, self.velocity):
            v *= self.momentum
            v += p.grad
            p.data -= self.learning_rate*v

import numpy as np

def pair(v):
    return (v, v) if isinstance(v, int) else tuple(v)

def geometry(shape, kernel, stride=1, padding=0, dilation=1):
    n, c, h, w = shape
    kh, kw = pair(kernel); sh, sw = pair(stride)
    ph, pw = pair(padding); dh, dw = pair(dilation)
    if min(n, c, h, w, kh, kw, sh, sw, dh, dw) <= 0 or min(ph, pw) < 0:
        raise ValueError('dimensiones inválidas')
    oh = (h + 2*ph - dh*(kh-1) - 1)//sh + 1
    ow = (w + 2*pw - dw*(kw-1) - 1)//sw + 1
    if min(oh, ow) <= 0:
        raise ValueError('el núcleo no cabe')
    return n, c, h, w, kh, kw, sh, sw, ph, pw, dh, dw, oh, ow

def im2col(x, kernel, stride=1, padding=0, dilation=1):
    n,c,h,w,kh,kw,sh,sw,ph,pw,dh,dw,oh,ow = geometry(x.shape, kernel, stride, padding, dilation)
    xp = np.pad(x, ((0,0),(0,0),(ph,ph),(pw,pw)))
    cols = np.empty((c*kh*kw, n*oh*ow), dtype=x.dtype)
    for i in range(oh):
        for j in range(ow):
            patch = xp[:,:,i*sh:i*sh+dh*(kh-1)+1:dh,j*sw:j*sw+dw*(kw-1)+1:dw]
            cols[:, i*ow+j::oh*ow] = patch.reshape(n, -1).T
    return cols

def col2im(cols, shape, kernel, stride=1, padding=0, dilation=1):
    n,c,h,w,kh,kw,sh,sw,ph,pw,dh,dw,oh,ow = geometry(shape, kernel, stride, padding, dilation)
    if cols.shape != (c*kh*kw, n*oh*ow):
        raise ValueError('forma de columnas incorrecta')
    xp = np.zeros((n,c,h+2*ph,w+2*pw), dtype=cols.dtype)
    for i in range(oh):
        for j in range(ow):
            patch = cols[:, i*ow+j::oh*ow].T.reshape(n,c,kh,kw)
            xp[:,:,i*sh:i*sh+dh*(kh-1)+1:dh,j*sw:j*sw+dw*(kw-1)+1:dw] += patch
    return xp[:,:,ph:ph+h,pw:pw+w]

def conv_forward(x, weight, bias, stride=1, padding=0, dilation=1):
    out_channels, channels, kh, kw = weight.shape
    if channels != x.shape[1] or bias.shape != (out_channels,):
        raise ValueError('canales o sesgo incompatibles')
    g = geometry(x.shape, (kh,kw), stride, padding, dilation)
    n, oh, ow = g[0], g[-2], g[-1]
    cols = im2col(x, (kh,kw), stride, padding, dilation)
    out = (weight.reshape(out_channels,-1) @ cols + bias[:,None]).reshape(out_channels,n,oh,ow).transpose(1,0,2,3)
    cache = (x.shape, weight.copy(), cols.copy(), pair(stride), pair(padding), pair(dilation))
    return out, cache

def conv_backward(grad, cache):
    shape, weight, cols, stride, padding, dilation = cache
    n, cout, oh, ow = grad.shape
    expected = geometry(shape, weight.shape[2:], stride, padding, dilation)
    if (n,cout,oh,ow) != (shape[0],weight.shape[0],expected[-2],expected[-1]):
        raise ValueError('forma del gradiente incorrecta')
    g = grad.transpose(1,0,2,3).reshape(cout,-1)
    dw = (g @ cols.T).reshape(weight.shape)
    db = g.sum(axis=1)
    dx = col2im(weight.reshape(cout,-1).T @ g, shape, weight.shape[2:], stride, padding, dilation)
    return dx, dw, db


# La celda anterior define im2col, col2im, conv_forward y conv_backward.
# Antes de esta celda ejecuta la definición íntegra de Tensor de m15-l09.
def conv_tensor(x, weight, bias, stride=1, padding=0, dilation=1):
    y, cache = conv_forward(x.data, weight.data, bias.data, stride, padding, dilation)
    out = Tensor(y, (x,weight,bias))
    def backward():
        dx,dw,db = conv_backward(out.grad,cache)
        x.grad += dx; weight.grad += dw; bias.grad += db
    out._backward = backward
    return out

class Conv2d:
    def __init__(self, weight, bias, stride=1, padding=0, dilation=1):
        self.weight = Tensor(weight)
        self.bias = Tensor(bias)
        self.stride, self.padding, self.dilation = stride, padding, dilation

    def forward(self, x):
        return conv_tensor(x,self.weight,self.bias,self.stride,self.padding,self.dilation)

    def parameters(self):
        return [self.weight,self.bias]


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
[ ]Two architecturesBrowser
class LeNet:
    def __init__(self, generator):
        self.conv1=Conv2d(generator.normal(0,np.sqrt(2/25),(6,1,5,5)),np.zeros(6),padding=2)
        self.conv2=Conv2d(generator.normal(0,np.sqrt(2/150),(16,6,5,5)),np.zeros(16))
        self.pool=MaxPool2d(2,2)
        self.fc1=Linear(400,120,generator)
        self.fc2=Linear(120,84,generator)
        self.fc3=Linear(84,10,generator)
    def __call__(self,x):
        x=self.pool.forward(self.conv1.forward(x).relu())
        x=self.pool.forward(self.conv2.forward(x).relu())
        x=x.reshape(x.data.shape[0],400)
        return self.fc3(self.fc2(self.fc1(x).relu()).relu())
    def parameters(self):
        return (self.conv1.parameters()+self.conv2.parameters()+self.fc1.parameters()
                +self.fc2.parameters()+self.fc3.parameters())

class MatchedMLP:
    def __init__(self,generator):
        self.layers=[Linear(a,b,generator) for a,b in [(784,65),(65,76),(76,65),(65,10)]]
    def __call__(self,x):
        x=x.reshape(x.data.shape[0],784)
        for layer in self.layers[:-1]: x=layer(x).relu()
        return self.layers[-1](x)
    def parameters(self): return [p for layer in self.layers for p in layer.parameters()]

model=LeNet(np.random.default_rng(16006))
baseline=MatchedMLP(np.random.default_rng(16006))
print('Parámetros LeNet, MLP:',sum(p.data.size for p in model.parameters()),sum(p.data.size for p in baseline.parameters()))
assert sum(p.data.size for p in model.parameters())==sum(p.data.size for p in baseline.parameters())==61706
uniform=Tensor(np.zeros((8,10)))
print('CE de diez logits iguales:',cross_entropy(uniform,np.arange(8)%10).data)
[ ]Numerical backward checkBrowser
# Gradcheck de toda la red: una componente informativa por parámetro.
# Las diferencias centrales se calculan fuera de posibles cambios de argmax.
check_model=LeNet(np.random.default_rng(16008))
check_rng=np.random.default_rng(16010)
check_x=check_rng.normal(size=(2,1,28,28))
check_y=np.array([2,7])
# Rompe empates sistemáticos y evita los codos de ReLU en este control.
for parameter in check_model.parameters()[1::2]:
    parameter.data[:]=check_rng.normal(scale=.01,size=parameter.data.shape)
check_loss=cross_entropy(check_model(Tensor(check_x)),check_y)
check_loss.backward()
errors=[]
for parameter in check_model.parameters():
    pos=np.unravel_index(np.argmax(np.abs(parameter.grad)),parameter.grad.shape)
    analytic=float(parameter.grad[pos])
    old=parameter.data[pos]
    eps=1e-5
    parameter.data[pos]=old+eps
    plus=float(cross_entropy(check_model(Tensor(check_x)),check_y).data)
    parameter.data[pos]=old-eps
    minus=float(cross_entropy(check_model(Tensor(check_x)),check_y).data)
    parameter.data[pos]=old
    numerical=(plus-minus)/(2*eps)
    errors.append(abs(analytic-numerical))
print('Gradcheck por tensor: errores máximos',errors)
assert max(errors)<1e-6
[ ]Training in batchesBrowser
# Estado de entrenamiento: se conserva al ejecutar más tandas.
batch_rng=np.random.default_rng(16007)
optimizer=SGD(model.parameters(),learning_rate=.02,momentum=.9)
history=[]
training_closed=False
initial_filters=model.conv1.weight.data.copy()

def train_steps(steps=4,batch_size=8):
    if training_closed: raise RuntimeError('El ensayo terminó al evaluar test; reinicia para entrenar otra vez')
    if steps<1 or batch_size<1: raise ValueError('pasos y lote deben ser positivos')
    for _ in range(steps):
        batch=batch_rng.choice(train_ids,size=batch_size,replace=False)
        optimizer.zero_grad()
        logits=model(Tensor(X[batch]))
        loss=cross_entropy(logits,labels[batch])
        if not np.isfinite(loss.data): raise FloatingPointError('pérdida no finita')
        loss.backward()
        norms=[float(np.linalg.norm(p.grad)) for p in model.parameters()]
        if not all(np.isfinite(norms)): raise FloatingPointError('gradiente no finito')
        acc=float(np.mean(logits.data.argmax(axis=1)==labels[batch]))
        history.append({'step':len(history)+1,'loss':float(loss.data),'accuracy':acc,'gradient_norms':norms})
        optimizer.step()
    return history[-1]

print('Primera tanda:',train_steps())
print('Filtros iniciales:',initial_filters.shape,'filtros actuales:',model.conv1.weight.data.shape)
[ ]Incremental validationBrowser
# Validación incremental para mantener cada llamada breve; no consultar test para ajustar.
validation={'cursor':0,'step':len(history),'confusion':np.zeros((10,10),dtype=np.int64)}
def validation_chunk(batch_size=16):
    if validation['step']!=len(history):
        raise RuntimeError('El modelo cambió: reinicia la validación antes de continuar')
    start=validation['cursor']
    ids=valid_ids[start:start+batch_size]
    if len(ids):
        pred=np.argmax(model(Tensor(X[ids])).data,axis=1)
        np.add.at(validation['confusion'],(labels[ids],pred),1)
        validation['cursor']+=len(ids)
    cm=validation['confusion']
    return {'contados':int(cm.sum()),'aciertos':int(np.trace(cm)),
            'exactitud':float(np.trace(cm)/cm.sum()) if cm.sum() else None,
            'completa':validation['cursor']==len(valid_ids)}
print('Primer fragmento de validación:',validation_chunk())
# Antes de medir otra versión del modelo:
# validation={'cursor':0,'step':len(history),'confusion':np.zeros((10,10),dtype=np.int64)}
# Repite validation_chunk() hasta completa. cm = validation['confusion'].
[ ]Overfit one batchBrowser
# Test de cordura: red y optimizador independientes, lote fijo, sin alterar model.
overfit_model=LeNet(np.random.default_rng(16009))
overfit_optimizer=SGD(overfit_model.parameters(),learning_rate=.02,momentum=.9)
overfit_ids=train_ids[:8]
overfit_history=[]
def overfit_steps(steps=4):
    for _ in range(steps):
        overfit_optimizer.zero_grad()
        logits=overfit_model(Tensor(X[overfit_ids]))
        loss=cross_entropy(logits,labels[overfit_ids])
        loss.backward()
        overfit_optimizer.step()
        overfit_history.append(float(loss.data))
    final_logits=overfit_model(Tensor(X[overfit_ids])).data
    return {'pasos':len(overfit_history),'inicial':overfit_history[0],
            'actual':float(cross_entropy(Tensor(final_logits),labels[overfit_ids]).data),
            'exactitud':float(np.mean(final_logits.argmax(axis=1)==labels[overfit_ids]))}
print('Primera tanda de sobreajuste:',overfit_steps())
# Repite overfit_steps() y compara pérdida y exactitud en el mismo lote.

The next control injects a specific fault: it computes backward and then zeros all gradients before updating. Both networks start from the same weights and see the same batch. The broken control retains its parameters; the other should show progress. This is a deliberate detectable fault, not a representation of every possible backward error.

[ ]Detect broken backwardBrowser
good=LeNet(np.random.default_rng(16009))
broken=LeNet(np.random.default_rng(16009))
good_opt=SGD(good.parameters(),learning_rate=.02,momentum=.9)
broken_opt=SGD(broken.parameters(),learning_rate=.02,momentum=.9)
fixed=train_ids[:8]
def fixed_loss(net): return float(cross_entropy(net(Tensor(X[fixed])),labels[fixed]).data)
before_good=fixed_loss(good);before_broken=fixed_loss(broken)
for _ in range(4):
    for net,opt,is_broken in ((good,good_opt,False),(broken,broken_opt,True)):
        opt.zero_grad()
        loss=cross_entropy(net(Tensor(X[fixed])),labels[fixed])
        loss.backward()
        if is_broken:
            for p in net.parameters(): p.grad.fill(0)
        opt.step()
after_good=fixed_loss(good);after_broken=fixed_loss(broken)
print('Pérdida correcta:',before_good,'→',after_good)
print('Pérdida con gradientes anulados:',before_broken,'→',after_broken)
assert after_good<before_good and after_broken==before_broken

Complete training without freezing the page

The initial batch performed four updates. To reproduce the recorded trial, run the next cell ten times, evaluate validation with the following cell and repeat that cycle six times. This measures steps 204, 404, 604, 804, 1004 and 1204. The validation cell saves a copy of the first checkpoint with best accuracy; do not consult test to choose it. Each batch run keeps work bounded. You can train more, but redefine model selection in advance and reserve another set if you already consulted test.

[ ]A batch of 20 updatesBrowser
print('Último minilote:',train_steps(20))
[ ]Validate and keep the best checkpointBrowser
if 'best' not in globals():
    best={'score':-1.0,'step':0,'params':None}
    evaluations=[]
expected=[204,404,604,804,1004,1204]
if len(evaluations)>=len(expected) or len(history)!=expected[len(evaluations)]:
    print('La próxima validación corresponde al paso',expected[len(evaluations)] if len(evaluations)<len(expected) else 'ninguno')
else:
    predictions=[]
    for start in range(0,len(valid_ids),16):
        ids=valid_ids[start:start+16]
        predictions.extend(np.argmax(model(Tensor(X[ids])).data,axis=1).tolist())
    score=float(np.mean(np.asarray(predictions)==labels[valid_ids]))
    evaluations.append((len(history),score))
    if score>best['score']:
        best={'score':score,'step':len(history),'params':[p.data.copy() for p in model.parameters()]}
    print('Validación, paso y exactitud:',evaluations[-1],'; mejor paso:',best['step'])

Once all six cycles are complete, run the test cell once. The condition checks all six checkpoints and prevents an automatic run of every cell from treating the one-batch model as final. The validation-selected checkpoint is restored and a matrix with true rows and predicted columns is printed. The trial then closes: to train again, restart the experiment, because prior momentum corresponds to other weights.

[ ]Held-out final evaluationBrowser
if training_closed:
    print('Test ya consultado; reinicia el experimento para volver a entrenar.')
elif len(history)!=1204 or [step for step,_ in evaluations]!=[204,404,604,804,1004,1204] or best['params'] is None:
    print('Completa primero los seis ciclos de entrenamiento y validación.')
else:
    for parameter,saved in zip(model.parameters(),best['params']):
        parameter.data[:]=saved
    predicted=[]
    for start in range(0,len(test_ids),16):
        ids=test_ids[start:start+16]
        predicted.extend(np.argmax(model(Tensor(X[ids])).data,axis=1).tolist())
    confusion=np.zeros((10,10),dtype=int)
    np.add.at(confusion,(labels[test_ids],predicted),1)
    print('Checkpoint elegido:',best['step'],'validación:',best['score'])
    print('Test, aciertos y total:',int(np.trace(confusion)),int(confusion.sum()))
    print('Matriz de confusión:'); print(confusion)
    training_closed=True

The next cell contains the record of an earlier run, not the current state’s result: it was obtained in Pyodide with the same seeds, batches and selection rule. Use it to compare your reproduction. That run chose the first validation maximum at step 804 and got 343 of 360 test examples correct. The first lesson’s HOG plus SVM cell got 312 of 360 on the same indices, with a protocol difference: that baseline was retrained on training plus validation, while this CNN used only training. This comparison is exploratory: the same test also appears in the race figure and can be consulted in the trainer. One seed and one test set do not prove universal superiority.

[ ]Reference run recordBrowser
# Salida de la ejecución de 1204 pasos descrita arriba; no se recalcula aquí.
recorded_validation=[(204,314/359),(404,321/359),(604,323/359),
                     (804,336/359),(1004,335/359),(1204,336/359)]
selected=max(recorded_validation,key=lambda row:row[1])
print('Validación registrada:',recorded_validation,'; primer máximo:',selected)
print('Aciertos en test, CNN y HOG:',343,312,'de',360)

To review curves and filters in your current state, inspect history and initial_filters, and compare with model.conv1.weight.data. After running test, if you need more tuning, do not treat the same test as an independent evaluation again. The overfitting check uses another network and optimizer to avoid contaminating the main experiment.

[ ]Network curve and filtersBrowser
import matplotlib.pyplot as plt

fig,axes=plt.subplots(2,6,figsize=(9,3))
limit=max(np.max(np.abs(initial_filters)),np.max(np.abs(model.conv1.weight.data)),1e-12)
for i in range(6):
    for row,weights in enumerate((initial_filters,model.conv1.weight.data)):
        axes[row,i].imshow(weights[i,0],cmap='coolwarm',vmin=-limit,vmax=limit)
        axes[row,i].set_axis_off()
axes[0,0].set_title('Inicial'); axes[1,0].set_title('Actual')
fig.tight_layout(); plt.show()
fig,ax=plt.subplots(figsize=(6,2.5))
ax.plot([r['step'] for r in history],[r['loss'] for r in history])
ax.set(xlabel='Actualización',ylabel='Pérdida del minilote')
fig.tight_layout(); plt.show()

The next local cell compares logits and gradients of both implementations with copied weights, trains CNN and MLP with the same parameter count and records curves used in the figure. Verification uses three seeds and 15 epochs; unless you set ORYON_VERIFY_SHORT=1, it proposes five seeds and 50 epochs for your run. Size selection, normalization, padding and step count are in the program. The cost ratio is a measurement for that machine and protocol, not a prediction for Pyodide.

[ ]Parity and comparison with PyTorchLocal GPU
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
import numpy as np

digits=load_digits()
images=digits.images.astype(np.float64)/16.0
labels=digits.target.astype(int)
ids=np.arange(len(labels))
train_ids,rest_ids=train_test_split(ids,test_size=.4,random_state=16001,stratify=labels)
valid_ids,test_ids=train_test_split(rest_ids,test_size=.5,random_state=16002,stratify=labels[rest_ids])
assert len(set(train_ids)&set(valid_ids))==len(set(train_ids)&set(test_ids))==len(set(valid_ids)&set(test_ids))==0

def resize28(batch):
    """Bilineal con centros de píxel, bordes extendidos; equivale a align_corners=False."""
    x=np.asarray(batch,dtype=np.float64)
    if x.ndim!=3 or x.shape[1:]!=(8,8): raise ValueError('Se espera N×8×8')
    coord=np.clip((np.arange(28)+.5)*8/28-.5,0,7)
    lo=np.floor(coord).astype(int);hi=np.minimum(lo+1,7); t=coord-lo
    vertical=x[:,lo,:]*(1-t)[None,:,None]+x[:,hi,:]*t[None,:,None]
    up=vertical[:,:,lo]*(1-t)[None,None,:]+vertical[:,:,hi]*t[None,None,:]
    return up[:,None,:,:]

X=resize28(images)
print('Particiones de l01:',len(train_ids),len(valid_ids),len(test_ids),'y datos:',X.shape)
assert X.shape==(1797,1,28,28) and np.isfinite(X).all()


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

class Linear:
    def __init__(self, nin, nout, generator):
        self.weight = Tensor(generator.normal(0, np.sqrt(2/nin), (nin, nout)))
        self.bias = Tensor(np.zeros(nout))
    def __call__(self, x):
        return x @ self.weight + self.bias
    def parameters(self):
        return [self.weight, self.bias]

class MLP:
    def __init__(self, generator):
        self.hidden = Linear(64, 128, generator)
        self.output = Linear(128, 10, generator)
    def __call__(self, x):
        return self.output(self.hidden(x).relu())
    def parameters(self):
        return self.hidden.parameters() + self.output.parameters()

class SGD:
    def __init__(self, parameters, learning_rate, momentum):
        self.parameters = list(parameters)
        self.learning_rate = learning_rate
        self.momentum = momentum
        self.velocity = [np.zeros_like(p.data) for p in self.parameters]
    def zero_grad(self):
        for p in self.parameters:
            p.grad.fill(0)
    def step(self):
        for p, v in zip(self.parameters, self.velocity):
            v *= self.momentum
            v += p.grad
            p.data -= self.learning_rate*v

import numpy as np

def pair(v):
    return (v, v) if isinstance(v, int) else tuple(v)

def geometry(shape, kernel, stride=1, padding=0, dilation=1):
    n, c, h, w = shape
    kh, kw = pair(kernel); sh, sw = pair(stride)
    ph, pw = pair(padding); dh, dw = pair(dilation)
    if min(n, c, h, w, kh, kw, sh, sw, dh, dw) <= 0 or min(ph, pw) < 0:
        raise ValueError('dimensiones inválidas')
    oh = (h + 2*ph - dh*(kh-1) - 1)//sh + 1
    ow = (w + 2*pw - dw*(kw-1) - 1)//sw + 1
    if min(oh, ow) <= 0:
        raise ValueError('el núcleo no cabe')
    return n, c, h, w, kh, kw, sh, sw, ph, pw, dh, dw, oh, ow

def im2col(x, kernel, stride=1, padding=0, dilation=1):
    n,c,h,w,kh,kw,sh,sw,ph,pw,dh,dw,oh,ow = geometry(x.shape, kernel, stride, padding, dilation)
    xp = np.pad(x, ((0,0),(0,0),(ph,ph),(pw,pw)))
    cols = np.empty((c*kh*kw, n*oh*ow), dtype=x.dtype)
    for i in range(oh):
        for j in range(ow):
            patch = xp[:,:,i*sh:i*sh+dh*(kh-1)+1:dh,j*sw:j*sw+dw*(kw-1)+1:dw]
            cols[:, i*ow+j::oh*ow] = patch.reshape(n, -1).T
    return cols

def col2im(cols, shape, kernel, stride=1, padding=0, dilation=1):
    n,c,h,w,kh,kw,sh,sw,ph,pw,dh,dw,oh,ow = geometry(shape, kernel, stride, padding, dilation)
    if cols.shape != (c*kh*kw, n*oh*ow):
        raise ValueError('forma de columnas incorrecta')
    xp = np.zeros((n,c,h+2*ph,w+2*pw), dtype=cols.dtype)
    for i in range(oh):
        for j in range(ow):
            patch = cols[:, i*ow+j::oh*ow].T.reshape(n,c,kh,kw)
            xp[:,:,i*sh:i*sh+dh*(kh-1)+1:dh,j*sw:j*sw+dw*(kw-1)+1:dw] += patch
    return xp[:,:,ph:ph+h,pw:pw+w]

def conv_forward(x, weight, bias, stride=1, padding=0, dilation=1):
    out_channels, channels, kh, kw = weight.shape
    if channels != x.shape[1] or bias.shape != (out_channels,):
        raise ValueError('canales o sesgo incompatibles')
    g = geometry(x.shape, (kh,kw), stride, padding, dilation)
    n, oh, ow = g[0], g[-2], g[-1]
    cols = im2col(x, (kh,kw), stride, padding, dilation)
    out = (weight.reshape(out_channels,-1) @ cols + bias[:,None]).reshape(out_channels,n,oh,ow).transpose(1,0,2,3)
    cache = (x.shape, weight.copy(), cols.copy(), pair(stride), pair(padding), pair(dilation))
    return out, cache

def conv_backward(grad, cache):
    shape, weight, cols, stride, padding, dilation = cache
    n, cout, oh, ow = grad.shape
    expected = geometry(shape, weight.shape[2:], stride, padding, dilation)
    if (n,cout,oh,ow) != (shape[0],weight.shape[0],expected[-2],expected[-1]):
        raise ValueError('forma del gradiente incorrecta')
    g = grad.transpose(1,0,2,3).reshape(cout,-1)
    dw = (g @ cols.T).reshape(weight.shape)
    db = g.sum(axis=1)
    dx = col2im(weight.reshape(cout,-1).T @ g, shape, weight.shape[2:], stride, padding, dilation)
    return dx, dw, db


# La celda anterior define im2col, col2im, conv_forward y conv_backward.
# Antes de esta celda ejecuta la definición íntegra de Tensor de m15-l09.
def conv_tensor(x, weight, bias, stride=1, padding=0, dilation=1):
    y, cache = conv_forward(x.data, weight.data, bias.data, stride, padding, dilation)
    out = Tensor(y, (x,weight,bias))
    def backward():
        dx,dw,db = conv_backward(out.grad,cache)
        x.grad += dx; weight.grad += dw; bias.grad += db
    out._backward = backward
    return out

class Conv2d:
    def __init__(self, weight, bias, stride=1, padding=0, dilation=1):
        self.weight = Tensor(weight)
        self.bias = Tensor(bias)
        self.stride, self.padding, self.dilation = stride, padding, dilation

    def forward(self, x):
        return conv_tensor(x,self.weight,self.bias,self.stride,self.padding,self.dilation)

    def parameters(self):
        return [self.weight,self.bias]


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


class LeNet:
    def __init__(self, generator):
        self.conv1=Conv2d(generator.normal(0,np.sqrt(2/25),(6,1,5,5)),np.zeros(6),padding=2)
        self.conv2=Conv2d(generator.normal(0,np.sqrt(2/150),(16,6,5,5)),np.zeros(16))
        self.pool=MaxPool2d(2,2)
        self.fc1=Linear(400,120,generator)
        self.fc2=Linear(120,84,generator)
        self.fc3=Linear(84,10,generator)
    def __call__(self,x):
        x=self.pool.forward(self.conv1.forward(x).relu())
        x=self.pool.forward(self.conv2.forward(x).relu())
        x=x.reshape(x.data.shape[0],400)
        return self.fc3(self.fc2(self.fc1(x).relu()).relu())
    def parameters(self):
        return (self.conv1.parameters()+self.conv2.parameters()+self.fc1.parameters()
                +self.fc2.parameters()+self.fc3.parameters())

class MatchedMLP:
    def __init__(self,generator):
        self.layers=[Linear(a,b,generator) for a,b in [(784,65),(65,76),(76,65),(65,10)]]
    def __call__(self,x):
        x=x.reshape(x.data.shape[0],784)
        for layer in self.layers[:-1]: x=layer(x).relu()
        return self.layers[-1](x)
    def parameters(self): return [p for layer in self.layers for p in layer.parameters()]

model=LeNet(np.random.default_rng(16006))
baseline=MatchedMLP(np.random.default_rng(16006))
print('Parámetros LeNet, MLP:',sum(p.data.size for p in model.parameters()),sum(p.data.size for p in baseline.parameters()))
assert sum(p.data.size for p in model.parameters())==sum(p.data.size for p in baseline.parameters())==61706
uniform=Tensor(np.zeros((8,10)))
print('CE de diez logits iguales:',cross_entropy(uniform,np.arange(8)%10).data)


import json
import os
from pathlib import Path
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG',':4096:8')
import torch
from torch import nn

torch.set_num_threads(1)
torch.manual_seed(16006)
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.benchmark=False
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
short=os.environ.get('ORYON_VERIFY_SHORT')=='1'
seeds=[16011,16012,16013] if short else [16011,16012,16013,16014,16015]
sizes=[128,512,1437] if short else [128,256,512,1024,1437]
epochs=15 if short else 50
batch_size=64

class TorchLeNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1=nn.Conv2d(1,6,5,padding=2); self.conv2=nn.Conv2d(6,16,5)
        self.fc1=nn.Linear(400,120);self.fc2=nn.Linear(120,84);self.fc3=nn.Linear(84,10)
    def forward(self,x):
        x=torch.nn.functional.max_pool2d(torch.relu(self.conv1(x)),2)
        x=torch.nn.functional.max_pool2d(torch.relu(self.conv2(x)),2)
        x=x.reshape(x.shape[0],400)
        return self.fc3(torch.relu(self.fc2(torch.relu(self.fc1(x)))))

class TorchMLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.layers=nn.ModuleList([nn.Linear(a,b) for a,b in [(784,65),(65,76),(76,65),(65,10)]])
    def forward(self,x):
        x=x.reshape(x.shape[0],784)
        for layer in self.layers[:-1]: x=torch.relu(layer(x))
        return self.layers[-1](x)

def transfer(own,net):
    """Conv OIHW igual; matrices densas de (entrada,salida) a (salida,entrada)."""
    torch_layers=([net.conv1,net.conv2,net.fc1,net.fc2,net.fc3] if isinstance(net,TorchLeNet) else list(net.layers))
    own_layers=([own.conv1,own.conv2,own.fc1,own.fc2,own.fc3] if isinstance(net,TorchLeNet) else own.layers)
    with torch.no_grad():
        for source,target in zip(own_layers,torch_layers):
            weights=source.weight.data if isinstance(target,nn.Conv2d) else source.weight.data.T
            target.weight.copy_(torch.from_numpy(weights));target.bias.copy_(torch.from_numpy(source.bias.data))

def verify_parity(kind):
    own=LeNet(np.random.default_rng(16006)) if kind=='cnn' else MatchedMLP(np.random.default_rng(16006))
    net=(TorchLeNet() if kind=='cnn' else TorchMLP()).double().to(device)
    transfer(own,net)
    batch=train_ids[:4]
    xx=Tensor(X[batch]);scores=own(xx);loss=cross_entropy(scores,labels[batch]);loss.backward()
    tx=torch.tensor(X[batch],device=device,dtype=torch.float64,requires_grad=True)
    ty=net(tx); tl=torch.nn.functional.cross_entropy(ty,torch.tensor(labels[batch],device=device));tl.backward()
    err_logits=float(np.max(np.abs(scores.data-ty.detach().cpu().numpy())))
    err_input=float(np.max(np.abs(xx.grad-tx.grad.cpu().numpy())))
    errors=[]
    torch_layers=([net.conv1,net.conv2,net.fc1,net.fc2,net.fc3] if kind=='cnn' else list(net.layers))
    params=own.parameters()
    for i,layer in enumerate(torch_layers):
        wg=layer.weight.grad.cpu().numpy()
        if not isinstance(layer,nn.Conv2d): wg=wg.T
        errors.extend([float(np.max(np.abs(params[2*i].grad-wg))),
                       float(np.max(np.abs(params[2*i+1].grad-layer.bias.grad.cpu().numpy())))])
    print(kind,'logits:',err_logits,'input:',err_input,'máximo gradiente por parámetro:',max(errors))
    assert max([err_logits,err_input]+errors)<1e-9
    return {'logits':err_logits,'input_gradient':err_input,'parameter_gradients':errors}

parity={kind:verify_parity(kind) for kind in ('cnn','mlp')}
source=torch.tensor(X,dtype=torch.float32,device=device)
target=torch.tensor(labels,dtype=torch.long,device=device)
pool=np.concatenate([train_ids,valid_ids])
assert len(pool)==1437 and not set(pool)&set(test_ids)

def shift_batch(images,offsets):
    out=torch.zeros_like(images)
    for i,(dy,dx) in enumerate(offsets):
        dy,dx=int(dy),int(dx)
        ya,yb=max(0,dy),min(28,28+dy);xa,xb=max(0,dx),min(28,28+dx)
        out[i,:,ya:yb,xa:xb]=images[i,:,ya-dy:yb-dy,xa-dx:xb-dx]
    return out

offsets={a:np.random.default_rng(17777+a).integers(-a,a+1,size=(len(test_ids),2)) for a in range(5)}
test_images={a:shift_batch(source[test_ids],offsets[a]) for a in offsets}
records=[];weights={}
for seed in seeds:
    order=np.random.default_rng(seed).permutation(pool)
    for size in sizes:
        subset=order[:size]
        for kind in ('cnn','mlp'):
            own=LeNet(np.random.default_rng(seed)) if kind=='cnn' else MatchedMLP(np.random.default_rng(seed))
            net=(TorchLeNet() if kind=='cnn' else TorchMLP()).to(device)
            transfer(own,net)
            assert sum(p.numel() for p in net.parameters())==61706
            opt=torch.optim.SGD(net.parameters(),lr=.02,momentum=.9)
            shuffle=np.random.default_rng(seed+1000)
            for epoch in range(epochs):
                net.train()
                permutation=shuffle.permutation(subset)
                for i in range(0,size,batch_size):
                    batch=permutation[i:i+batch_size]
                    opt.zero_grad(set_to_none=True)
                    scores=net(source[batch]);loss=torch.nn.functional.cross_entropy(scores,target[batch])
                    if not torch.isfinite(loss): raise FloatingPointError('pérdida no finita')
                    loss.backward();opt.step()
            net.eval()
            accuracies=[];confusion=None
            with torch.inference_mode():
                for a in range(5):
                    predicted=torch.cat([net(test_images[a][i:i+64]).argmax(1) for i in range(0,len(test_ids),64)]).cpu().numpy()
                    accuracies.append(float(np.mean(predicted==labels[test_ids])))
                    if a==0:
                        confusion=np.zeros((10,10),dtype=int)
                        np.add.at(confusion,(labels[test_ids],predicted),1)
            records.append({'seed':seed,'size':size,'model':kind,'accuracy_by_shift':accuracies,'confusion':confusion.tolist()})
            if seed==seeds[0] and size==1437:
                weights[kind]={name:value.detach().cpu().tolist() for name,value in net.state_dict().items()}
            print('semilla',seed,'n',size,kind,'precisiones',accuracies)
            del opt,net,own
            if device.type=='cuda': torch.cuda.empty_cache()

out=Path(os.environ.get('ORYON_LENET_OUTPUT','m16-l06-lenet.json'))
result={'seed_protocol':seeds,'sizes':sizes,'epochs':epochs,'batch_size':batch_size,'device':str(device),
        'initialization':'NumPy He, semillas indicadas; pesos copiados a PyTorch',
        'train_pool':'indices train+valid de m16-l01; subconjuntos anidados por semilla',
        'test':'360 índices de test de m16-l01; desplazamientos enteros 0..4, relleno cero',
        'parity_float64':parity,'offsets':{str(k):v.tolist() for k,v in offsets.items()},
        'records':records,'weights_seed':seeds[0],'weights':weights}
out.write_text(json.dumps(result,ensure_ascii=False,allow_nan=False),encoding='utf-8')
print('JSON:',out)

from time import perf_counter
def run(kind):
    own = LeNet(np.random.default_rng(16006))
    if kind == 'torch':
        net = TorchLeNet().double().to(device)
        transfer(own, net)
        opt = torch.optim.SGD(net.parameters(), lr=.02, momentum=.9)
    else:
        net = own
        opt = SGD(own.parameters(), learning_rate=.02, momentum=.9)
    batches = np.array_split(train_ids[:32], 4)
    if device.type == 'cuda':
        torch.cuda.synchronize()
    start = perf_counter()
    for batch in batches:
        if kind == 'torch':
            opt.zero_grad(set_to_none=True)
            tx = torch.tensor(X[batch], dtype=torch.float64, device=device)
            ty = torch.tensor(labels[batch], dtype=torch.long, device=device)
            loss = torch.nn.functional.cross_entropy(net(tx), ty)
        else:
            opt.zero_grad()
            loss = cross_entropy(net(Tensor(X[batch])), labels[batch])
        loss.backward()
        opt.step()
    if device.type == 'cuda':
        torch.cuda.synchronize()
    elapsed = perf_counter() - start
    if kind == 'torch':
        params = []
        for layer in (net.conv1, net.conv2, net.fc1, net.fc2, net.fc3):
            w = layer.weight.detach().cpu().numpy()
            params.extend([w if w.ndim == 4 else w.T, layer.bias.detach().cpu().numpy()])
    else:
        params = [p.data for p in own.parameters()]
    return elapsed, [p.copy() for p in params]


# Ambos caminos reciben calentamiento completo fuera de la medición.
run('numpy')
run('torch')
numpy_time, numpy_params = run('numpy')
torch_time, torch_params = run('torch')
error = max(float(np.max(np.abs(a - b))) for a, b in zip(numpy_params, torch_params))
assert error < 1e-8, error
print('Pasos comparados: 4; lote: 8; float64; CUDA sincronizado; incluye transferencia de cada lote.')
print('Error máximo de parámetros tras cuatro pasos:', error)
print('Cociente NumPy CPU / PyTorch', device, ':', numpy_time / torch_time)
print('Un solo ensayo compartido no establece velocidad universal ni mide Pyodide.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

[ ]Count parameters and operationsBrowser
conv1=6*(25+1)
conv2=16*(6*25+1)
dense=[(400+1)*120,(120+1)*84,(84+1)*10]
mac=[28*28*6*25,10*10*16*6*25,400*120,120*84,84*10]
print('Parámetros por capa:',[conv1,conv2,*dense],'total:',conv1+conv2+sum(dense))
print('MAC por capa:',mac,'total:',sum(mac),'FLOP con dos por MAC:',2*sum(mac))
NumericShared parameters
For the modernized architecture above, with bias in every convolution and dense layer, how many trainable parameters are there in total?
NumericTen equal logits
If the ten logits of each example are exactly equal, what is mean cross-entropy in nats?
CodeOverfit check
Implement overfit_one_batch(model, batch, steps, threshold). model.loss(batch) returns current scalar loss and model.train_step(batch) performs a real update. Return True if, before or after at most steps updates, loss is finite and at most threshold; return False if a loss is nonfinite or the budget is exhausted. Reject steps that is not a nonnegative Python integer, including bool, and nonfinite or negative threshold with ValueError. This test detects obvious failures, not proof that the full gradient is correct.
def overfit_one_batch(model, batch, steps, threshold):
  pass
Shift+Enter to run
QuizWhat can you conclude?
A fixed batch keeps exactly the same loss after many updates. What is the best-supported conclusion?
CodeShift without wrapping
Implement shift_image(image, dy, dx): it takes a 2D NumPy array and integer shifts. Return a new array of the same shape and dtype, filled with zeros: positive dy moves down and positive dx right. If the shift moves the whole image out, return zeros. Use this operation to compare MLP and CNN on the same images and shifts; do not wrap pixels across the boundary.
def shift_image(image, dy, dx):
  pass
Shift+Enter to run
CodeA dense comparator
Implement mlp_forward(x, weights, biases) for the 784→65→76→65→10 comparator. x has shape (batch,784); each weight matrix has shape (input,output) and each bias shape (output,). Apply ReLU after the first three layers and return fourth-layer logits. Then train the MLP from the cells under the same protocol and compare both networks using paired shifts, without interpreting one result as a universal law.
def mlp_forward(x, weights, biases):
  pass
Shift+Enter to run
Key idea

A CNN is not validated merely because its loss falls: check backward, shapes and preprocessing, separate validation from test and compare alternatives with an explicit protocol.

References