121л. Why deep networks are hard to train: vanishing and exploding gradients, ReLU, normalization, residual connections
In 121к it turned out that depth pays: ten layers of two neurons do what a single layer needs a thousand neurons for. 116б.5 shows the flip side: a sigmoid network of ten layers barely learns, because the gradient at the first layers is millions of times smaller than at the output. Here in more detail: how exactly the gradient weakens from layer to layer and why the factor per layer is below one, when it grows instead and how to limit it, why ReLU is better than the sigmoid and how it is worse, what batch normalization and a residual connection do. And for each remedy, what it costs on a Cortex-M4: what stays in the firmware and what disappears.
Basis: numpy 2.3.3 in the stm-ml:1 image, the script train121l.py runs all
experiments, a repeated run gives the same files. Data: the same reader
of a 5 × 7 dot-matrix display as in 121ж and 121з: 35 points, 10 digits,
3000 training examples and 1000 test examples, seed 1218. Training:
mini-batches of 20 examples, softmax with cross-entropy (121и).
Network inference in C: gcc 12.2.0 (stm-sys:1) for cross-checking, 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) for instruction counts.
What it is called in the documentation
Original Meaning exploding gradient the gradient grows from layer to layer and training diverges gradient norm clipping a step that is too long is shortened to a given length unstable gradient the per-layer factors are not equal to one, so the gradient fades or grows dead (dying) ReLU a ReLU neuron whose sum is below zero on every example: output and gradient are zero batch statistics, running statistics mean and variance over the batch in training and the stored ones in use BN folding γ, β, μ and σ move into the weights and bias of the previous layer residual (skip) connection the block output is its input plus a correction a + f(a) depth vs width the same weights in several narrow layers or in one wide layer
121л.1 Experiment: the gradient by layer
Sigmoid networks 35 → 16 × H → 10, where H is the number of hidden layers of 16 neurons, initial weights by Xavier (116б.5). The measure of how fast a layer learns is the norm of the loss gradient with respect to its weights over all 3000 examples before training: the SGD step for that layer is proportional to it.
| Hidden layers H | 2 | 4 | 8 |
|---|---|---|---|
| first-layer gradient | 0.0322 | 0.0015 | 3.07·10⁻⁶ |
| output-layer gradient | 0.373 | 0.537 | 0.258 |
| factor per layer backward, average | 0.29 | 0.21 | 0.24 |
| correct of 1000 after 30 epochs, step 0.5 | 912 | 444 | 100 |
With each layer closer to the input the gradient is multiplied by roughly a quarter. With eight layers the first one learns 84000 times slower than the output, and the network does not learn at all: 100 of 1000 is guessing. Training does not fix it: after 30 epochs the same network has a first-layer gradient of 3.12·10⁻⁷ and an output gradient of 0.00437. The output layer has adapted to the almost random features the lower layers feed it, and after that the loss barely changes.
121л.2 Where the factor comes from: σ′ times a weight
From 121з: the layer error δˡ = (δˡ⁺¹·Wᵀ) ⊙ σ′(zˡ). In the backward pass this is the line
du = da * (c["h"] * (1.0 - c["h"]) if N["act"] == "sig" else (c["u"] > 0)) # δ ⊙ f′
At each layer backward the error passes two factors: the weights and the derivative of the activation. For one path through the network this is the product w·σ′(z) over all layers of the path. The sigmoid derivative σ′(z) = σ(z)·(1 − σ(z)) is largest at z = 0 and equals 1/4 there: the product of two numbers summing to 1 is at most ½ · ½. So |w·σ′| ≤ |w|/4, and for the factor to be at least one a weight above 4 in magnitude is needed, while z must stay near zero.
With Xavier initial weights the spread of a 16 → 16 layer is 0.250, so |w|/4 is about 0.05 on average. A layer has not one path but a sum over 16 neurons, so the result is not 0.05 but the measured 0.21–0.29. The mean σ′ over all neurons and examples in the experiment is 0.233: the sigmoid works almost in the middle, and it is mainly the weights that keep the factor below one.
This also shows that vanishing and exploding are one disease: the first-layer gradient is the product of the factors of all layers above it, and if they are not close to one, the product over eight layers moves by orders of magnitude one way or the other. For the sigmoid to get a factor above one it needs large weights, and large weights push z away from zero, where σ′ is small. That is why in sigmoid networks the gradient vanishes more often than it explodes.
121л.3 Exploding gradient and norm clipping
For ReLU the derivative is zero or one, and the factor per layer is set only by the weights. A network 35 → 32 × 8 → 10 with ReLU, initial spread by He √(2/n_in) and twice that, training for 20 epochs, step 0.05:
| Weight spread | He | twice as large |
|---|---|---|
| loss before training | 2.55 | 431 |
| total gradient norm | 2.41 | 1400 |
| spread of network outputs | 0.866 | 444 |
| SGD, correct of 1000 | 949 | diverges: the loss is not a number |
| SGD with norm clipping to 1, correct of 1000 | 911 | 755 |
Doubling the weight spread doubles the signal at every layer: over nine layers that is 512 times, and the outputs are hundreds instead of units. The gradient is just as huge; the very first SGD step inflates the weights further, and after a few steps the loss becomes infinite.
Norm clipping is the simplest remedy: if the total length of the gradient exceeds the threshold, it is shortened to the threshold, keeping the direction:
if clip is not None:
nr = gnorm(G)
if nr > clip:
sc = clip / nr
With it the same bad network learns: 755 of 1000. But clipping treats the symptom: on a good network with threshold 1 it gave 911 instead of 949, because clipping also fired where the step was normal. The threshold is chosen from the typical gradient norm of a trained network, and the root cause, the scale of the weights, is fixed by proper initialization.
121л.4 ReLU: a cheap factor of one and dead neurons
The ReLU derivative is 1 where the neuron is open, and the factor per layer is not squeezed by σ′. This is the main reason deep networks moved to ReLU. The price: a neuron whose sum is below zero on all examples gets a zero gradient and will never open again: it is dead. A network 35 → 64 → 64 → 10 with ReLU, 30 epochs, dead neurons counted on all 3000 examples after training:
| Learning step | 0.05 | 0.5 | 1 | 2 |
|---|---|---|---|---|
| dead in the first layer of 64 | 0 | 0 | 12 | 45 |
| dead in the second layer of 64 | 0 | 0 | 1 | 64 |
| correct of 1000 | 950 | 959 | 952 | 112 |
There are no dead neurons while the step is moderate. At step 1, 12 neurons of the first layer died, almost a fifth, and accuracy barely changed: the network had headroom. At step 2 one large step drove the biases deep below zero, the whole second layer died, and the network answers with almost one class. A dead neuron on a device is 33 weights that sit in flash and are computed on every inference, changing nothing. It is worth finding them by running the training set and cutting them out before moving to the device.
Weight spread for ReLU. ReLU zeroes half of the sums, so the signal at a layer loses half of its variance; He doubles the spread compared with Xavier exactly for this case. A network 35 → 32 × 16 → 10 with ReLU, spread of the hidden-layer outputs before training:
| Layer | 1 | 4 | 8 | 12 | 16 | Correct of 1000 after 20 epochs |
|---|---|---|---|---|---|---|
| Xavier | 0.38 | 0.112 | 0.0348 | 0.0131 | 0.00138 | 691 |
| He | 0.526 | 0.438 | 0.544 | 0.823 | 0.345 | 857 |
With Xavier the signal by the sixteenth layer has weakened almost 300 times, and the gradient weakens likewise. With He it stays within the same range over the whole depth.
121л.5 Batch normalization, folding it into the weights, and residual connections
Batch normalization (118а) sits between the weighted sum and the activation: each neuron's sum is brought to mean 0 and spread 1 over the examples of the batch, then scaled and shifted by trainable γ and β. Whatever the layer weights do, the activation input gets a signal of one scale, and the factor per layer no longer depends on the weight spread. The same eight-layer sigmoid network from 121л.1, but with normalization:
| Network 35 → 16 × 8 → 10 | first-layer gradient | output gradient | correct of 1000 |
|---|---|---|---|
| without normalization | 3.07·10⁻⁶ | 0.258 | 100 |
| with normalization | 0.173 | 0.263 | 922 |
In the figure this is the dashed line: the gradient is of one order at every layer.
There is no normalization on the device. After training μ and σ are stored (here recomputed over the whole training set), and normalization becomes a linear function of one sum: γ·(z − μ)/σ + β. The weighted sum z = w·x + b is linear too, and two linear functions in a row are one: W′ = W·γ/σ, b′ = (b − μ)·γ/σ + β.
k = N["g"][l] / np.sqrt(N["var"][l] + EPS)
W.append(N["W"][l] * k)
b.append((N["b"][l] - N["mu"][l]) * k + N["be"][l])
In numbers: the first neuron of the first layer of the network 35 → 32 → 32 → 10 with ReLU and normalization: weight from the first input −0.1402, bias 0.0000, μ = −0.4440, σ = 0.8205, γ = 1.0042, β = 0.0861. Folded: −0.1402·1.0042/0.8205 = −0.1716 and (0 + 0.4440)·1.0042/0.8205 + 0.0861 = 0.6295. Check on all 1000 test examples: in double the largest output difference between "normalization as is" and "folded" is 1.1·10⁻¹⁴, the answer matched on 1000 of 1000; in C in float32 it is 6.4·10⁻⁶, both networks are right on 953 of 1000.
Residual connections. A residual connection adds the block input to its output: a + f(a). In the forward pass it is one addition:
A.append(A[-1] + h if N["res"] and A[-1].shape[1] == h.shape[1] else h) # остаточная связь
In the backward pass the derivative of a + f(a) with respect to a is one plus the derivative of f, and the gradient gets a path to the first layers with neither σ′ nor weights on it. Networks 35 → 32 × H → 10, 20 epochs; first-layer gradient before training:
| Network | Connections | First-layer gradient | Correct of 1000 |
|---|---|---|---|
| sigmoid, 16 layers | none | 2.88·10⁻¹¹ | 95 |
| sigmoid, 16 layers | residual | 0.487 | 929 |
| ReLU with He, 32 layers | none | 0.245 | 95 |
| ReLU with He, 32 layers | residual, weights as is | 7.67·10⁶ | diverges |
| ReLU with He, 32 layers | residual, block weights ×0.1 | 2.61 | 950 |
| ReLU with He, 50 layers | none | 0.0584 | 100 |
| ReLU with He, 50 layers | residual, block weights ×0.1 | 9.34 | 946 |
Sixteen sigmoid layers without the connections do not learn at all; with them, 929. ReLU with He already fails to learn at 32 layers in 20 epochs, though the first-layer gradient is fine. Residual connections with full He weights do the opposite: each block adds a signal of the same size to the signal, and after 32 blocks it explodes. A block must start by giving a small correction, inner-layer weights 10 times smaller, and then both 32 and 50 layers learn.
121л.6 What matters on a Cortex-M
Training stays on the computer; the device runs the forward pass (121ж, 121з).
One C function dense computes all variants: normalization as is,
folded, ReLU and sigmoid. Normalization as is is the line
if (L->mu)
s = (s - L->mu[j]) / sqrtf(L->var[j] + 1e-5f) * L->g[j] + L->be[j];
Instructions: QEMU netduinoplus2 with -icount, arm-none-eabi-gcc -O2 with FPU,
average over 100 inferences; accuracy: on 1000 examples in C in QEMU,
matching the computer:
| Network | Weights | Instructions per inference | At 168 MHz, no faster than | Correct of 1000 |
|---|---|---|---|---|
| 35 → 32 → 32 → 10 with ReLU, normalization as is | 2464 + 256 | 17786 | 105.9 µs | 953 |
| the same, normalization folded | 2464 | 16698 | 99.4 µs | 953 |
| the same, sigmoid instead of ReLU | 2464 | 21284 | 126.7 µs | — |
| wide 35 → 80 → 10 with ReLU | 3600 | 23790 | 141.6 µs | 958 |
| deep 35 → 28 × 4 → 10 with ReLU | 3612 | 24602 | 146.4 µs | 914 |
ReLU is cheaper than the sigmoid. The sigmoid instead of ReLU on 64 hidden neurons
added 4586 instructions, about 72 instructions per neuron, which is expf; ReLU is
one comparison. And expf from newlib takes 600 bytes of flash,
which a ReLU network does not need.
Folded normalization costs nothing. Normalization as is costs 1088 extra instructions (17 per neuron, including a square root and a division) and 256 numbers γ, β, μ, σ, which is 1024 bytes. Folded: zero instructions and zero bytes beyond an ordinary layer, and the same answers.
Depth versus width. The weights are nearly equal: 3600 and 3612. The deep network needs 3.4 % more instructions, the overhead of each layer. But the RAM for activations is two neighbouring layers at once: for the wide one 35 + 80 = 115 numbers, 460 bytes, for the deep one 35 + 28 = 63 numbers, 252 bytes. On such a small task the wide network is more accurate, 958 against 914; the gain from depth, as in 121к, appears when the task itself is built from parts. The conclusion is not "deeper is better" but to measure: accuracy on the set, instructions and RAM for activations.
121л.7 Pitfalls
A bias before normalization does not learn. Normalization subtracts the mean of the sum, and the bias b is subtracted with it: its gradient is zero. In the experiment the first neuron's bias after 30 epochs is 0.0000. Its role is taken by β; in layers with normalization b can be omitted.
Residual connections and full weights. a + f(a) with He weights doubles the variance at each block: over 32 blocks the first-layer gradient is 7.67·10⁶, and training diverges at once. The branch f starts with small weights.
Folding with the wrong statistics. μ and σ must be the ones the network uses in operation: stored over the whole set, not the statistics of the last batch. And ε under the root must be the same as in training: in Keras and in your own code it can differ.
Clipping where it is not needed. A threshold of 1 on a healthy network cut accuracy from 949 to 911. The threshold is set above the typical norm, so that it fires only on outliers.
A large step and ReLU. At step 2 the network 35 → 64 → 64 → 10 lost the whole second layer. If after training accuracy suddenly drops to one class, count the dead neurons first.
The difference of the folded network is not zero. In float32 the outputs differ by 6.4·10⁻⁶: the order of additions is different. Compare answers on the set, not outputs bit by bit.
121л.8 Summary
- A sigmoid network with eight layers: first-layer gradient 3.07·10⁻⁶ against 0.258 at the output, 100 of 1000 correct; factor per layer 0.21–0.29.
- σ′ ≤ 1/4, so |w·σ′| ≥ 1 requires a weight above 4.
- Weights twice as large as He on an eight-layer ReLU network: loss 431, training diverges; norm clipping to 1 gives 755 of 1000.
- ReLU at step 2: 45 neurons of the first layer and all 64 of the second are dead.
- Batch normalization: first-layer gradient 0.173, 922 correct; folded into the weights: output difference 1.1·10⁻¹⁴ and not a single extra instruction.
- Residual connections: a sigmoid on 16 layers gives 929 instead of 95; ReLU on 50 layers gives 946 instead of 100, if the branch starts with small weights.
- Cortex-M4: the sigmoid is about 72 instructions per neuron, normalization as is is 1088 instructions per network, folded is zero; a deep network with the same weights needs 252 bytes of activations against 460.
Further reading: Michael Nielsen, Neural Networks and Deep Learning, neuralnetworksanddeeplearning.com.
Full sources
deep121l.c — network forward pass in C with normalization as is or folded, ReLU or sigmoid, with weights from model121l.h.
/* Раздел 121л: ответ сети на C — что из «трудностей глубины» остаётся на приборе.
* layer_t — слой: веса по нейронам W[j][i], смещения, необязательная нормировка (mu, var, g, be).
* dense — взвешенная сумма, нормировка (если есть) и активация ReLU или сигмоида.
* net_run — прямой проход по слоям через два буфера, ответ — номер наибольшего выхода.
* Сети из model121l.h (train121l.py): BN — 35 → 32 → 32 → 10 с нормировкой как есть, FOLD — она же
* со впечённой нормировкой, WIDE — 35 → 80 → 10, DEEP — 35 → 28 × 4 → 10.
* На компьютере (-DML_HOST) main считает точность каждой сети на 1000 проверочных примерах.
* Проверка — _verify/nn121l_check.py. */
#include <math.h>
#include <stdint.h>
#include "model121l.h"
enum { ACT_RELU, ACT_SIG, ACT_NONE };
typedef struct {
int nin, nout;
const float *W, *b;
const float *mu, *var, *g, *be;
} layer_t;
#define MAXW 80
static float abuf[2][MAXW];
static void dense(const layer_t *L, const float *x, float *y, int act)
{
for (int j = 0; j < L->nout; j++) {
const float *w = L->W + j * L->nin;
float s = L->b[j];
for (int i = 0; i < L->nin; i++)
s += w[i] * x[i];
if (L->mu)
s = (s - L->mu[j]) / sqrtf(L->var[j] + 1e-5f) * L->g[j] + L->be[j];
if (act == ACT_RELU)
s = s > 0.0f ? s : 0.0f;
else if (act == ACT_SIG)
s = 1.0f / (1.0f + expf(-s));
y[j] = s;
}
}
int net_run(const layer_t *L, int nl, const uint8_t *in, int act, float *out)
{
float *x = abuf[0], *y = abuf[1], *t;
for (int i = 0; i < L[0].nin; i++)
x[i] = (float)in[i];
for (int l = 0; l < nl; l++) {
dense(&L[l], x, y, l == nl - 1 ? ACT_NONE : act);
t = x, x = y, y = t;
}
int best = 0;
for (int j = 0; j < L[nl - 1].nout; j++) {
if (out)
out[j] = x[j];
if (x[j] > x[best])
best = j;
}
return best;
}
static const layer_t NET_BN[3] = {
{35, 32, BN_W0, BN_B0, BN_MU0, BN_VAR0, BN_G0, BN_BE0},
{32, 32, BN_W1, BN_B1, BN_MU1, BN_VAR1, BN_G1, BN_BE1},
{32, 10, BN_W2, BN_B2, 0, 0, 0, 0},
};
static const layer_t NET_FOLD[3] = {
{35, 32, FD_W0, FD_B0, 0, 0, 0, 0},
{32, 32, FD_W1, FD_B1, 0, 0, 0, 0},
{32, 10, FD_W2, FD_B2, 0, 0, 0, 0},
};
static const layer_t NET_WIDE[2] = {
{35, 80, WIDE_W0, WIDE_B0, 0, 0, 0, 0},
{80, 10, WIDE_W1, WIDE_B1, 0, 0, 0, 0},
};
static const layer_t NET_DEEP[5] = {
{35, 28, DEEP_W0, DEEP_B0, 0, 0, 0, 0},
{28, 28, DEEP_W1, DEEP_B1, 0, 0, 0, 0},
{28, 28, DEEP_W2, DEEP_B2, 0, 0, 0, 0},
{28, 28, DEEP_W3, DEEP_B3, 0, 0, 0, 0},
{28, 10, DEEP_W4, DEEP_B4, 0, 0, 0, 0},
};
int count_right(const layer_t *L, int nl, int act)
{
int ok = 0;
for (int k = 0; k < N_TEST; k++)
ok += net_run(L, nl, TEST_X + 35 * k, act, 0) == TEST_Y[k];
return ok;
}
float fold_diff(void)
{
float a[10], b[10], e = 0.0f;
for (int k = 0; k < N_TEST; k++) {
net_run(NET_BN, 3, TEST_X + 35 * k, ACT_RELU, a);
net_run(NET_FOLD, 3, TEST_X + 35 * k, ACT_RELU, b);
for (int j = 0; j < 10; j++)
e = fmaxf(e, fabsf(a[j] - b[j]));
}
return e;
}
#ifdef ML_HOST
#include <stdio.h>
int main(void)
{
printf("right_bn=%d\n", count_right(NET_BN, 3, ACT_RELU));
printf("right_fold=%d\n", count_right(NET_FOLD, 3, ACT_RELU));
printf("right_wide=%d\n", count_right(NET_WIDE, 2, ACT_RELU));
printf("right_deep=%d\n", count_right(NET_DEEP, 5, ACT_RELU));
printf("fold_diff=%.1e\n", fold_diff());
return 0;
}
#endif
Next: section 121м "A convolutional network by hand: convolution, pooling, shared weights — and the same network in int8 on a Cortex-M" — the series "Neural networks from the inside": how a filter with shared weights slides along an accelerometer signal, why the global maximum finds a short event anywhere in the window, how to pass the gradient through convolution and pooling and check it numerically — and how the same network lives in int8 on a Cortex-M4 with our own code and with CMSIS-NN.