Shortcut Connections

Next Build
Let's discuss the concept behind shortcut connections, also known as skip connections or residual connections. Originally, shortcut connections were proposed to address deep networks in computer vision (especially residual networks) to mitigate the vanishing gradient problem. The vanishing gradient problem refers to the gradients (which guide weight updates during training) gradually becoming smaller as they are backpropagated through the layers, making it difficult to effectively train early layers.

Figure 4.12 Comparison of a deep neural network with five layers, left: without skip connections, right: with skip connections.
Figure 4.12 shows that a shortcut connection creates an alternative, shorter path for gradients to flow through the network by skipping one or more layers, which is achieved by adding the output of one layer to the output of a later layer. This is why these connections are also called skip connections. They play a key role in maintaining gradient flow during backpropagation in training.
A skip connection involves adding the input of a layer to its output, effectively creating an alternative path that bypasses certain layers. The gradient represents the mean absolute gradient of each layer.
This code implements a deep neural network with five layers, each consisting of a linear layer and a GELU activation function. In the forward pass, we iteratively pass the input through the layers, and if the self.use_shortcut attribute is set to True, we optionally add a shortcut connection.
Let's use this code to initialize a neural network without shortcut connections. Each layer will be initialized to accept an example with three input values and return three output values. The last layer returns a single output value:
This code specifies a loss function that calculates how close the model output is to a user-specified target (here, the target value is 0 for simplicity). Then, when loss.backward() is called, PyTorch calculates the loss gradients for each layer in the model. We can iterate over the weight parameters via model.named_parameters(). Suppose we have a 3 × 3 weight parameter matrix for a given layer. In that case, the layer will have 3 × 3 gradient values, and we print the mean absolute gradient of these 3 × 3 gradient values to obtain a single gradient value per layer, making it easier to compare gradients across layers.
In short, the .backward() method is a convenient method in PyTorch that computes the loss gradients, which is essential for model training, without requiring us to implement the gradient calculation mathematics ourselves, thus making it more accessible to work with deep neural networks.
The output of the print_gradients function shows that as we progress from the last layer (layers.4) to the first layer (layers.0), the gradients become smaller and smaller, a phenomenon known as the vanishing gradient problem.
Now let's instantiate a model with skip connections and see how it performs:
The gradients of the last layer (layers.4) are still larger than those of other layers. However, as we progress toward the first layer (layers.0), the gradient values stabilize and do not shrink to a negligible value.
In summary, shortcut connections are important for overcoming the limitations caused by the vanishing gradient problem in deep neural networks. Skip connections are a core building block of very large models (such as LLMs) and will help facilitate more effective training by ensuring consistent gradient flow between layers when training the GPT model in the next chapter.
Next, we will connect all the concepts covered previously (layer normalization, GELU activation, FeedForward, and shortcut connections) together to form a TransformerBlock, which is the final building block we need to code the GPT architecture.
Transformer Block
Now, let's implement the transformer block, a fundamental building block of GPT and other LLM architectures.
This block is repeated over a dozen times in the 124-million-parameter GPT-2 architecture, combining several concepts we covered earlier: multi-head attention, layer normalization, dropout, feedforward layers, and GELU activation. Later, we will connect this TransformerBlock with the rest of the GPT architecture.

Figure 4.13 An example of a Transformer Block. The input tokens have been embedded into 768-dimensional vectors. Each row corresponds to the vector representation of a token. The output of the Transformer Block is vectors of the same dimension as the input, which can be fed into subsequent layers of the LLM.
Figure 4.13 shows a Transformer block that combines multiple components, including a Masked Multi-head Attention Module and the FeedForward module we implemented earlier. When the Transformer block processes an input sequence, each element in the sequence (e.g., a word or subword token) is represented by a fixed-size vector (in this case, 768 dimensions). The operations inside the Transformer block, including the Multi-head Attention and FeedForward layers, are designed to transform these vectors in a way that preserves their dimensions.
The idea is that the self-attention mechanism in the Masked Multi-head Attention Module identifies and analyzes relationships between elements in the input sequence. In contrast, the FeedForward Network modifies the data at each position independently. This combination not only enables the input to be understood and processed more nuancedly but also enhances the model's overall ability to handle complex data patterns.
The given code defines a TransformerBlock class in PyTorch, which contains a multi-head attention mechanism (MultiHeadAttention) and a feedforward network (FeedForward), both configured based on a provided configuration dictionary (cfg), such as GPTCONFIG124M.
Layer normalization (LayerNorm) is applied before these two components, while dropout is applied after them to regularize the model and prevent overfitting. This is also known as Pre-LayerNorm. Older architectures, such as the original transformer model, apply layer normalization after self-attention and the feedforward network, which is known as Post-LayerNorm and often leads to worse training dynamics.
The class also implements FeedForward, with a shortcut connection after each component that adds the block's input to its output. This key feature helps gradient flow during training and improves the learning of deep models.
Using the GPTCONFIG124M dictionary we defined earlier, let's instantiate a Transformer Block and give it some example data:
As we can see, the Transformer Block maintains the input dimensions in its output, indicating that the Transformer Block architecture processes data sequences throughout the network without changing their shape.
In the Transformer Block architecture, the preservation of shape is not accidental but a key aspect of its design. This design allows it to be effectively applied to various sequence-to-sequence tasks, where each output vector directly corresponds to an input vector, maintaining a one-to-one relationship. However, the output is a context vector that encapsulates information from the entire input sequence. This means that although the physical dimensions of the sequence (length and feature size) remain unchanged as they pass through the Transformer Block, the content of each output vector is re-encoded to incorporate contextual information from the entire input sequence.

Figure 4.14 The building blocks needed to construct the GPT architecture. The black checkmarks indicate the modules we have completed.