Module contents
Lesson 9 of 22Core 110 min

Micro autograd II: a tensor micro framework

The scalar engine becomes a NumPy tensor micro-framework with VJP rules, broadcasting in backward passes, and saved-tensor choices that determine activation memory. Build layers, an optimizer, and fused cross-entropy, train an MLP on digits, and explain the tensor approach's speedup.

After this lesson you can

  • Implement Tensor with VJP rules for matrix multiplication, elementwise operations, reductions, reshape, transpose, and indexing.
  • Implement gradient reduction for broadcasting and fused cross-entropy with a stable backward pass.
  • Choose what each operation saves for backward and measure its effect on activation memory.
  • Train an MLP on the tensor engine and explain its speedup over the scalar engine in terms of useful work per graph node.
  • Design gradient tests with random shapes and broadcasting.

Before you start

One operation, many numbers

The scalar engine from the previous lesson represents each product and sum with an object. A dense layer for a batch has a regular structure: Z=XW+bZ=XW+b. Treating XX, WW, and bb as arrays lets one matrix operation describe thousands of products and sums. The graph now stores array operations, while NumPy performs the work inside them. It is the same chain rule in a tensor autograd engine.

For each node xx, its adjoint has the shape of xx: xˉ=∂L/∂x\bar x=\partial L/\partial x. A backward pass receives yˉ\bar y and computes the transpose Jacobian times that adjoint without constructing the full Jacobian. If y=f(x)y=f(x), its contract is xˉ+=Jf(x)Tyˉ\bar x\mathrel{+}=J_f(x)^\mathsf{T}\bar y. Contributions from different uses accumulate, as in the scalar engine. Review the VJP of a contraction and the matrix rules before continuing.

For X∈RB×dX\in\mathbb R^{B\times d}, W∈Rd×kW\in\mathbb R^{d\times k}, and G=Zˉ∈RB×kG=\bar Z\in\mathbb R^{B\times k}, the backward pass for Z=XWZ=XW is Xˉ+=GWT\bar X\mathrel{+}=GW^\mathsf{T} and Wˉ+=XTG\bar W\mathrel{+}=X^\mathsf{T}G. Each shape matches its argument. Here we implement @ for two-dimensional matrices: NumPy’s general version also accepts vectors and broadcast batch dimensions, which need additional rules.

The index calculation explains both rules. Since Zij=∑rXirWrjZ_{ij}=\sum_r X_{ir}W_{rj}, an element WrjW_{rj} affects every row and receives ∑iXirGij\sum_i X_{ir}G_{ij}. An element XirX_{ir} affects every column and receives ∑jGijWrj\sum_j G_{ij}W_{rj}. These expressions are the entries of XTGX^\mathsf{T}G and GWTGW^\mathsf{T}, respectively. Matching shapes is a necessary check, but not a proof of the rule.

For an elementwise operation y=f(x)y=f(x), the VJP is xˉ+=yˉ⊙f′(x)\bar x\mathrel{+}=\bar y\odot f'(x). For the product of two arrays, first form yˉ⊙b\bar y\odot b and yˉ⊙a\bar y\odot a in the broadcast shape, then reduce them. exp can save its output; log needs enough information for 1/x1/x. reshape returns the adjoint to its previous shape and transpose applies the inverse permutation. Concatenation splits the adjoint into corresponding segments and accumulates if the same tensor was concatenated more than once.

Broadcasting has an inverse too

In Z=X+bZ=X+b, with bb of shape (k,)(k,), the same bjb_j participates in all BB rows. By the chain rule, bˉj=∑i=1BZˉij\bar b_j=\sum_{i=1}^{B}\bar Z_{ij}, not an arbitrary copy of one row. For a broadcast product, first multiply by the other operand and then reduce. Broadcasting need not create physical copies; drawing them helps count uses and their contributions.

InteractiveUndoing broadcasting
The boxes are the original inputs. Their shapes determine which axes can broadcast.
A (4, 3)
B (3,)
The output adjoint is Gij=1+i+jG_{ij}=1+i+j, with zero-based indices. Operation: A+BA + B. For addition the local contribution is GG; for multiplication it is G⊙BG\odot B for AA and G⊙AG\odot A for BB.
  • A and its contributions
  • B and its contributions
Operation and shapes
Selected operand
Operands
Output(4, 3)
Selected inputB[0]
Uses of this input4
Step through the expansion, select an element, and add the contributions returning to its original shape. The local derivative of a product depends on the other operand.

unbroadcast first sums dimensions added on the left, then keeps expanded dimensions as size-one dimensions. A scalar has shape (): all axes are reduced. The function assumes the original shape could broadcast to the adjoint’s shape; it does not make incompatible shapes valid. For example, if the output has shape (4,3)(4,3) and the bias (3,)(3,), sum axis zero. If an input has shape (4,1)(4,1) and output (4,5)(4,5), sum the last axis while retaining it.

In the reverse direction, the backward pass for sum broadcasts the adjoint to each position contributing to the sum; mean does the same and divides by the number of reduced elements. When axes are removed, first reinsert them in their original positions. If loss is already averaged over the batch, its factor is included in the adjoint: do not divide again when undoing a broadcast bias. An exercise below checks this case.

InteractiveCheck a VJP
Addition and bias
Z = A + B
A (m, n), B (1, n), G (m, n)
G is the adjoint of Z. Find the adjoint of B in its original shape.
Language: a, b, g, elementwise +, -, *, /, matrix @, and parentheses. T transposes; sum0 and sum1 retain the axis; ones creates ones of the same shape and rows returns the row count. reshapeA returns elements in A’s original shape; scatter accumulates the three columns at indices [0, 0, 1] of A; tanhprime computes 1 − tanh² elementwise. The derivative of the scalar function sum(G ⊙ Z) is computed by varying each input with central differences at step 10⁻⁵. The test uses three shapes and values generated with a fixed seed.
Accepted if each difference is at most 10−6(1+∣reference∣)10^{-6}(1+|\mathrm{reference}|). Agreement on a finite suite does not prove the formula for all shapes.
Requested gradient
OperandB
Choose an operation, write a rule, and compare it with finite differences on the suggested cases. A numerical test suite finds errors but does not prove every possible case.

What each rule must remember

Saved-tensor design follows the formulas, not a universal rule to save everything. For y=tanh⁡xy=\tanh x, dy/dx=1−y2dy/dx=1-y^2; for sigmoid y=σ(x)y=\sigma(x), dy/dx=y(1−y)dy/dx=y(1-y). Saving the output value suffices. ReLU must distinguish positive from nonpositive input: a Boolean mask suffices if the local derivative at zero is chosen as zero. In this code a NumPy bool mask takes one byte per element; one bit per element requires explicit packing and accounting for rounding to bytes.

Matrix multiplication needs information from both inputs to calculate both gradients. This implementation saves copies to protect its backward pass if an array is mutated after the forward pass. Other engines may share storage, forbid mutation, or detect it using version counters. An unprotected mutable reference can produce a gradient for data different from those that produced the output.

Exact GELU is f(x)=xΦ(x)f(x)=x\Phi(x), where Φ\Phi is the normal cumulative distribution function. Its derivative Φ(x)+xϕ(x)\Phi(x)+x\phi(x) is not generally determined by f(x)f(x): the function decreases and then increases in the negative region, so two inputs can share an output but have different slopes. Saving the input is one solution; another sufficient representation for the derivative could also be saved. See the original GELU definition. The interactive’s figures measure logical memory of selected arrays, not peak process memory, and avoid counting a shared array twice. That model assumes immutable shared storage; the lab engine makes defensive copies and may therefore retain more bytes.

We can prove the claim without relying on decimals. At [−1,0][-1,0], f′′(x)=ϕ(x)(2−x2)>0f''(x)=\phi(x)(2-x^2)>0. Also, f′(0)=1/2f'(0)=1/2 and f′(−1)=Φ(−1)−ϕ(1)<0f'(-1)=\Phi(-1)-\phi(1)<0: by symmetry, Φ(−1)=∫1∞ϕ(t) dt<∫1∞tϕ(t) dt=ϕ(1)\Phi(-1)=\int_1^\infty\phi(t)\,dt<\int_1^\infty t\phi(t)\,dt=\phi(1). The derivative increases strictly and changes sign once, so there is an interior minimum. Since f(−1)<f(0)=0f(-1)<f(0)=0, the value f(−1)f(-1) is also attained on the increasing branch, with positive derivative; at −1-1 the derivative is negative. The two exact inputs have equal outputs and different derivatives.

InteractiveWhat each operation saves

Network 784 → 256 → 256 → 10. Each Linear saves its float32 input to calculate weight gradients. An output saved by the activation shares the same array with the next Linear input and is counted once.

Hidden layer 1
Activation
Save for backward

Sufficient for ReLU. The sign mask determines the derivative under the chosen zero convention. Additional memory: 256 B.

Hidden layer 2
Activation
Save for backward

Sufficient for ReLU. The sign mask determines the derivative under the chosen zero convention. Additional memory: 256 B.

Saved memory breakdown
Linear inputs: 5.06 KiB Additional information: 512 B

The count includes float32 arrays and, for masks, one byte per element or packed bits rounded up to a byte per layer. Packing is an explicit representation, not a guarantee of NumPy or a framework. The count assumes weight matrices are available and saved arrays are not modified in place; it excludes parameters, gradients, temporaries, and actual peak memory. Without recomputation, an insufficient choice cannot support the general backward pass.

2
256
1
Saved activations5.56 KiB
Bytes per example5696.00
Insufficient policies0
Build a network and choose what to retain for each activation. Compare bytes and policies that allow the backward pass to be computed.

A small engine with explicit limits

The code implements addition, multiplication, 2D matmul, activations, reductions, reshaping, transposition, indexing, and concatenation. For addition, unbroadcast returns each contribution to its shape; for a reduction, the seed is broadcast again. For indexing, np.add.at accumulates even when an index appears repeatedly; a[idx] += g with repeated indices can lose contributions because of NumPy’s temporary buffering. The add.at documentation specifies this accumulation.

max divides the adjoint equally among tied maxima: this is a subgradient choice, not an ordinary derivative at a tie. Thus gradcheck is performed away from ties and the tie rule is tested separately. ReLU also has a convention at zero. Topological traversal is iterative and clears intermediate values on each pass but accumulates at leaves; the optimizer must zero its parameters when starting an independent step. There is no GPU, higher-order dynamic graph, or complete memory-management system.

[ ]Tensor and its vector-Jacobian productsBrowser
import numpy as np
from copy import deepcopy

def unbroadcast(grad, shape):
    grad = np.asarray(grad)
    while grad.ndim > len(shape):
        grad = grad.sum(axis=0)
    for axis, size in enumerate(shape):
        if size == 1 and grad.shape[axis] != 1:
            grad = grad.sum(axis=axis, keepdims=True)
    if grad.shape != tuple(shape):
        raise ValueError('formas incompatibles')
    return grad

class Tensor:
    def __init__(self, data, parents=(), backward=None):
        self.data = np.array(data, dtype=np.float64, copy=True)
        self.grad = np.zeros_like(self.data)
        self.parents = tuple(parents)
        self._backward = backward or (lambda: None)

    @staticmethod
    def wrap(x): return x if isinstance(x, Tensor) else Tensor(x)

    def __add__(self, other):
        other = Tensor.wrap(other)
        a_shape, b_shape = self.data.shape, other.data.shape
        out = Tensor(self.data + other.data, (self, other))
        def backward():
            self.grad += unbroadcast(out.grad, a_shape)
            other.grad += unbroadcast(out.grad, b_shape)
        out._backward = backward
        return out
    __radd__ = __add__

    def __mul__(self, other):
        other = Tensor.wrap(other)
        a, b = self.data.copy(), other.data.copy()
        out = Tensor(a*b, (self, other))
        def backward():
            self.grad += unbroadcast(out.grad*b, a.shape)
            other.grad += unbroadcast(out.grad*a, b.shape)
        out._backward = backward
        return out
    __rmul__ = __mul__
    def __neg__(self): return self * -1
    def __sub__(self, other): return self + (-Tensor.wrap(other))
    def __rsub__(self, other): return Tensor.wrap(other) - self

    def __matmul__(self, other):
        other = Tensor.wrap(other)
        a, b = self.data.copy(), other.data.copy()
        if a.ndim != 2 or b.ndim != 2:
            raise ValueError('matmul admite matrices 2D')
        out = Tensor(a @ b, (self, other))
        def backward():
            self.grad += out.grad @ b.T
            other.grad += a.T @ out.grad
        out._backward = backward
        return out

    def tanh(self):
        y = np.tanh(self.data)
        out = Tensor(y, (self,))
        out._backward = lambda: self._accumulate(out.grad*(1-y*y))
        return out
    def sigmoid(self):
        x = self.data
        y = np.exp(-np.logaddexp(0, -x))
        out = Tensor(y, (self,))
        out._backward = lambda: self._accumulate(out.grad*y*(1-y))
        return out
    def relu(self):
        mask = self.data > 0
        out = Tensor(np.maximum(self.data, 0), (self,))
        out._backward = lambda: self._accumulate(out.grad*mask)
        return out
    def exp(self):
        y = np.exp(self.data)
        out = Tensor(y, (self,))
        out._backward = lambda: self._accumulate(out.grad*y)
        return out
    def log(self):
        x = self.data.copy()
        if np.any(x <= 0): raise ValueError('log exige entrada positiva')
        out = Tensor(np.log(x), (self,))
        out._backward = lambda: self._accumulate(out.grad/x)
        return out
    def _accumulate(self, value): self.grad += value

    def sum(self, axis=None, keepdims=False):
        shape = self.data.shape
        axes = tuple(range(len(shape))) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
        axes = tuple(a % len(shape) for a in axes) if shape else ()
        out = Tensor(self.data.sum(axis=axis, keepdims=keepdims), (self,))
        def backward():
            g = out.grad
            if not keepdims:
                for a in sorted(axes): g = np.expand_dims(g, a)
            self.grad += np.broadcast_to(g, shape)
        out._backward = backward
        return out
    def mean(self, axis=None, keepdims=False):
        axes = tuple(range(self.data.ndim)) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
        count = int(np.prod([self.data.shape[a] for a in axes]))
        return self.sum(axis, keepdims) * (1.0/count)
    def max(self, axis=None, keepdims=False):
        shape = self.data.shape
        axes = tuple(range(len(shape))) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
        axes = tuple(a % len(shape) for a in axes) if shape else ()
        maxima = self.data.max(axis=axis, keepdims=True)
        mask = self.data == maxima
        counts = mask.sum(axis=axis, keepdims=True)
        out = Tensor(self.data.max(axis=axis, keepdims=keepdims), (self,))
        def backward():
            g = out.grad
            if not keepdims:
                for a in sorted(axes): g = np.expand_dims(g, a)
            self.grad += mask * (g/counts)
        out._backward = backward
        return out
    def reshape(self, *shape):
        original = self.data.shape
        out = Tensor(self.data.reshape(*shape), (self,))
        out._backward = lambda: self._accumulate(out.grad.reshape(original))
        return out
    def transpose(self, *axes):
        perm = (tuple(axes[0]) if len(axes) == 1 and isinstance(axes[0], (tuple, list))
                else tuple(axes) if axes else tuple(reversed(range(self.data.ndim))))
        transposed = self.data.transpose(perm)  # NumPy valida la permutación.
        normalized = tuple(a % self.data.ndim for a in perm) if self.data.ndim else ()
        inverse = np.argsort(normalized)
        out = Tensor(transposed, (self,))
        out._backward = lambda: self._accumulate(out.grad.transpose(inverse))
        return out
    def __getitem__(self, index):
        # También pueden mutarse listas o estructuras anidadas de índices.
        index = deepcopy(index)
        out = Tensor(self.data[index], (self,))
        def backward(): np.add.at(self.grad, index, out.grad)
        out._backward = backward
        return out
    @staticmethod
    def concat(tensors, axis=0):
        tensors = tuple(tensors)
        cuts = np.cumsum([t.data.shape[axis] for t in tensors])[:-1]
        out = Tensor(np.concatenate([t.data for t in tensors], axis=axis), tensors)
        def backward():
            for tensor, g in zip(tensors, np.split(out.grad, cuts, axis=axis)):
                tensor.grad += g
        out._backward = backward
        return out

    def backward(self, seed=None):
        if seed is None:
            if self.data.size != 1: raise ValueError('salida no escalar: proporciona semilla')
            seed = np.ones_like(self.data)
        seed = np.asarray(seed, dtype=float)
        if seed.shape != self.data.shape: raise ValueError('forma de semilla incorrecta')
        topo, seen, stack = [], set(), [(self, False)]
        while stack:
            node, done = stack.pop()
            if done: topo.append(node)
            elif node not in seen:
                seen.add(node)
                stack.append((node, True))
                stack.extend((p, False) for p in reversed(node.parents))
        for node in topo:
            if node.parents: node.grad.fill(0)
        self.grad += seed
        for node in reversed(topo): node._backward()
        return len(topo)

def cross_entropy(logits, labels):
    z = logits.data.copy()
    labels = np.asarray(labels)
    if (z.ndim != 2 or z.shape[0] == 0 or z.shape[1] == 0 or
            labels.ndim != 1 or labels.shape[0] != z.shape[0] or
            not np.issubdtype(labels.dtype, np.integer) or
            np.any(labels < 0) or np.any(labels >= z.shape[1])):
        raise ValueError('formas o etiquetas incorrectas')
    shifted = z - np.max(z, axis=1, keepdims=True)
    exp = np.exp(shifted)
    probabilities = exp/exp.sum(axis=1, keepdims=True)
    loss = np.mean(np.log(exp.sum(axis=1))-shifted[np.arange(len(labels)), labels])
    delta = probabilities.copy()
    delta[np.arange(len(labels)), labels] -= 1
    delta /= len(labels)
    out = Tensor(loss, (logits,))
    out._backward = lambda: logits._accumulate(out.grad*delta)
    return out

Checking shapes and values

Gradcheck compares a projection of the output with central differences. If uu is a seed with the shape of f(x)f(x), the scalar function uTf(x)u^\mathsf{T}f(x) has gradient Jf(x)TuJ_f(x)^\mathsf{T}u. This checks the VJP without constructing a Jacobian. We repeat shapes and points and use float64; absolute errors depend on step size and scale. Ties and kinks need specific tests.

[ ]Gradcheck: broadcasting, matrix multiplication, and shapesBrowser
import numpy as np

gen = np.random.default_rng(123)

def gradcheck(name, arrays, operation, eps=1e-6):
    inputs = [Tensor(a) for a in arrays]
    result = operation(*inputs)
    seed = gen.normal(size=result.data.shape)
    result.backward(seed)
    errors = []
    for k, array in enumerate(arrays):
        for index in np.ndindex(array.shape):
            plus = [a.copy() for a in arrays]
            minus = [a.copy() for a in arrays]
            plus[k][index] += eps
            minus[k][index] -= eps
            high = operation(*[Tensor(a) for a in plus]).data
            low = operation(*[Tensor(a) for a in minus]).data
            numerical = np.sum(seed * (high-low)) / (2*eps)
            errors.append(abs(numerical-inputs[k].grad[index]))
    worst = max(errors, default=0.)
    assert worst < 2e-6, (name, worst)
    print(name, 'error absoluto máximo', worst)

for batch, width in [(2, 3), (4, 5), (3, 2)]:
    a = gen.normal(size=(batch, 1))
    b = gen.normal(size=(1, width))
    gradcheck(f'broadcast {batch}x{width}', [a, b], lambda x, y: x*y+x+y)
    left = gen.normal(size=(batch, 3))
    right = gen.normal(size=(3, width))
    gradcheck(f'matmul {batch}x3x{width}', [left, right], lambda x, y: x@y)

data = gen.normal(size=(2, 3, 4))
gradcheck('transpose con eje negativo y reshape', [data], lambda x: x.transpose((-1, 0, 1)).reshape(4, 6))
gradcheck('sum y mean', [data], lambda x: x.sum(axis=(0, -1)).mean())
gradcheck('tanh', [data], lambda x: x.tanh())
gradcheck('sigmoide', [data], lambda x: x.sigmoid())
gradcheck('exp', [data], lambda x: x.exp())
gradcheck('log', [np.exp(data)], lambda x: x.log())
gradcheck('relu lejos del codo', [np.array([[-2., -0.5, 1., 3.]])], lambda x: x.relu())
gradcheck('max sin empates', [np.array([[1., 2., 3.], [5., 4., 1.]])], lambda x: x.max(axis=1))
gradcheck('indexado repetido', [data], lambda x: x[[0, 0, 1], [2, 2, 1], [3, 3, 0]])
gradcheck('concatenar nodo compartido', [gen.normal(size=(2, 2)), gen.normal(size=(2, 1))], lambda x, y: Tensor.concat([x, y, x], axis=1))
gradcheck('entropía cruzada', [gen.normal(size=(4, 3))], lambda z: cross_entropy(z, np.array([0, 2, 1, 2])))

The next cell tests a case ordinary finite differences do not cover: a repeated index must sum contributions. It also checks the chosen policy for a tied maximum and that mutating an input after the forward pass does not change the saved VJP. The copy protects values needed by this implementation’s backward pass; it does not guarantee every in-place operation is safe in every framework.

[ ]Repeated indices, ties, and mutationBrowser
# Las diferencias finitas en un empate no verifican una derivada ordinaria.
x = Tensor([[3., 3., 1.], [1., 2., 2.]])
x.max(axis=1).sum().backward()
print('max empatado, subgradiente elegido:', x.grad)
assert np.array_equal(x.grad, [[.5, .5, 0.], [0., .5, .5]])

# La lista de índices se copia en el forward y los usos repetidos se acumulan.
x = Tensor([2., 3., 4.])
indices = [0, 0, 2]
result = x[indices].sum()
indices[:] = [1, 1, 1]
result.backward()
print('índices originales repetidos, gradiente:', x.grad)
assert np.array_equal(x.grad, [2., 0., 1.])

# El producto guarda copias de los valores necesarios para el backward.
x = Tensor([2., 3.])
y = Tensor([4., 5.])
result = (x*y).sum()
x.data[:] = 99.
y.data[:] = 77.
result.backward()
print('producto tras mutar entradas, gradientes:', x.grad, y.grad)
assert np.array_equal(x.grad, [4., 5.]) and np.array_equal(y.grad, [2., 3.])

Fused cross-entropy

For logits Z∈RB×CZ\in\mathbb R^{B\times C} and integer labels tit_i, define mi=max⁡jZijm_i=\max_j Z_{ij} and sij=Zij−mis_{ij}=Z_{ij}-m_i. The mean loss is B−1∑i[log⁡∑jexp⁡(sij)−si,ti]B^{-1}\sum_i[\log\sum_j\exp(s_{ij})-s_{i,t_i}]. The shift prevents exponential overflow; retaining the subtraction as si,tis_{i,t_i} avoids cancellation of large numbers. The derivative is (P−Y)/B(P-Y)/B, with P=softmax⁡(Z)P=\operatorname{softmax}(Z) and one-hot YY. The formula assumes normalized labels and mean reduction; sum reduction omits 1/B1/B.

The function cross_entropy computes both operations as one node and saves the distribution needed for its backward pass. Fusion here is algebraic and at graph level: it does not imply NumPy runs it as a single specialized kernel. Compare log-sum-exp stabilization and the softmax and cross-entropy pairing.

To derive it, ∂log⁡∑jeZj/∂Zk=eZk/∑jeZj=Pk\partial\log\sum_j e^{Z_j}/\partial Z_k=e^{Z_k}/\sum_j e^{Z_j}=P_k, while differentiating −Zt-Z_t subtracts one only for the target class. Dividing by BB corresponds to the chosen mean. The maximum evaluates the expression stably; the full expression is invariant to shifting all logits in a row, and the fused VJP comes from the original function. We need not separately differentiate an max branch to obtain the correct gradient.

[ ]Extreme logits and the gradientBrowser
z = Tensor([[1000., 999., -1000.], [1e16, 1e16, 1e16]])
loss = cross_entropy(z, np.array([0, 2]))
loss.backward()
print('pérdida finita', float(loss.data), 'gradiente', z.grad)
print('suma de gradientes por fila', z.grad.sum(axis=1))

From Tensor to a trainable network

Linear owns weights and bias; MLP composes two layers and ReLU; SGD maintains a momentum accumulator per parameter. Under the chosen convention, vt=0.9vt−1+gtv_t=0.9v_{t-1}+g_t and θt=θt−1−ηvt\theta_t=\theta_{t-1}-\eta v_t. This is a specific convention: other libraries may place the learning factor inside the velocity or change initialization. Inputs and constants are not optimizer parameters.

At each update, accumulated parameter gradients are cleared, loss is computed on a new batch, and backward runs before any weight changes. The optimizer need not know the rules for matmul or ReLU: it only reads the accumulated gradients. The 23 batches result from dividing a full training permutation into almost equal parts; each epoch visits every example in that partition once. The test set is evaluated afterward without updating weights.

We use load_digits, 8×88\times8 images with intensities divided by 16, and stratify the class split before training. This small dataset checks the engine; it is not a general recognition benchmark. The test split stays outside updates. Since this configuration was chosen after running the experiment, its test figure is a reproducible check for the lesson, not an independent evaluation after hyperparameter search.

[ ]Linear, MLP, and SGD with momentumBrowser
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
[ ]Data, training, and evaluationBrowser
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from time import perf_counter

X, y = load_digits(return_X_y=True)
X = X/16.0
train, test = train_test_split(np.arange(len(y)), test_size=0.2,
                               random_state=42, stratify=y)
network = MLP(np.random.default_rng(11))
optimizer = SGD(network.parameters(), learning_rate=0.05, momentum=0.9)
batch_rng = np.random.default_rng(21)
start = perf_counter()
for epoch in range(20):
    for ids in np.array_split(batch_rng.permutation(train), 23):
        optimizer.zero_grad()
        loss = cross_entropy(network(Tensor(X[ids])), y[ids])
        loss.backward()
        optimizer.step()
elapsed = perf_counter()-start
prediction = np.argmax(network(Tensor(X[test])).data, axis=1)
print('entrenamiento y prueba:', len(train), len(test))
print('épocas, pérdida del último lote:', epoch+1, float(loss.data))
print('precisión de prueba:', np.mean(prediction == y[test]))
print('segundos por época en esta ejecución:', elapsed/(epoch+1))

Per-node cost and computational cost

Each tensor layer groups operations the scalar engine would represent separately. Reducing overhead does not change the mathematics or guarantee a fixed speed ratio. In Pyodide, NumPy runs in the browser without BLAS and on one thread; in other installations, matrix libraries and hardware change the result. Measured times correspond to this run and should be measured again in the environment where they are used.

InteractiveScalar versus tensor

Medians of five passes from a small benchmark-cell run in Pyodide under Node. They include forward and backward with the same four-example batch, weights, and loss, but no update. Times depend on environment and load; they are not universal.

Vertical axis: median seconds per pass, logarithmic scale.

  • Scalar graph
  • Tensor graph
  • NumPy, manual backward

The measured network is 2-h-h-2. For h = 8, the scalar tape has 1045 nodes and the tensor tape 16; NumPy computes backward manually. The other view models a 2-h-h-1 network with hypothetical costs, so it does not fit these measurements.

View
Parameters114
Scalar median2.94 ms
Tensor median402 µs
NumPy median157 µs
Compare a run measured in Pyodide under Node with a hypothetical cost model. Change the width; in the model view you can also vary batch size and per-node overhead.

To measure the trend, rebuild Value from the previous lesson and compare three 2-h-h-2 networks with the same weights, data, and loss. In each case, parity of all gradients with manual NumPy is checked first. Time includes forward, backward, and gradient materialization without parameter updates; medians of five passes do not guarantee a speedup on another machine.

[ ]Reproducible comparison of three enginesBrowser
import math
import numpy as np

class Value:
    def __init__(self, data, children=(), op=''):
        self.data = float(data)
        self.grad = 0.0
        self._prev = tuple(children)
        self.op = op
        self._backward = lambda: None

    @staticmethod
    def wrap(x):
        return x if isinstance(x, Value) else Value(x)

    def __add__(self, other):
        other = Value.wrap(other)
        out = Value(self.data + other.data, (self, other), '+')
        def backward():
            self.grad += out.grad
            other.grad += out.grad
        out._backward = backward
        return out

    __radd__ = __add__

    def __mul__(self, other):
        other = Value.wrap(other)
        out = Value(self.data * other.data, (self, other), '*')
        def backward():
            self.grad += other.data * out.grad
            other.grad += self.data * out.grad
        out._backward = backward
        return out

    __rmul__ = __mul__

    def __neg__(self):
        return self * -1

    def __sub__(self, other):
        return self + (-Value.wrap(other))

    def __rsub__(self, other):
        return Value.wrap(other) - self

    def __truediv__(self, other):
        return self * Value.wrap(other)**-1

    def __rtruediv__(self, other):
        return Value.wrap(other) / self

    def __pow__(self, power):
        if not isinstance(power, (int, float)):
            raise TypeError('el exponente debe ser constante')
        out = Value(self.data**power, (self,), f'**{power}')
        def backward():
            local = 0.0 if power == 0 else power*self.data**(power-1)
            self.grad += local*out.grad
        out._backward = backward
        return out

    def tanh(self):
        t = math.tanh(self.data)
        out = Value(t, (self,), 'tanh')
        def backward():
            self.grad += (1-t*t)*out.grad
        out._backward = backward
        return out

    def relu(self):
        out = Value(max(0., self.data), (self,), 'relu')
        def backward():
            self.grad += (self.data > 0)*out.grad
        out._backward = backward
        return out

    def exp(self):
        t = math.exp(self.data)
        out = Value(t, (self,), 'exp')
        def backward():
            self.grad += t*out.grad
        out._backward = backward
        return out

    def log(self):
        if self.data <= 0:
            raise ValueError('log requiere una entrada positiva')
        out = Value(math.log(self.data), (self,), 'log')
        def backward():
            self.grad += out.grad/self.data
        out._backward = backward
        return out

    def backward(self):
        topo, seen = [], set()
        stack = [(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((parent, False)
                             for parent in reversed(node._prev))
        for node in topo:
            if node._prev:
                node.grad = 0.0
        self.grad += 1.0
        for node in reversed(topo):
            node._backward()
        return len(topo)

import gc
import statistics
import time
import numpy as np

def build_case(width, batch=4):
    rng = np.random.default_rng(710 + width)
    dims = [2, width, width, 2]
    X = rng.normal(0, 0.5, (batch, 2))
    labels = rng.integers(0, 2, size=batch)
    W = [rng.normal(0, 0.25, (a, b)) for a, b in zip(dims[:-1], dims[1:])]
    bias = [rng.normal(0, 0.1, b) for b in dims[1:]]
    sw = [[[Value(W[k][i, j]) for j in range(W[k].shape[1])]
           for i in range(W[k].shape[0])] for k in range(3)]
    sb = [[Value(v) for v in b] for b in bias]
    tw = [Tensor(w) for w in W]
    tb = [Tensor(b) for b in bias]

    def scalar():
        for layer in sw:
            for row in layer:
                for p in row: p.grad = 0.0
        for layer in sb:
            for p in layer: p.grad = 0.0
        losses = []
        for x, target in zip(X, labels):
            h = [Value(v) for v in x]
            for k in range(3):
                z = [sum((h[i]*sw[k][i][j] for i in range(len(h))), sb[k][j])
                     for j in range(len(sb[k]))]
                h = [zj.tanh() for zj in z] if k < 2 else z
            maximum = max(v.data for v in h)
            losses.append(sum((v-maximum).exp() for v in h).log() - (h[target]-maximum))
        objective = sum(losses) * (1.0/batch)
        count = objective.backward()
        gradients = np.concatenate([np.array([[p.grad for p in row] for row in sw[k]]).ravel()
                                    if part == 0 else np.array([p.grad for p in sb[k]])
                                    for k in range(3) for part in range(2)])
        return objective.data, gradients, count

    def tensor():
        for p in tw+tb: p.grad.fill(0)
        h = Tensor(X)
        for k in range(3):
            h = h @ tw[k] + tb[k]
            if k < 2: h = h.tanh()
        objective = cross_entropy(h, labels)
        count = objective.backward()
        gradients = np.concatenate([tw[k].grad.ravel() if part == 0 else tb[k].grad.ravel()
                                    for k in range(3) for part in range(2)])
        return float(objective.data), gradients, count

    def manual():
        h = [X]
        for k in range(3):
            z = h[-1] @ W[k] + bias[k]
            h.append(np.tanh(z) if k < 2 else z)
        shifted = h[-1] - h[-1].max(axis=1, keepdims=True)
        ex = np.exp(shifted)
        sums = ex.sum(axis=1, keepdims=True)
        value = np.mean(np.log(sums[:, 0]) - shifted[np.arange(batch), labels])
        delta = ex/sums
        delta[np.arange(batch), labels] -= 1
        delta /= batch
        grads = [None]*3
        for k in range(2, -1, -1):
            dw, db = h[k].T @ delta, delta.sum(axis=0)
            grads[k] = (dw, db)
            if k: delta = (delta @ W[k].T) * (1-h[k]**2)
        gradients = np.concatenate([grads[k][part].ravel() for k in range(3) for part in range(2)])
        return float(value), gradients, 0
    return scalar, tensor, manual, sum(w.size+b.size for w, b in zip(W, bias))

def benchmark(width):
    scalar, tensor, manual, params = build_case(width)
    ref_loss, ref_grad, _ = manual()
    results = []
    for name, fn in [('escalar', scalar), ('tensorial', tensor), ('numpy_manual', manual)]:
        loss, grad, nodes = fn()
        loss_error = abs(loss-ref_loss)
        grad_error = float(np.max(np.abs(grad-ref_grad)))
        assert loss_error < 1e-11 and grad_error < 1e-11, (name, loss_error, grad_error)
        del grad
        gc.collect()
        elapsed = []
        for _ in range(5):
            start = time.perf_counter()
            result = fn()
            elapsed.append(time.perf_counter()-start)
            del result
        results.append((name, nodes, loss_error, grad_error, statistics.median(elapsed), min(elapsed), max(elapsed)))
    print('h=', width, 'B=', 4, 'parámetros=', params)
    for row in results: print(row)
    del scalar, tensor, manual
    gc.collect()


for width in (4, 8, 16):
    benchmark(width)

The following count compares objects reachable from the loss for the same MLP and batch after backward. It uses the previously defined Value and Tensor classes and cross_entropy function. It adds the shallow size of each node and separately the data and gradients: for scalars it counts unique float objects; for tensors it adds the bytes of owned arrays data and grad. It excludes attribute dictionaries, parent references, closures, copies saved by closures, ndarray headers, temporaries, and peak memory. It is not total process consumption either. Sizes depend on the runtime.

[ ]Shallow graph memoryBrowser
import sys
import numpy as np

def reachable(root, parents_name):
    stack, seen, nodes = [root], set(), []
    while stack:
        node = stack.pop()
        if id(node) in seen:
            continue
        seen.add(id(node))
        nodes.append(node)
        stack.extend(getattr(node, parents_name))
    return nodes

def make_memory_graphs(width=8, batch=4):
    rng = np.random.default_rng(710 + width)
    dims = [2, width, width, 2]
    X = rng.normal(0, 0.5, (batch, 2))
    labels = rng.integers(0, 2, size=batch)
    arrays_w = [rng.normal(0, 0.25, (a, b))
                for a, b in zip(dims[:-1], dims[1:])]
    arrays_b = [rng.normal(0, 0.1, b) for b in dims[1:]]

    sw = [[[Value(arrays_w[k][i, j]) for j in range(dims[k+1])]
           for i in range(dims[k])] for k in range(3)]
    sb = [[Value(v) for v in b] for b in arrays_b]
    losses = []
    for row, target in zip(X, labels):
        h = [Value(v) for v in row]
        for k in range(3):
            z = [sum((h[i]*sw[k][i][j] for i in range(len(h))), sb[k][j])
                 for j in range(len(sb[k]))]
            h = [v.tanh() for v in z] if k < 2 else z
        maximum = max(v.data for v in h)
        losses.append(sum((v-maximum).exp() for v in h).log() -
                      (h[target]-maximum))
    scalar_loss = sum(losses) * (1.0/batch)

    tw = [Tensor(w) for w in arrays_w]
    tb = [Tensor(b) for b in arrays_b]
    h = Tensor(X)
    for k in range(3):
        h = h @ tw[k] + tb[k]
        if k < 2:
            h = h.tanh()
    tensor_loss = cross_entropy(h, labels)
    scalar_loss.backward()
    tensor_loss.backward()

    scalar_grad = np.concatenate([
        np.array([[p.grad for p in row] for row in sw[k]]).ravel()
        if part == 0 else np.array([p.grad for p in sb[k]])
        for k in range(3) for part in range(2)])
    tensor_grad = np.concatenate([
        tw[k].grad.ravel() if part == 0 else tb[k].grad.ravel()
        for k in range(3) for part in range(2)])
    assert abs(scalar_loss.data - float(tensor_loss.data)) < 1e-11
    assert np.max(np.abs(scalar_grad-tensor_grad)) < 1e-11
    return scalar_loss, tensor_loss

scalar_root, tensor_root = make_memory_graphs()
scalar_nodes = reachable(scalar_root, '_prev')
tensor_nodes = reachable(tensor_root, 'parents')

def superficial_nodes(nodes):
    return sum(sys.getsizeof(node) for node in nodes)

def scalar_values_bytes(nodes):
    # Varias referencias pueden compartir el mismo objeto float.
    values = {id(value): value for node in nodes
              for value in (node.data, node.grad)}
    return sum(sys.getsizeof(value) for value in values.values())

def tensor_buffers_bytes(nodes):
    arrays = {id(array): array for node in nodes
              for array in (node.data, node.grad)}
    assert all(array.flags.owndata for array in arrays.values())
    return sum(array.nbytes for array in arrays.values())

print('MLP 2-8-8-2, lote 4; pérdida y gradientes coinciden')
print('escalar: nodos, bytes superficiales, bytes float data/grad',
      len(scalar_nodes), superficial_nodes(scalar_nodes),
      scalar_values_bytes(scalar_nodes))
print('tensorial: nodos, bytes superficiales, bytes de buffers data/grad',
      len(tensor_nodes), superficial_nodes(tensor_nodes),
      tensor_buffers_bytes(tensor_nodes))

Exercises

ProofWhat must be saved for backward?
Prove: Compare the information that reconstructs the local derivative of tanh, sigmoid, and exact GELU.
0
Let y=f(x). A rule based only on output must return the same derivative for any two inputs sharing y.

Step 1 of 3. If y = tanh(x), how is the local derivative written?

CodeReduce the broadcast gradient
Implement unbroadcast(grad, shape): grad is an ndarray with the broadcast shape and shape is an operand's compatible original shape. Sum over axes added at the beginning and original axes of size 1, retaining those axes. Scalar shape is ().
import numpy as np

def unbroadcast(grad, shape):
  pass
Shift+Enter to run
CodeVJP of a max reduction
Implement max_backward(x, grad, axis): x is a nonempty ndarray, axis is a valid positive or negative integer, and grad has the shape of max(x, axis=axis), without the reduced axis. Return the adjoint with x's shape, dividing each grad component equally among tied maxima in its reduction.
import numpy as np

def max_backward(x, grad, axis):
  pass
Shift+Enter to run
QuizThe gradient of a shared bias
A layer forms Z=H+b, with H of shape (B,k) and b of shape (k,). If G is the adjoint of Z, which operation produces the adjoint of b?
NumericMemory saved per example
A 784-512-512-10 MLP saves the inputs to its three matrix products in float32 and a Boolean mask of one byte per element for each of its two ReLUs. For one example, how many bytes do those buffers total? Count each buffer once and exclude parameters, logits, and temporaries.

Check the examples in the solutions with the following calculation. The search for the second GELU input is numerical; the general conclusion depends on the existence of two inputs with the same output and different derivatives, not on the rounding shown.

[ ]Check GELU and the memory countBrowser
from scipy.special import ndtr
from scipy.optimize import brentq

def gelu(x): return x*ndtr(x)
def gelu_prime(x): return ndtr(x) + x*np.exp(-x*x/2)/np.sqrt(2*np.pi)
left = -1.0
right = brentq(lambda x: gelu(x)-gelu(left), -0.7, -0.4)
print('entradas:', left, right)
print('salidas:', gelu(left), gelu(right))
print('derivadas:', gelu_prime(left), gelu_prime(right))
entries = 4*(784+512+512)
masks = 512+512
extra = 4*(512+512)
print('entradas, máscaras, total, con preactivaciones:', entries, masks,
      entries+masks, entries+masks+extra)
Key idea

A tensor operation implements its VJP and accumulates a gradient shaped like each input. Broadcasting is undone by summing, repeated indexing accumulates, and saved information must suffice to compute backward without depending on subsequent mutations. Grouping work reduces graph nodes; observed cost also depends on implementation and environment.