Lesson 2.3 — Training Stability
Signal propagation · forward & backward signals
Forward signal
If activation scales grow across layers, values saturate or overflow; if they shrink, features collapse and become indistinguishable.
Backward signal
Each layer Jacobian acts on the upstream gradient, amplifying, compressing, or canceling directions. Gradient magnitude alone does not equal training quality.
Note on notation: mathematical derivations here use column vectors, while NumPy labs use
batch-first row-vector weights of shape (D_in, D_out). PyTorch
nn.Linear stores transposed weights of shape (D_out, D_in).
Gradient flow · Jacobian products
Follow one loss gradient backward. Each layer can stretch one direction and compress another. What reaches the input depends on which direction the preceding layer receives.
Let be a layer output, its Jacobian, and a column gradient. A two-layer trace reads from left to right below. The rightmost matrix in acts first.
| Start at the output | After | Action of | At the input |
|---|---|---|---|
| Horizontal unit arrow | Horizontal, twice as long | Double horizontal lengths again | Horizontal, length 4 |
| Horizontal unit arrow | Horizontal, twice as long | Halve horizontal lengths and double vertical ones | Horizontal, length 1 |
Both examples use layers whose largest stretch is 2. The second layer encountered in the backward pass can amplify a vertical arrow, but it receives a horizontal one. Multiplying the largest stretches gives an upper bound of 4 in both rows. Only the first row reaches it.
If every local norm is at most , even the upper bound shrinks as . For a scalar chain with a constant local derivative , the signed multiplier is exactly . Negative derivatives can reverse direction while the magnitude still shrinks.
Trace a scalar gradient through successive layers
01 · Scalar Gradient Chain
Activation and its local derivative
02 · Activation & Derivative Explorer
| Activation | Training Characteristics |
|---|---|
| Sigmoid | Saturates with vanishing gradients on both tails; non-zero-centered output; suited for binary probability outputs rather than deep hidden layers. |
| Tanh | Zero-centered output; saturates for large |z|. |
| ReLU | Derivative is 1 on positive inputs and 0 on negative inputs; can suffer from persistently inactive units. |
| GELU | Smooth nonlinearity retaining small negative values; common in Transformers, though not a guarantee of stability. |
Variance propagation · Xavier & He
He's derivation comes from ReLU's second moment rather than output variance halving directly. For
uniform initialization U(-a, a), variance is a²/3, so
a = √(3 Var(W)). Zero biases are fine, but all-zero weights fail to break symmetry.
03 · Deep Signal Profile (Width=16, 64 Samples)
PyTorch initialization snippet
import torch
from torch import nn
layer = nn.Linear(64, 64)
nn.init.xavier_uniform_(layer.weight) # near-linear / tanh baseline
nn.init.kaiming_uniform_(layer.weight, nonlinearity="relu") # ReLU
nn.init.zeros_(layer.bias)
Diagnose before clipping
Check data, loss, and learning rate first. Global gradient norm clipping only caps the current step's gradient magnitude—it cannot fix vanishing gradients and does not bound Adam's actual parameter update norm identically.
For threshold C > 0, clipping projects the combined gradient onto the closed Euclidean ball of radius C. Gradients inside the ball, including zero, stay where they are. Increasing the hidden third component in the diagram can shorten the projected arrow even if the first two components are fixed.
04 · Global Gradient Norm Clipping
PyTorch global gradient norm clipping
optimizer.zero_grad(set_to_none=True)
loss = criterion(model(x), y)
loss.backward()
# Returns total norm before clipping.
norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0, error_if_nonfinite=True)
optimizer.step()
BatchNorm, LayerNorm & RMSNorm
BatchNorm (B, D) depends on other samples in the mini-batch during training and uses
running statistics during evaluation. LayerNorm reduces across trailing feature dimensions per
sample without mixing tokens. RMSNorm scales by root-mean-square without subtracting the mean
and typically omits bias. Note that BatchNorm1d reduces (N, C, L)
across N and L—never pass (B, T, D) directly as
(N, C, L).
05 · Normalization Axis Inspector (4×3)
06 · BatchNorm Train / Eval Timeline
eval() mode, BatchNorm freezes running statistics rather than normalizing by the current batch.PyTorch normalization & clipping verification
import torch
from torch import nn
from torch.nn import functional as F
torch.set_default_dtype(torch.float64)
x = torch.tensor([[1., 3., 6.], [2., 4., 8.], [3., 5., 10.], [4., 6., 12.]])
eps = 1e-5
for dim, layer in [
(0, nn.BatchNorm1d(3, affine=False, eps=eps)),
(1, nn.LayerNorm(3, elementwise_affine=False, eps=eps)),
]:
manual = (x - x.mean(dim, keepdim=True)) / (x.var(dim, unbiased=False, keepdim=True) + eps).sqrt()
torch.testing.assert_close(layer(x), manual)
rms = x / (x.square().mean(-1, keepdim=True) + eps).sqrt()
torch.testing.assert_close(F.rms_norm(x, (3,), eps=eps), rms)
bn = nn.BatchNorm1d(1, affine=False, momentum=0.1, eps=eps)
for batch in [torch.arange(4.)[:, None], torch.arange(2., 6.)[:, None]]:
bn.train()
bn(batch)
print("running stats:", bn.running_mean.item(), bn.running_var.item())
bn.eval()
print("eval:", bn(torch.arange(1., 5.)[:, None]).flatten())
p = nn.Parameter(torch.zeros(3))
p.grad = torch.tensor([3., 4., 0.])
n = nn.utils.clip_grad_norm_([p], 2.0)
assert abs(n.item() - 5) < 1e-12 and abs(p.grad.norm().item() - 2) < 1e-5
print("normalization and clipping checks passed")
Identity path and gradient transport
When F's Jacobian is small, the residual block stays close to the identity; residual
connections require matching input and output shapes (or an explicit projection). Pre-norm vs.
post-norm Transformer layouts are covered in Chapter 04.
07 · Residual Gradient Route
Controlled deep MLP · robot dynamics
08 · Live Deep MLP Stability Benchmark
Default single-seed results at 5 hidden layers: Tiny/Tanh val ≈ 0.97137, Xavier/Tanh
≈ 0.01513; Xavier/ReLU ≈ 0.03114, He/ReLU ≈ 0.03274;
Xavier/Tanh residual ≈ 0.03039. The latter two pairs do not prove He or residual is
always better—structural changes alter the initial function, and real comparisons require multiple
seeds, separate tuning, and an independent test set.
Complete implementation · NumPy + PyTorch
import numpy as np
import torch
from torch import nn
torch.set_num_threads(1)
def init(depth, width, scheme, seed=42):
state = seed
def rand(shape):
nonlocal state
vals = []
for _ in range(int(np.prod(shape))):
state = (1664525 * state + 1013904223) % 2**32
vals.append(2 * state / 2**32 - 1)
return np.array(vals).reshape(shape)
sizes = [2] + [width] * depth + [1]
params = []
for i, (a, b) in enumerate(zip(sizes, sizes[1:])):
var = {"tiny": 0.01 / a, "large": 4 / a, "xavier": 2 / (a + b), "he": 2 / a}[scheme] if i < depth else 2 / (a + b)
params.append([rand((a, b)) * np.sqrt(3 * var), np.zeros(b)])
return params
def dataset(n, shift):
i = np.arange(n) + shift
x = 2 * np.sin(1.71 * i + 0.2)
u = np.cos(2.13 * i + 0.4)
return np.stack([x, u], 1), (0.65 * x + 0.5 * np.sin(2 * x) + 0.35 * u)[:, None]
def forward(p, X, act, residual):
h = X
cache = []
for i, (W, b) in enumerate(p[:-1]):
z = h @ W + b
a = np.tanh(z) if act == "tanh" else np.maximum(0, z)
skip = residual and i > 0
cache.append((h, z, a, skip))
h = h + 0.2 * a if skip else a
return h @ p[-1][0] + p[-1][1], h, cache
def gradient(p, X, y, act, residual):
pred, h, cache = forward(p, X, act, residual)
g = 2 * (pred - y) / pred.size
grads = [(h.T @ g, g.sum(0))]
g = g @ p[-1][0].T
for i in reversed(range(len(cache))):
h, z, a, skip = cache[i]
dz = g * (0.2 if skip else 1) * (1 - a * a if act == "tanh" else (z > 0))
grads.append((h.T @ dz, dz.sum(0)))
g = dz @ p[i][0].T + (g if skip else 0)
return grads[::-1]
class MLP(nn.Module):
def __init__(self, p, act, residual):
super().__init__()
self.layers = nn.ModuleList([nn.Linear(W.shape[0], W.shape[1], dtype=torch.float64) for W, b in p])
self.act = act
self.residual = residual
with torch.no_grad():
for l, (W, b) in zip(self.layers, p):
l.weight.copy_(torch.tensor(W.T))
l.bias.copy_(torch.tensor(b))
def forward(self, x):
for i, l in enumerate(self.layers[:-1]):
z = l(x)
a = torch.tanh(z) if self.act == "tanh" else torch.relu(z)
x = x + 0.2 * a if self.residual and i > 0 else a
return self.layers[-1](x)
def run(scheme, act, residual=False, depth=5, width=6, lr=0.025, epochs=60):
X, y = dataset(64, 0)
V, vy = dataset(32, 100)
p = init(depth, width, scheme)
model = MLP(p, act, residual)
opt = torch.optim.SGD(model.parameters(), lr=lr)
initial = float(np.mean((forward(p, X, act, residual)[0] - y)**2))
err = 0.0
for ep in range(epochs):
order = (np.arange(len(y)) + 7 * ep) % len(y)
for start in range(0, len(y), 16):
ids = order[start:start + 16]
xx, yy = X[ids], y[ids]
grad = gradient(p, xx, yy, act, residual)
opt.zero_grad()
loss = ((model(torch.tensor(xx)) - torch.tensor(yy))**2).mean()
loss.backward()
for l, (gW, gb) in zip(model.layers, grad):
err = max(err, np.max(np.abs(gW - l.weight.grad.numpy().T)), np.max(np.abs(gb - l.bias.grad.numpy())))
p = [[W - lr * gW, b - lr * gb] for (W, b), (gW, gb) in zip(p, grad)]
opt.step()
pe = max(max(np.max(np.abs(W - l.weight.detach().numpy().T)), np.max(np.abs(b - l.bias.detach().numpy()))) for (W, b), l in zip(p, model.layers))
tr = float(np.mean((forward(p, X, act, residual)[0] - y)**2))
va = float(np.mean((forward(p, V, act, residual)[0] - vy)**2))
assert err < 1e-8 and pe < 1e-8, (err, pe)
print(scheme, act, residual, "initial", initial, "train", tr, "val", va, "grad_err", err, "param_err", pe)
return initial, tr, va
if __name__ == "__main__":
for cfg in [("tiny", "tanh", False), ("xavier", "tanh", False), ("xavier", "relu", False), ("he", "relu", False), ("xavier", "tanh", True)]:
run(*cfg)