Neural-net foundations6 / 15

Lesson 6 · Building networks

Making deep networks train

The problem

The course's default network has two hidden layers. What happens with twenty?

Take a 20-layer network, 32 units wide, on the same rush-hour deliveries. Train it with the Lesson 4 template, unchanged: AdamW, learning rate 0.01, batches of 32, 40 epochs. The only thing that changes is the starting size of the weights:

Starting weightsBest validation accuracy
the right size (explained below)88%
half that size53.5%
twice that size78%, with a validation loss of 43.5

53.5% is what you get by calling every delivery "on time". A factor of two in the starting weights decides whether the network learns at all. This lesson shows why, and what keeps a deep network trainable: careful starting weights, normalisation layers and gradient clipping.

Watching a signal through 20 layers

Each layer multiplies its input by a weight matrix and applies an activation. Some of that pushes numbers up, some pushes them down. Over 20 layers, a small push either way adds up.

The figure below passes all 200 training deliveries through the 20-layer network once, forward and then backward. Each small histogram shows one layer's numbers, with their spread (the standard deviation) in the corner. "Layer outputs" are h(ℓ)\mathbf{h}^{(\ell)}, the values after the activation. "Weight gradients" are the gradients of the loss for W(ℓ)W^{(\ell)}, what the optimiser uses to update that layer.

Activation:
Starting scale:
Normalisation:

Spread of the outputs: layer 1 0.86, layer 20 0.26 (×0.31).

Step 0 · epoch 0 · loss 0.677 · validation accuracy 46.5%

Training uses the template: AdamW, learning rate 0.01, batches of 32, up to 20 epochs. Accuracy is measured every 4 epochs.

A 20-layer, 32-wide network on the 200 training deliveries. Each tile is one layer; all tiles share one x-axis, so a shrinking spread shows as a narrow spike. Change the activation, the starting scale or the normalisation, then train it with the Lesson 4 template.

Things to notice, with no normalisation:

  • ReLU at ×1: the outputs keep a sensible spread all the way down (0.86 at layer 1, 0.26 at layer 20).
  • ReLU at ×0.5: the spread halves at every layer. By layer 20 it's 0.00000025. Every gradient is tiny too, around 10−810^{-8}, because each weight's gradient is multiplied by the small signal coming into it.
  • ReLU at ×2: the spread doubles at every layer, to about 280,000. The gradients are in the tens of thousands.
  • Sigmoid, even at ×1: the outputs look fine, but the gradients shrink towards the input. They're 0.027 for the last layer's weights and 10−1410^{-14} for the first. The first layers can't learn.
  • Tanh at ×2: the opposite. The gradients grow towards the input, from 0.1 to 6.5.

These numbers come from the figure's random starting weights. PyTorch's own random draw gives slightly different numbers.

Train a few of them. ReLU at ×1 learns. ReLU at ×0.5 and sigmoid stay near 50%. ReLU at ×2 swings wildly.

These two failures have names. Vanishing gradients: the gradients shrink as they flow back, so the early layers barely learn. Exploding gradients: they grow, and the steps become wild.

Why: the same multiplication, twenty times

Backprop multiplies the gradient by each layer's local gradient on its way back. Twenty layers means twenty multiplications. If each one shrinks the gradient by half, you're left with 0.5200.5^{20} of it.

0510152010⁻⁶10⁻⁴10⁻²110²10⁴10⁶layers passedsize (log scale)

After 0 layers: 20 = 1 and 0.50 = 1

Layer 0 of 20

Lines: ×2 (solid) and ×0.5 (dashed) per layer. Dots: the real 20-layer ReLU network’s output spread, relative to layer 1, started at ×2 and ×0.5.

Multiply by 0.5 twenty times, or by 2 twenty times, on a log scale. The dots are the real ReLU network's output spread at each layer, divided by layer 1's, started at ×0.5 and at ×2.

The real network sits right on the lines. 0.5200.5^{20} is about one millionth and 2202^{20} is about a million. Nothing in between survives 20 layers.

This is the "settle or explode" table from the Eigenvectors lesson. Apply a matrix again and again, and every vector shrinks to zero if its spectral radius is below 1. If it's above 1, most vectors blow up. A deep network is a matrix power in disguise, with an activation squeezed in between each multiplication. Training only works near the edge, where each layer keeps the size about the same.

The activation's slope is part of each multiplication. The sigmoid's slope is at most 0.25. So ten sigmoid layers shrink a gradient to at most 0.25100.25^{10}, about one millionth, unless the weights are large. That is the problem the "Why ReLU won" aside in Lesson 1 described. ReLU's slope is exactly 1 for positive inputs, so it doesn't shrink the gradient on its own.

Starting weights: the 1/√fan-in rule

Weights must start random, but at what size? Think about one unit in a layer with 32 inputs. Its sum is z=w1x1+⋯+w32x32z = w_1 x_1 + \dots + w_{32} x_{32}: 32 terms added up. The number of inputs a unit has is its fan-in.

If the inputs and weights are independent with mean 0, the variances of the terms add up:

Var⁡(z)=fan-in×Var⁡(w)×Var⁡(x)\operatorname{Var}(z) = \text{fan-in} \times \operatorname{Var}(w) \times \operatorname{Var}(x)

To keep Var⁡(z)=Var⁡(x)\operatorname{Var}(z) = \operatorname{Var}(x), the weights need Var⁡(w)=1/fan-in\operatorname{Var}(w) = 1/\text{fan-in}, so their standard deviation is 1/fan-in1/\sqrt{\text{fan-in}}.

ReLU sets the negative half of zz to zero, which halves the variance. To make up for it, double the weights' variance: standard deviation 2/fan-in\sqrt{2/\text{fan-in}}. This is He initialisation (also called Kaiming initialisation, after Kaiming He).

Worked example

The right scale for a 32-wide ReLU layer

  1. Fan-in is 32. He initialisation: 2/32=1/16=0.25\sqrt{2 / 32} = \sqrt{1/16} = 0.25. So each weight is drawn from a normal distribution with mean 0 and standard deviation 0.25.

Choosing the starting weights like this is weight initialisation. Other activations need other factors. PyTorch calls the factor the gain: 2\sqrt{2} for ReLU, 5/35/3 for tanh and 1 for sigmoid. The standard deviation is the gain divided by fan-in\sqrt{\text{fan-in}}, and that is what "×1" means in the figure.

Predict first

Every weight and bias in the default 2-16-16-2 network starts at exactly 0.1, and then it trains as usual. Afterwards, how many different hidden units does each layer have?

DeeperWhere the 1/√fan-in rule comes fromThe variance of a sum of independent terms is the sum of their variances. The rule falls out in three lines. · 3 min

Take one term, wxw x, with ww and xx independent and ww having mean 0. Its mean is E[w]E[x]=0E[w]E[x] = 0. Its variance is

Var⁡(wx)=E[w2x2]=E[w2] E[x2]=Var⁡(w) E[x2]\operatorname{Var}(wx) = E[w^2 x^2] = E[w^2]\,E[x^2] = \operatorname{Var}(w)\,E[x^2]

The sum zz has fan-in such terms, all independent, so the variances add (from the Expectation lesson):

Var⁡(z)=fan-in×Var⁡(w) E[x2]\operatorname{Var}(z) = \text{fan-in} \times \operatorname{Var}(w)\, E[x^2]

If xx itself has mean 0, E[x2]=Var⁡(x)E[x^2] = \operatorname{Var}(x), and setting Var⁡(w)=1/fan-in\operatorname{Var}(w) = 1/\text{fan-in} keeps the variance fixed. This is the rule for tanh-like activations, and it goes back to work by Yann LeCun in the 1990s.

ReLU outputs are never negative, so their mean isn't 0. For a zz symmetric around 0, E[ReLU(z)2]E[\text{ReLU}(z)^2] is exactly half of E[z2]E[z^2]: the positive half survives, the negative half becomes 0. So each layer loses a factor of 2 in E[x2]E[x^2], and Var⁡(w)=2/fan-in\operatorname{Var}(w) = 2/\text{fan-in} puts it back. That's He initialisation (He and others, 2015).

These are statements about averages at the start of training. They don't promise the sizes stay right once the weights change. That's one reason normalisation layers, next, are so useful.

PyTorch's default, and when to change it

nn.Linear doesn't use He initialisation. It draws weights uniformly between ±1/fan-in\pm 1/\sqrt{\text{fan-in}}, which has a standard deviation of 1/3⋅fan-in1/\sqrt{3 \cdot \text{fan-in}}: about 0.41 of He's. That's fine for the course's 2-16-16-2 network. In 20 ReLU layers, it shrinks the signal by about 0.41 at each layer.

The biases keep the outputs from reaching 0, which hides the problem. But measure how much each unit's output differs from one delivery to the next. It falls from 0.32 at layer 1 to 0.00000001 at layer 20. Every delivery gets the same prediction, so the network can't learn.

PyTorch's default start in a deep ReLU network
def default_init_spread(depth: int = 20, width: int = 32, seed: int = 0) -> list[float]:
    """PyTorch's default nn.Linear start (uniform on ±1/√fan_in) in a deep ReLU network. Returns how
    much each hidden layer's outputs differ from one delivery to the next."""
    torch.manual_seed(seed)
    sizes = [2] + [width] * depth
    x, _ = standardised_training_set()
    spreads = []
    h = x
    with torch.inference_mode():
        for n_in, n_out in zip(sizes[:-1], sizes[1:]):
            h = torch.relu(nn.Linear(n_in, n_out)(h))  # default initialisation
            spreads.append(h.std(dim=0).mean().item())  # spread across deliveries, averaged over units
    return spreads

So for deep networks, set the initialisation yourself. nn.init has the standard ones:

The 20-layer network, with He initialisation
def make_deep_mlp(
    depth: int = 20,
    width: int = 32,
    activation: str = "relu",
    norm: str = "none",
    scale: float = 1.0,
) -> nn.Sequential:
    """2 inputs → `depth` hidden layers of `width` → 2 logits. Each hidden layer is
    Linear → (BatchNorm1d or LayerNorm) → activation."""
    sizes = [2] + [width] * depth + [2]
    layers: list[nn.Module] = []
    for i, (n_in, n_out) in enumerate(zip(sizes[:-1], sizes[1:])):
        linear = nn.Linear(n_in, n_out)
        # He (Kaiming) initialisation: normal with std = gain / √fan_in, where the gain is
        # √2 for ReLU, 5/3 for tanh and 1 for sigmoid. scale = 1 is the "right" size.
        nn.init.kaiming_normal_(linear.weight, nonlinearity=activation)
        nn.init.zeros_(linear.bias)
        with torch.no_grad():
            linear.weight.mul_(scale)  # 0.5 or 2 to see what goes wrong
        layers.append(linear)
        if i < depth:  # hidden layers only; the last Linear gives the logits
            if norm == "batch":
                layers.append(nn.BatchNorm1d(n_out))
            elif norm == "layer":
                layers.append(nn.LayerNorm(n_out))
            layers.append(ACTIVATIONS[activation]())
    return nn.Sequential(*layers)
  • nn.init.kaiming_normal_(w, nonlinearity="relu") draws from a normal distribution with standard deviation gain/fan-in\text{gain}/\sqrt{\text{fan-in}}. Pass "tanh" or "sigmoid" for those activations.
  • nn.init.xavier_normal_ (Glorot initialisation) uses the average of fan-in and fan-out instead. It is common with tanh.
  • The trailing underscore means "in place": it fills the tensor it's given.

Normalisation: reset the size at every layer

Initialisation gets the sizes right at the start. Training then changes the weights, and the sizes can drift. A sturdier fix measures the numbers as they flow and rescales them at every layer.

ML fundamentals standardises the inputs with feature scaling: subtract the mean, divide by the standard deviation. Normalisation layers do the same thing inside the network.

Batch normalisation standardises each unit over the batch. For each unit, take its values across the batch's examples, subtract their mean μ\mu and divide by their standard deviation σ\sigma. Then a learned scale γ\gamma and shift β\beta let the network choose its own size, if a different one helps:

y=γ x−μσ2+ϵ+βy = \gamma \, \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta

Here β\beta is a shift, unrelated to Adam's β1,β2\beta_1, \beta_2, and ϵ=10−5\epsilon = 10^{-5} avoids dividing by zero. γ\gamma starts at 1 and β\beta at 0.

Worked example

Batch norm on one unit, batch of 4

  1. One unit outputs 2, 2, 6 and 6 for the four examples in the batch. The mean is μ=4\mu = 4.

That last line is the point. Whatever size the weights give a layer's outputs, batch norm hands the next layer numbers with spread about 1. Set the figure to ReLU, ×2, batch norm: every layer's outputs now have a spread near 0.6, against 280,000 without it. In PyTorch, that network reaches 79.5% where the plain one got 78% with a loss of 43.5. At ×1, batch norm matches the plain network's 88%.

This is batch normalisation, or batch norm.

Layer normalisation standardises over the other direction: each example's own units. For one delivery, take its 32 values in a layer, subtract their mean and divide by their standard deviation. Then apply the learned scale and shift as before. For example, one delivery's four units output 1, 1, 5 and 5: mean 3, standard deviation 2, so the outputs become −1,−1,1,1-1, -1, 1, 1.

This is layer normalisation, or layer norm. It never looks at other examples, so it works the same with a batch of one, and the same in training and in testing.

Layer norm keeps the sizes steady in the figure too. But it trains badly on this problem: the PyTorch run stays at 53.5%. In a plain stack of 20 layers with only 2 inputs, it doesn't help. Its home is the transformer, where it sits inside blocks with residual connections (see the asides below). The lesson here is that a steady size is necessary for training, not enough on its own.

The catch: batch norm and evaluation

Batch norm needs a batch to average over. At test time you may predict one delivery at a time, and its result shouldn't depend on which other deliveries happen to share its batch. So batch norm keeps running averages of each unit's mean and variance during training, and uses those at test time.

That makes model.train() and model.eval() matter. In training mode, a batch of one delivery fails outright:

Batch norm needs model.eval() at test time
def batch_norm_needs_eval() -> tuple[str, list[float]]:
    """Batch norm in training mode needs a batch to average over. One delivery on its own fails;
    in evaluation mode it uses the running averages instead."""
    seed_everything(0)
    model = make_deep_mlp(depth=2, width=16, norm="batch")
    one = torch.tensor([[0.5, -1.0]])  # a single (standardised) delivery, shape (1, 2)
    try:
        model(one)  # still in training mode
        message = "no error"
    except ValueError as err:
        message = str(err)
    model.eval()  # batch norm now uses its running averages
    with torch.inference_mode():
        logits = model(one)
    return message, logits[0].tolist()
ValueError: Expected more than 1 value per channel when training, got input size torch.Size([1, 16])

With a batch of 2 or more, there is no error, which is worse: the predictions silently depend on the batch. The template's evaluate calls model.eval() for exactly this reason. In PyTorch, both layers slot into an nn.Sequential after each nn.Linear: nn.BatchNorm1d(32) or nn.LayerNorm(32), where 32 is the layer's width.

DigressionBatch norm vs layer norm: which way you averageSame formula, different axis. Batch norm averages down a column; layer norm averages across a row. · 2 min

Write a layer's outputs for a batch as a table: one row per example, one column per unit.

  • Batch norm standardises each column: one unit, across the batch's examples.
  • Layer norm standardises each row: one example, across its units.

Batch norm needs reasonably large batches, since a mean of 4 examples is a noisy estimate. It also needs the running averages and the train/eval switch. It is common in convolutional networks for images, where batches are large.

Layer norm doesn't care about batch size. That suits language models, where each example is a sequence of different length and batches can be small. Transformers use layer norm; see the Transformers course.

DigressionResidual connections: the other big fixAdd each layer's input to its output, and the gradient gets a path around every layer. · 2 min

A residual connection changes a layer from h↦f(h)\mathbf{h} \mapsto f(\mathbf{h}) to h↦h+f(h)\mathbf{h} \mapsto \mathbf{h} + f(\mathbf{h}). The layer only learns a correction to its input.

On the way back, the gradient flows through the sum's two branches. One goes through ff and may shrink. The other passes straight through, multiplied by 1. So even after 100 layers, part of the gradient reaches the start unshrunk.

Residual connections (from the ResNet paper, 2015) made networks with hundreds of layers trainable. With normalisation, they're the main reason deep networks work today. Transformers use both. The Convolutional networks course builds them properly.

Dead ReLUs

Lesson 2 noticed a couple of hidden units in the trained network that did nothing. Lesson 3 showed that a ReLU with a negative input passes back a gradient of 0. Put these together.

A ReLU unit whose sum zz is negative for every training example outputs 0 for every example. Its slope is 0 for every example, so its incoming weights get no gradient at all, and they never change again. The unit is dead. The first figure in this lesson counts them in each layer's label.

In the 20-layer network, the figure at the top shows many dead units even before training. A deep, narrow stack fed by only 2 inputs is prone to this. In the default network, what kills units is mostly big steps. One large update can push a unit's bias far negative, and then nothing brings it back. Train the default network with the template at three learning rates. Then count the units that are 0 for all 200 training deliveries, out of 16 per layer:

Learning rateDead in layer 1Dead in layer 2
0.01 (the default)32
0.0547
0.21314

At 0.2, 14 of the 16 units in layer 2 are dead. That's one reason the constant rate of 0.2 did badly in the last lesson.

Counting dead units, and leaky ReLU
@torch.inference_mode()
def dead_units(model: nn.Sequential, x: torch.Tensor) -> list[int]:
    """For each ReLU layer: how many units output 0 for every example in x."""
    counts = []
    h = x
    for layer in model:
        h = layer(h)
        if isinstance(layer, nn.ReLU):
            counts.append(int((h.amax(dim=0) <= 0).sum()))  # a unit is dead if its largest output is 0
    return counts


def dead_after_training(lr: float, epochs: int = 200) -> list[int]:
    """Train the default network with the template at learning rate lr; count its dead units."""
    seed_everything(0)
    train_loader, val_loader = rush_hour_loaders()
    model = make_mlp([2, 16, 16, 2])
    fit(model, train_loader, val_loader, epochs=epochs, lr=lr)
    x, _ = standardised_training_set()
    return dead_units(model, x)


leaky = nn.LeakyReLU(negative_slope=0.01)  # slope 0.01 below zero instead of 0, so no unit is ever fully off

The fixes are a sensible learning rate (with warm-up), and an activation whose slope is never exactly 0. Leaky ReLU outputs 0.01z0.01z for negative zz instead of 0. Its slope there is small but not zero, so a unit that has switched off still gets a small gradient and can recover. In PyTorch it's nn.LeakyReLU(negative_slope=0.01). GELU, from Lesson 1, has the same property.

Gradient clipping

Initialisation and normalisation keep sizes sensible on average. Now and then, one batch still produces a huge gradient. Some loss surfaces have cliffs: places where the loss drops sharply over a short distance, so the slope there is enormous. One step from such a slope can throw the weights far away and undo a lot of training.

02468101200.511.522.533.5w₁w₂plainclipped at 2
plain (0 steps)clipped at 2 (0 steps)× minimum
Step 0 of 30

Both start at (0.3, 3), on the high side of the cliff.

Plain gradient descent, learning rate 0.4. Darker is higher loss; the × marks the bottom.

A loss surface with a gentle bowl, bottom at (6, 1), and a cliff at w₁ = 2. Both paths use plain gradient descent with learning rate 0.4 from the same start. One clips the gradient's length first.

Things to notice:

  • For the first 8 steps, the two paths are identical. The gradient is shorter than the limit, so clipping does nothing.
  • At the cliff, the gradient's length jumps to about 20. Without clipping, that one step moves the weights 8 units, far past the bottom at (6,1)(6, 1). It takes the rest of the run to crawl back.
  • With clipping, the step is cut to length 0.4×2=0.80.4 \times 2 = 0.8, but it still points the same way. The path walks down the cliff and on towards the bottom.

This is gradient clipping: if the gradient is longer than a limit cc, scale it down to length cc, keeping its direction.

g←g⋅min⁡ ⁣(1,  c∥g∥)\mathbf{g} \leftarrow \mathbf{g} \cdot \min\!\left(1, \; \frac{c}{\lVert \mathbf{g} \rVert}\right)

∥g∥\lVert \mathbf{g} \rVert is the gradient's length, taken over every parameter of the network together, as if they were one long vector.

Worked example

Clipping one gradient

  1. The gradient is g=(30,40)\mathbf{g} = (30, 40). Its length is 302+402=2,500=50\sqrt{30^2 + 40^2} = \sqrt{2{,}500} = 50.

Predict first

The 20-layer ReLU network started at ×2 has gradients in the tens of thousands. If you clip them to length 1 every step, does it now train?

In PyTorch

torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm) does exactly this. It treats all the gradients as one long vector, scales them in place if they're too long, and returns the length they had before clipping. It goes in the template's loop between loss.backward(), which makes the gradients, and optimizer.step(), which uses them:

The template's train_one_epoch, plus clipping
def train_one_epoch_clipped(model, loader, loss_fn, optimizer, device, max_norm: float = 1.0) -> tuple[float, float, list[float]]:
    """The template's train_one_epoch with one added line: clip the gradients before the step.
    Also returns each step's gradient norm (before clipping), which is worth logging."""
    model.train()
    total_loss, correct, count, norms = 0.0, 0, 0, []
    for x, y in loader:
        x, y = x.to(device), y.to(device)
        optimizer.zero_grad()
        logits = model(x)
        loss = loss_fn(logits, y)
        loss.backward()
        norm = nn.utils.clip_grad_norm_(model.parameters(), max_norm=max_norm)  # new: after backward, before step
        optimizer.step()
        norms.append(norm.item())
        total_loss += loss.item() * len(y)
        correct += (logits.argmax(dim=1) == y).sum().item()
        count += len(y)
    return total_loss / count, correct / count, norms

That's the only change to the template. The norm it returns is the single most useful number to log while training: a sudden jump warns of trouble before the loss shows it. This is clip_grad_norm_. It computes the same length as torch.linalg.vector_norm would over all the gradients. Values of max_norm between 0.5 and 5 are common starting points; treat that as a rule of thumb.

Putting it together

Back to the 20-layer network. Every result below uses the template, 40 epochs, and keeps the epoch with the lowest validation loss:

SetupBest validation accuracyWhat went on
ReLU, He initialisation88%sizes stay sensible
ReLU, ×0.553.5%signal and gradients vanish
ReLU, ×278%outputs explode; validation loss 43.5
sigmoid, ×153.5%gradients vanish towards the input
tanh, ×177.5%learns a little; best at epoch 6
ReLU, ×1, batch norm88%as good as the right start
ReLU, ×2, batch norm79.5%batch norm rescues most of a bad start
ReLU, ×2, clipped at 153.5%clipping can't fix a bad start

The recipe for a deep network, in order:

  1. Use ReLU or GELU in hidden layers, not the sigmoid.
  2. Start the weights at the right size: kaiming_normal_ for ReLU. PyTorch's default is fine for shallow networks.
  3. Add normalisation if the network is deep: batch norm for big batches, layer norm in transformers. Remember model.eval().
  4. Clip the gradients as cheap insurance, and log the norm.
  5. Keep the learning rate sensible, with a warm-up, so units don't die.

Even with all of these, this plain 20-layer network does worse than the default 2-16-16-2 network, which reaches 95.5% at its best epoch. Depth only pays off with more data and residual connections. For 200 deliveries, two layers are plenty.

Common misconceptions

"Vanishing gradients mean the loss is near its minimum." Small gradients can mean you're at the bottom. They can also mean the signal died on the way back. In the ×0.5 network every gradient is about 10−810^{-8}, and the loss is stuck at 0.69, as bad as a coin toss.

"Starting all weights at one value is fine; training sorts it out." Units that start equal get equal gradients and stay equal. Starting every weight at 0.1 leaves each hidden layer with one distinct unit, copied 16 times.

"PyTorch's default initialisation is He initialisation." nn.Linear draws uniformly on ±1/fan-in\pm 1/\sqrt{\text{fan-in}}, about 0.41 times He's spread. Deep ReLU networks need kaiming_normal_.

"Batch norm works the same in training and testing." It uses the batch's statistics while training and its running averages while testing. Forget model.eval() and your predictions depend on the batch.

"Clipping clips each gradient number to a range." clip_grad_norm_ scales all the gradients together, which keeps their direction. Clipping each number separately (clip_grad_value_) changes the direction.

Recap

  • Through many layers, each multiplication either shrinks or grows the signal. Gradients that shrink to nothing (vanishing) or grow huge (exploding) stop a deep network training.
  • Start weights random, with standard deviation gain/fan-in\text{gain}/\sqrt{\text{fan-in}}: 2/fan-in\sqrt{2/\text{fan-in}} for ReLU (He initialisation). Random breaks the symmetry between units; the scale keeps sizes steady.
  • Batch norm standardises each unit over the batch, and layer norm standardises each example over its units. Both then apply a learned scale and shift. Batch norm needs model.eval() at test time.
  • A ReLU that is negative for every example gets no gradient and dies. Big learning rates kill many; leaky ReLU and GELU never fully switch off.
  • Gradient clipping caps the gradient's total length and keeps its direction. It guards against spikes but doesn't fix a bad start.
  • PyTorch names in this lesson: nn.init.kaiming_normal_, nn.init.xavier_normal_, nn.init.zeros_ and nn.init.constant_; nn.Linear's default initialisation; nn.BatchNorm1d and nn.LayerNorm; nn.LeakyReLU; torch.nn.utils.clip_grad_norm_.