Concepts / Connecting Attention and Linear Layers in a Transformer Block

Connecting Attention and Linear Layers in a Transformer Block

A per-layer mean of absolute gradient values measures how strong the learning signal is at each layer. A larger number means that layer receives a bigger correction during training. A tiny number means the layer receives almost no useful correction.

  • Programming

Why Early Layers Need a Strong Signal

When a deep network trains poorly, one of the first questions to ask is whether the learning signal is reaching the early layers at all. Training works by sending a loss value backward through the network so that every weight can learn how to change. If that backward signal fades as it travels, the early layers hardly learn, no matter how long training runs.

This article takes a measurement approach. Instead of starting with the mathematics of the chain rule, you will run one small helper function on two versions of the same deep network: one built without shortcut connections and one built with them. The helper reports a single gradient number per layer, so the two runs can be compared directly. Keep one question in mind as you read: if the signal shrinks as it moves backward, which layer would you expect to show the smallest gradient?

Sending the Loss Backward

The helper is called print_gradients. It takes a model and a sample input, passes the input through the model to get an output, and compares that output with a target value. In this setup the target is simply zero, chosen for simplicity. The comparison is done with a mean squared error loss, which measures how far the output is from the target.

The step that matters most is calling loss.backward(). This asks PyTorch to compute the gradient for each layer's parameters. You never write the gradient formulas yourself. PyTorch does that work, which is why training deep networks is practical.

python
Notes on the code
  • The sample input passes through the model to produce an output.
  • The target is zero, so the loss measures how far the output is from zero.
  • loss.backward() fills in a gradient for each parameter; no formulas are written by hand.
  • The final loop reports one mean absolute gradient per weight-bearing layer.

Turning Each Layer's Gradients into One Number

A layer's weight matrix holds many values, and each one has its own gradient. A 3 by 3 weight matrix, for example, produces nine gradient values. Looking at nine numbers per layer is hard to compare across a deep network, so the helper reduces each layer to one summary value.

To make that summary, the helper takes the absolute value of every gradient in a layer and then averages those absolute values. The absolute value removes the sign, so positive and negative gradients both count toward the size of the signal. The result is one number per layer, which is easy to compare across the depth of the network.

Key point

A per-layer mean of absolute gradient values measures how strong the learning signal is at each layer. A larger number means that layer receives a bigger correction during training. A tiny number means the layer receives almost no useful correction.

Predicting the Baseline Pattern

What do you think happens?

For a deep network with no shortcut connections, read from the last layer back to the first. Do the per-layer gradient values stay steady, grow, or shrink?

  • They stay steady across all layers

  • They grow as you move toward the first layer

  • They shrink as the signal travels backward toward the first layer

Reveal answer
Answer:

They shrink as the signal travels backward toward the first layer.

The baseline run uses a model without shortcut connections. Reading its report from the last layer to the first, the gradients get smaller as the signal travels backward. Commit to your guess before reading the baseline report, because the comparison is more useful once you have tested your own expectation.

The Vanishing Gradient Problem Layer by Layer

The baseline run applies the helper to a model built without shortcut connections, using the same sample input. The report lists one mean gradient for each weight-bearing layer. Read from the last layer to the first, the pattern is consistent: the gradients get smaller as the signal travels backward. This is the phenomenon called the vanishing gradient problem.

Last layerlargest gradientMiddle layerssmaller gradientFirst layeralmost nothinggradient travels backwardgradient travels backward
Moving backward from the last layer toward the first, how does the mean absolute gradient change in a network without shortcut connections?

The problem matters because a layer whose gradient is tiny receives almost no useful correction during training. The early layers are where many useful features get built, so when they barely learn, the whole network suffers. The source ties this problem to deep networks without shortcut connections, and the baseline run is the case where it appears.

How a Shortcut Connection Creates a Second Route

A shortcut connection is a link that lets the signal bypass part of the network. Information and gradients can then travel across layers through a second route in addition to the usual layer path. The source describes shortcut connections as connections that allow gradients to flow more consistently across layers. In this course's model, the shortcut behavior is switched on with a single argument, use_shortcut=True, when the model is created.

Lossgradient starts hereLast layerLayer blockusual layer pathFirst layerreceives gradientbackwardusual pathusual pathshortcut route
With a shortcut connection, which path does the gradient take backward through the block, and how does that second path help?

Reading the Two Reports Side by Side

Once you have both versions, read the comparison in a fixed order. Start at the last layer, where the loss is computed, and follow the gradient backward to the first layer. Without shortcut connections, the gradient shrinks along that path. With shortcut connections, the last layer still carries the largest gradient, but the value stabilizes as you move toward the first layer instead of dropping away to almost nothing.

Last layerlargest gradientLast layerlargest gradientFirst layeralmost nothingFirst layerstabilized value
How does the pattern of gradient sizes across layers differ between a network without shortcuts and one with shortcuts?
QuestionWithout shortcut connectionsWith shortcut connections
Where is the largest gradient?At the last layerStill at the last layer
What happens moving toward the first layer?Gradients keep shrinkingValues stabilize instead of collapsing
What does the first layer receive?Almost no useful correctionNo longer a vanishingly small value

Reading the two per-layer reports in the same direction, from last layer to first

Worked example

Deciding whether gradients shrink toward the first layer

You have a per-layer gradient report for a deep model and want to know whether its gradients are shrinking toward the first layer.

  1. 1
    Fix the starting point

    Confirm the random starting weights were seeded, for example with torch.manual_seed(123), so the report is repeatable.

  2. 2
    Order the layers

    Read the report from the last layer, where the loss is computed, to the first layer.

  3. 3
    Compare neighboring values

    Check whether each layer's mean absolute gradient is smaller than the one before it in this backward direction.

  4. 4
    Check the first layer

    If the first layer's value is far smaller than the last layer's and keeps falling along the path, the gradients are shrinking toward the first layer, which is the vanishing gradient pattern.

  5. 5
    Compare with the shortcut run

    If the shortcut run's values stabilize toward the first layer instead of collapsing, the shortcut is helping the backward signal reach early layers.

Result

A report that shrinks steadily from the last layer to the first points to the vanishing gradient problem. A report that stays usable at the first layer shows the pattern that shortcut connections are meant to produce.

Keeping Comparisons Fair

A fair comparison fixes the random starting point and reads both reports in the same direction. The source seeds the random number generator with torch.manual_seed(123) before it creates the shortcut model. Seeding makes the random starting weights repeatable, so when two runs differ, you can attribute the difference to the architecture and not to the random starting point.

Best practice

Use the same sample input for both models, seed the random generator before creating each model, and always read the layers from last to first. Avoid drawing conclusions from a single number; compare the whole pattern across layers.

Mistakes When Reading Gradient Reports

  • Common mistake

    Reading the report from the first layer to the last

    Why it fails

    The source reads the comparison from the last layer, where the loss is computed, back to the first. Reading in the opposite direction makes the trend look reversed.

    Do this instead

    Start at the last layer and follow the gradient backward.

  • Common mistake

    Assuming the last layer's gradient is the one at risk

    Why it fails

    Even with shortcut connections, the last layer still has the largest gradient. The concern is the early layers, where values can shrink toward almost nothing.

    Do this instead

    Check the first layer's value relative to the last layer's value.

  • Common mistake

    Comparing two runs with different random starting weights

    Why it fails

    Differences may come from the random starting point rather than the architecture.

    Do this instead

    Seed the random generator before creating each model so the comparison isolates the shortcut connections.

  • Common mistake

    Treating the absolute-value average as a signed value

    Why it fails

    Taking the absolute value removes the sign, so the number reports the size of the signal, not its direction.

    Do this instead

    Interpret the per-layer number as signal strength only.

  • Common mistake

    Drawing a conclusion from one number instead of the whole pattern across layers

Applying the Check to Your Own Model

MEDIUM

You run the helper on a deep model and get a per-layer report. Read it from the last layer to the first. Describe whether the gradients are steady, growing, or shrinking toward the first layer, and state whether the early layers are receiving a usable learning signal.

Hints
  • Start at the last layer, where the loss is computed.
  • Ask whether each layer's mean absolute gradient is smaller than the one closer to the loss.
  • Compare the first layer's value with the last layer's value, and with the shortcut run if you have one.

Key Takeaways

  • Calling loss.backward() computes a gradient for each layer's parameters, and a per-layer mean of absolute gradient values makes layers easy to compare.
  • Without shortcut connections, gradients shrink as they move from the last layer to the first, which is the vanishing gradient problem.
  • With shortcut connections, the gradient at the first layer no longer collapses to a vanishingly small value, although the last layer still has the largest gradient.
  • A fair comparison fixes the random starting point, uses the same input, and reads both reports in the same direction from last layer to first.

Related concepts

More concepts starting with C