121з. Backpropagation in matrix form: four equations, the Hadamard product and why the algorithm is fast
In 116б backpropagation was written out link by link for a network with one hidden layer and checked with finite differences, in 121ж the 35 → 16 → 10 network recognises a digit from the 35 dots of a dot-matrix display. Here is the same algorithm in general form: the forward pass in matrices for a network of any depth and a whole batch of examples, the layer error δ and the four equations from which the whole backward pass is built, and the counting: how many times cheaper it is than the numerical gradient and what a batch in matrices costs against a loop over examples. The second half is training right on the microcontroller: memory, instructions of one SGD step on a Cortex-M4 with an FPU and fine-tuning of the output layer for a particular instrument.
Basis: numpy 2.3.3 in the stm-ml:1 image, the scripts train121i.py (everything
that does not depend on the clock — a repeated run gives the same files)
and time121i.py (time on a computer with an Intel Core Ultra 7
270K Plus processor, OpenBLAS in one thread). The SGD step in C: gcc 12.2.0 (stm-sys:1)
for the cross-check, arm-none-eabi-gcc 12.2.1 and QEMU 7.2 (stm-arm:1, board
netduinoplus2 with an STM32F405 — the same Cortex-M4F core as the F407) — instruction
counts, armclang 6.24 — bytes. The STM32F407VG data come from the device
description in the Keil pack STM32F4xx_DFP 2.17.1.
Terms used in the documentation
Term Meaning weighted input z the weighted sum of a neuron before activation error of a layer δ layer error: the derivative of the loss with respect to the weighted sum Hadamard (Schur) product ⊙ Hadamard product: element-wise product chain rule chain rule: the derivative of a composite function is the product of the derivatives of its links central difference central difference: (f(w + ε) − f(w − ε))/2ε transpose Wᵀ transposed matrix: rows and columns swap places outer product outer product: a column times a row gives a matrix BLAS the library of matrix operations numpy stands on on-device training training on the instrument frozen layer frozen layer: its weights do not change during fine-tuning numerical stability numerical stability: no overflow and no loss of precision
121з.1 The forward pass in matrices: any depth, a whole batch
Layers are numbered from 1 to L. Layer l has a weight matrix Wˡ of size "inputs × neurons" and a row of biases bˡ. A batch of N examples is the matrix A⁰ = X, one example per row. Then each layer is two lines:
- the weighted sum Zˡ = Aˡ⁻¹Wˡ + bˡ — one matrix product for the whole batch, the bias is added to every row;
- the output Aˡ = σ(Zˡ) — the sigmoid applied to each number separately.
On the last layer softmax replaces the sigmoid, the loss is cross-entropy averaged over the batch (116б). For the 35 → 16 → 10 network from 121ж with a batch of 20 examples the sizes are: X — 20 × 35, W¹ — 35 × 16, Z¹ and A¹ — 20 × 16, W² — 16 × 10, Z² — 20 × 10. Depth changes nothing: a loop over layers, one product in each.
Z.append(A[-1] @ W + b) # Z = A·W + b — весь пакет одним умножением
The outputs of all layers Aˡ and the sums Zˡ must be kept: the backward pass takes them from there. That is the memory training spends on top of inference.
121з.2 The layer error δ and the four equations
The main quantity is the layer error δˡ = ∂C/∂Zˡ: how much the loss C changes if the weighted sum of each neuron is moved slightly. Everything that depends on the weights of the layer passes through the sum Z, so the weight gradients follow from δ at once, and the δ of the previous layer is one step back.
(1) Output layer. C depends on Z^L through the output A^L, by the chain rule δ^L = ∂C/∂A^L ⊙ σ′(Z^L). The sign ⊙ is the Hadamard product: two matrices of the same size are multiplied element by element. For the quadratic error ½(a − y)² the first link equals a − y. For softmax with cross-entropy the links cancel and δ^L = P − Y remains — the probabilities minus one at the right class (divided by N when averaged over the batch).
(2) Back propagation. The sum Zˡ affects C only through Zˡ⁺¹ = σ(Zˡ)Wˡ⁺¹ + bˡ⁺¹. A chain of two links: from Zˡ⁺¹ to Aˡ — multiplication by the transposed weight matrix, from Aˡ to Zˡ — the derivative of the sigmoid of each neuron: δˡ = (δˡ⁺¹Wˡ⁺¹ᵀ) ⊙ σ′(Zˡ). The sigmoid belongs to each neuron separately, so its derivative enters element-wise, not as a matrix product. For the sigmoid σ′(Z) = A ⊙ (1 − A) — from the saved output.
(3) By the bias. The bias enters the sum with coefficient 1: ∂C/∂bˡ is the sum of the rows of δˡ over the batch.
(4) By the weight. The weight w from input i to neuron j is multiplied by the input: ∂C/∂w = aᵢ · δⱼ, over the batch the sum of such products, in matrices ∂C/∂Wˡ = Aˡ⁻¹ᵀδˡ. Hence the rule: a weight from an input that was zero does not learn — with the bit inputs of 121ж that is every dark dot.
d = (softmax(Z[-1]) - T) / N # (1) выходной слой: softmax + перекрёстная энтропия
for li in range(len(P) - 1, -1, -1):
G[li] = [A[li].T @ d, d.sum(axis=0)] # (4) по весу: Aᵀ·δ; (3) по смещению: сумма δ
d = d @ Wt # (2) перенос назад: δ·Wᵀ …
d = d * A[li] * (1.0 - A[li]) # … ⊙ σ′(Z) = A(1 − A)
The equations were checked with central differences on a 35 → 16 → 16 → 10 network (1018 parameters, 10 examples): the largest difference relative to the largest derivative is 2.8·10⁻¹⁰ with softmax at the output and 2.0·10⁻¹⁰ with a sigmoid and the quadratic error. The Hadamard product and multiplication by the diagonal matrix diag(σ′) give the same thing (difference 1.1·10⁻¹⁶ — rounding), but the 16 × 16 diagonal matrix is 256 multiplications instead of 16.
121з.3 The algorithm step by step
- Forward pass: for l = 1…L compute Zˡ and Aˡ, keep them.
- The output layer error δ^L — equation (1).
- For l = L…1: the gradients of the layer by (3) and (4); if l > 1 — δˡ⁻¹ by (2), through the not yet corrected matrix Wˡ.
- Descent step: Wˡ ← Wˡ − η·∂C/∂Wˡ, bˡ ← bˡ − η·∂C/∂bˡ (step size, momentum and Adam — in 116б).
The 35 → 16 → 10 network trained with these four lines (batch 20, step 0.5, 60 epochs, its own seed) recognises 917 of 1000 on validation and 907 of 1000 on the test — in 121ж the same network with the best epoch chosen gave 909.
121з.4 Why it is fast: counting multiplications and time
The numerical gradient is simpler to write: shift one parameter by ±ε, compute the loss twice. But that is 2 forward passes per parameter, and a forward pass itself costs on the order of the number of parameters — in total the square of the number of weights. Backpropagation gets all derivatives in one forward and one backward pass:
| Network | Parameters | Multiplications per example: forward | backward | numerical gradient | Ratio |
|---|---|---|---|---|---|
| 35 → 16 → 10 | 746 | 720 | 880 | 1074240 | 671 |
| 35 → 128 → 128 → 10 | 22410 | 22144 | 39808 | 992494080 | 16020 |
The backward pass costs less than twice the forward: (4) repeats the forward computation, (2) does too, but without the first layer: δ for the inputs is not needed. Time of the gradient on a batch of 20 examples (numpy, best of repeats):
| Network | Forward pass | Backpropagation | Numerical gradient | Ratio |
|---|---|---|---|---|
| 35 → 16 → 10 | 10 µs | 16 µs | 16956 µs | 1073 |
| 35 → 128 → 128 → 10 | 44 µs | 88 µs | 2239259 µs | 25575 |
For the small network the gap in time is larger than in multiplications: every numpy call has an overhead, and the numerical gradient makes them 1492 times. The conclusion is the same: the numerical gradient is only good for checking (as in 116б), you cannot train with it — for the large network one epoch of 150 batches would take more than five minutes instead of 13.8 ms.
A batch in matrices against a loop. The same gradient can be computed example by example and summed — the result matches to 2·10⁻¹⁶. But:
| Network | Batch of 20: matrices | loop | Epoch of 3000 examples: matrices | loop |
|---|---|---|---|---|
| 35 → 16 → 10 | 16 µs | 256 µs | 2.5 ms | 40.9 ms |
| 35 → 128 → 128 → 10 | 88 µs | 942 µs | 13.8 ms | 153.7 ms |
A gain of 16.1 and 11.2 times per epoch. The number of multiplications is the same — fewer calls, and BLAS computes the matrix product in blocks, keeping them in the processor cache. The element-wise σ′ is cheaper than the diagonal matrix in time too: on a layer of 128 neurons 0.73 µs against 3.82 µs.
121з.5 Training on the instrument: memory and instructions
A microcontroller has no numpy, but the four equations go to C directly: for one example δ is a vector, (4) is an outer product. An SGD step over the whole 35 → 16 → 10 network, without storing gradients — the weights are corrected at once:
for (int j = 0; j < N_HID; j++) { /* (2) перенос назад — до правки W2: δ₁ = (W2·δ) ⊙ h(1 − h) */
float s = 0.0f;
for (int c = 0; c < N_OUT; c++)
s += W2[j * N_OUT + c] * d[c];
d1[j] = s * h[j] * (1.0f - h[j]);
}
Memory (float, 4 bytes per number), for one example:
| 35 → 16 → 10 | 35 → 128 → 128 → 10 | |
|---|---|---|
| weights and biases | 2984 bytes | 89640 bytes |
| layer outputs per example | 244 bytes | 1204 bytes |
| gradients, if accumulated over a batch | 2984 bytes | 89640 bytes |
Plus δ — 104 bytes for the small network. Inference keeps the weights in flash memory; training needs them in RAM. The STM32F407VG has 1 MB of flash memory, 128 KB of RAM and another 64 KB of CCM (Keil pack STM32F4xx_DFP 2.17.1): the small network fits with room to spare, for the large one the weights and the batch gradients are 175 KB, no longer in 128 KB. Fine-tuning one output layer leaves only W² and b² in RAM — 680 bytes, the first layer stays in flash memory as for inference.
Instructions — QEMU netduinoplus2 with -icount, arm-none-eabi-gcc code
-O2 with the FPU, average over 500 calls:
| Action | Instructions | At 168 MHz, no faster than |
|---|---|---|
| answer (forward pass) | 5913 | 35.2 µs |
| SGD step over the output layer | 8103 | 48.2 µs |
| SGD step over the whole network | 10898 | 64.9 µs |
A step over the whole network costs less than twice an answer, as the count
of multiplications says; the numerical gradient on the instrument would cost 1492 forward passes —
810 times more than a step. In bytes (armclang -Os, FPU): sgd_step_last —
174, sgd_step_full — 348, classify — 128, the shared hidden and out_delta —
100 and 208. These are instructions, not cycles: the time is a lower bound.
121з.6 Fine-tuning the last layer for a particular instrument
The network from 121ж was trained on boards mounted any which way: a shift by one dot in any direction. A particular instrument is assembled differently: the board is shifted by one dot right and down at once, and the phototransistors over dots 2 and 17 are flooded with light and are always on. The general network recognises 310 of 500 digits on this instrument (on the general test — 907 of 1000).
Calibration at commissioning: the technician shows each digit 5 times — 50 examples with a known answer. The first layer is frozen, the output layer is fine-tuned: 20 passes over these 50 examples, one example per step, step 0.1 — 1000 steps. Correct out of 500 on this instrument:
| After passes | 1 | 2 | 5 | 10 | 20 |
|---|---|---|---|---|---|
| correct | 361 | 375 | 402 | 419 | 435 |
C repeats numpy (float32, the same order of examples): on the computer and in QEMU 310 before fine-tuning, 435 after, the answers matched numpy in 500 cases of 500. 1000 steps are 8.10 million instructions, at 168 MHz no less than 48 ms. For comparison (numpy):
| What to fine-tune | On the instrument, of 500 | On the general test, of 1000 |
|---|---|---|
| nothing | 310 | 907 |
| output layer | 435 | 859 |
| the whole network | 469 | 833 |
| train from scratch on 50 examples, 200 passes | 500 | 85 |
A network trained from scratch on one instrument recognises everything: it has a constant shift, the task is simpler. But outside the instrument it recognises almost nothing (85 of 1000 — at the level of guessing), and training it would take the full backward pass. Fine-tuning the output layer is a cheap compromise: 680 bytes of RAM, without carrying δ into the first layer.
121з.7 Pitfalls
The sizes did not match — or, worse, they did. A forgotten transpose in (2) on the 35 → 16 → 10 network is caught by numpy at once: "16 is different from 10". But for a square 16 × 16 matrix (network 35 → 16 → 16 → 10) the sizes match and there is no error — the gradient is simply wrong: 0.09 against central differences. Check the gradient on a network where all layers have different widths, and write the size of every matrix next to the formula.
The derivative of the activation is forgotten. Without ⊙ σ′ in (2) the difference from central differences is 0.94: the gradient points almost anywhere. The code runs without a single error — such a thing can only be found by checking the gradient.
Float overflow on large inputs. Raw ADC codes 0…4095 instead of
bits: the sums of the first layer range from −59453 to 54063 (with bits — from −16.8
to 18.2). 99.8 % of the hidden-layer sigmoids in float32 hit exactly 0
or 1, their derivative is zero: (2) zeroes δ, and the first layer does not learn.
In a network without a hidden layer the logits reach 53977, and expf overflows
already above 88.72: the naive softmax gave NaN for 1000 examples of 1000,
with the largest logit subtracted — none. Normalise the inputs (117),
subtract the largest in softmax — that is what out_delta does.
W² corrected before back propagation. (2) needs the matrix before the descent step:
in sgd_step_full the δ of the first layer is computed before W² and b² are corrected.
The step is in RAM, the weights in flash memory. A const array cannot be fine-tuned:
W2 and B2 in model121i.h have no const, and they go to RAM.
121з.8 Summary
- A layer is Z = AW + b, A = σ(Z) for the whole batch; the layer error δ = ∂C/∂Z.
- Four equations: δ^L = P − Y (softmax), δˡ = (δˡ⁺¹Wˡ⁺¹ᵀ) ⊙ σ′, ∂C/∂b is the sum of δ, ∂C/∂W = Aᵀδ. They agree with central differences to 2.8·10⁻¹⁰.
- The backward pass costs less than two forward ones: 880 multiplications against 720. The numerical gradient is 671 times more expensive in multiplications, 1073 times in time for the network with 746 parameters and 25575 times for the one with 22410.
- A batch in matrices is faster than a loop over examples by 16.1 times per epoch.
- Cortex-M4F: an SGD step over the whole 35 → 16 → 10 network is 10898 instructions, over the output layer 8103, an answer 5913.
- Fine-tuning the output layer on 50 examples: 310 → 435 of 500 on the instrument, 680 bytes of RAM; C matched numpy in 500 cases of 500.
Further reading: Michael Nielsen, Neural Networks and Deep Learning, neuralnetworksanddeeplearning.com.
Full sources
train121i.c — the answer, an SGD step over the output layer and over the whole network in C with the weights from model121i.h.
/* Раздел 121з: шаг SGD на приборе для сети 35 → 16 → 10 (сигмоида, softmax с перекрёстной энтропией).
* sgd_step_last — дообучение только выходного слоя: первый слой заморожен (W1, B1 во флеш-памяти),
* в ОЗУ — W2 и B2. Уравнения (1), (3), (4).
* sgd_step_full — шаг по всей сети: все четыре уравнения; w1 и b1 — копия первого слоя в ОЗУ.
* Вход — 35 байтов 0/1. Веса и данные — model121i.h (train121i.py).
* На компьютере (-DML_HOST) main дообучает выходной слой на 50 примерах прибора и сверяет с numpy.
* Проверка — _verify/nn121i_check.py. */
#include <math.h>
#include <stdint.h>
#if defined(ML_HOST) && !defined(ML_DATA)
#define ML_DATA
#endif
#include "model121i.h"
static void hidden(const float *w1, const float *b1, const uint8_t *x, float *h)
{
for (int j = 0; j < N_HID; j++) {
float z = b1[j];
for (int i = 0; i < N_IN; i++)
if (x[i])
z += w1[i * N_HID + j];
h[j] = 1.0f / (1.0f + expf(-z));
}
}
/* выход слоя: δ = softmax(s) − y — уравнение (1) для softmax с перекрёстной энтропией */
static void out_delta(const float *h, int label, float *d)
{
float m, sum = 0.0f;
for (int c = 0; c < N_OUT; c++) {
float s = B2[c];
for (int j = 0; j < N_HID; j++)
s += h[j] * W2[j * N_OUT + c];
d[c] = s;
}
m = d[0];
for (int c = 1; c < N_OUT; c++)
if (d[c] > m)
m = d[c];
for (int c = 0; c < N_OUT; c++) {
d[c] = expf(d[c] - m); /* сначала вычесть наибольший — иначе expf переполнится */
sum += d[c];
}
for (int c = 0; c < N_OUT; c++)
d[c] /= sum;
d[label] -= 1.0f;
}
void sgd_step_last(const uint8_t *x, int label, float lr)
{
float h[N_HID], d[N_OUT];
hidden(W1, B1, x, h);
out_delta(h, label, d);
for (int j = 0; j < N_HID; j++)
for (int c = 0; c < N_OUT; c++)
W2[j * N_OUT + c] -= lr * h[j] * d[c]; /* (4) по весу: h·δ */
for (int c = 0; c < N_OUT; c++)
B2[c] -= lr * d[c]; /* (3) по смещению: δ */
}
void sgd_step_full(float *w1, float *b1, const uint8_t *x, int label, float lr)
{
float h[N_HID], d[N_OUT], d1[N_HID];
hidden(w1, b1, x, h);
out_delta(h, label, d);
for (int j = 0; j < N_HID; j++) { /* (2) перенос назад — до правки W2: δ₁ = (W2·δ) ⊙ h(1 − h) */
float s = 0.0f;
for (int c = 0; c < N_OUT; c++)
s += W2[j * N_OUT + c] * d[c];
d1[j] = s * h[j] * (1.0f - h[j]);
}
for (int j = 0; j < N_HID; j++)
for (int c = 0; c < N_OUT; c++)
W2[j * N_OUT + c] -= lr * h[j] * d[c];
for (int c = 0; c < N_OUT; c++)
B2[c] -= lr * d[c];
for (int i = 0; i < N_IN; i++) /* (4) для первого слоя: x·δ₁ — у входа 0 правки нет */
if (x[i])
for (int j = 0; j < N_HID; j++)
w1[i * N_HID + j] -= lr * d1[j];
for (int j = 0; j < N_HID; j++)
b1[j] -= lr * d1[j];
}
int classify(const uint8_t *x)
{
float h[N_HID], best = -1e30f;
int k = 0;
hidden(W1, B1, x, h);
for (int c = 0; c < N_OUT; c++) {
float s = B2[c];
for (int j = 0; j < N_HID; j++)
s += h[j] * W2[j * N_OUT + c];
if (s > best) {
best = s;
k = c;
}
}
return k;
}
#ifdef ML_HOST
#include <stdio.h>
int main(void)
{
int before = 0, after = 0, agree = 0;
for (int k = 0; k < N_DEV; k++)
before += classify(&DEV_X[k * N_IN]) == DEV_Y[k];
for (int e = 0; e < FT_EPOCHS; e++)
for (int k = 0; k < N_CAL; k++)
sgd_step_last(&CAL_X[k * N_IN], CAL_Y[k], FT_LR);
for (int k = 0; k < N_DEV; k++) {
int p = classify(&DEV_X[k * N_IN]);
after += p == DEV_Y[k];
agree += p == NP_FT[k];
}
printf("dev_before=%d,%d\ndev_after=%d,%d\nagree_ft=%d,%d\n", before, N_DEV, after, N_DEV, agree, N_DEV);
return 0;
}
#endif
Next: section 121и "Cross-entropy, softmax, regularization and hyperparameter tuning in practice" — the series "Neural networks from the inside": why the quadratic cost slows down a saturated neuron, how to compute softmax without infinities, what L2, L1, dropout and data augmentation do to the weights and in what order to tune the step, stopping and batch size.