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
- 15Scalar autograd engineModule and parameters abstractionCost of backpropagation in dense networksOutput layer and loss pairing
- 02VJP of contractions and broadcastingBroadcastingLinear layer gradients
- 07Softmax cross-entropy loss
- 09Log-sum-exp trick and stable softmaxPython interpreter overhead
- 00Broadcasting rulesVectorization
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: . Treating , , and 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 , its adjoint has the shape of : . A backward pass receives and computes the transpose Jacobian times that adjoint without constructing the full Jacobian. If , its contract is . Contributions from different uses accumulate, as in the scalar engine. Review the VJP of a contraction and the matrix rules before continuing.
For , , and , the backward pass for is and . 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 , an element affects every row and receives . An element affects every column and receives . These expressions are the entries of and , respectively. Matching shapes is a necessary check, but not a proof of the rule.
For an elementwise operation , the VJP is . For the product of two arrays, first form and in the broadcast shape, then reduce them. exp can save its output; log needs enough information for . 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 , with of shape , the same participates in all rows. By the chain rule, , 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.
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 and the bias , sum axis zero. If an input has shape and output , 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.
What each rule must remember
Saved-tensor design follows the formulas, not a universal rule to save everything. For , ; for sigmoid , . 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 , where is the normal cumulative distribution function. Its derivative is not generally determined by : 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 , . Also, and : by symmetry, . The derivative increases strictly and changes sign once, so there is an interior minimum. Since , the value is also attained on the increasing branch, with positive derivative; at the derivative is negative. The two exact inputs have equal outputs and different derivatives.
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.
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 outChecking shapes and values
Gradcheck compares a projection of the output with central differences. If is a seed with the shape of , the scalar function has gradient . 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.
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.
# 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 and integer labels , define and . The mean loss is . The shift prevents exponential overflow; retaining the subtraction as avoids cancellation of large numbers. The derivative is , with and one-hot . The formula assumes normalized labels and mean reduction; sum reduction omits .
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, , while differentiating subtracts one only for the target class. Dividing by 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.
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, and . 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, 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.
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*vfrom 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.
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.
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.
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
Step 1 of 3. If y = tanh(x), how is the local derivative written?
import numpy as np
def unbroadcast(grad, shape):
passimport numpy as np
def max_backward(x, grad, axis):
passCheck 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.
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)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.