GNGiseldo Neo and Alana NeoBooks
Language Models with Python8 / 16

The Transformer Block Architecture

The “Transformer Block” is the fundamental atomic unit of architectures based on Large Language Models (LLMs). While the self-attention mechanism (discussed in previous chapters) is responsible for contextualizing tokens with one another, the Transformer Block is the structure that encapsulates this mechanism, processes the extracted information, and stabilizes the flow of gradients through the deep network.

A modern model (such as GPT-4, LLaMA, or Claude) is essentially a vertical stack of dozens or hundreds of these identical blocks.

8.1 Architecture Overview

The original Transformer combines an encoder, which builds bidirectional representations of the input, and a decoder, which generates the output autoregressively and queries the encoder through cross-attention. Models such as BERT mainly use the encoder stack; GPT-style models use only decoder blocks with a causal mask; translation and other sequence-to-sequence tasks often use both stacks.

Regardless of the family, the blocks reuse four ideas: attention to mix information across positions, feed-forward networks to transform each position, residual connections to preserve signal paths, and normalization to stabilize training.

The modern block architecture has diverged slightly from the original “Attention Is All You Need” paper (2017). The most significant change is the adoption of the Pre-Norm configuration (normalization before the sublayers) instead of Post-Norm, to ensure stability when training deep models.

The data flow within a single block follows this logical order:

  1. Input (xx)
  2. Normalization 1
  3. Self-attention
  4. Residual connection 1 (sum with the input)
  5. Normalization 2
  6. Feed-forward network (FFN)
  7. Residual connection 2 (sum with the previous result)

8.1.1 Data Flow Diagram (Pre-Norm)

Diagram

8.2 Residual Connections (Skip Connections)

Residual connections are vital for training deep neural networks. Mathematically, if we consider a sublayer (such as attention) as a function F(x)F(x), the output of the block is not just F(x)F(x), but rather:

Output=x+F(x)Output = x + F(x)

8.2.1 Technical Function

  1. Mitigation of the vanishing gradient: During backpropagation, the gradient can flow directly through the “skip” connection (xx) without being attenuated by the complex operations of the function F(x)F(x). This creates a “superhighway” for the gradient to flow from the last layers to the first.
  2. Information preservation: It allows the model to retain information from the original input if the transformation F(x)F(x) is unnecessary or destructive at that specific stage.

8.3 Normalization: LayerNorm vs. RMSNorm

Normalization is responsible for keeping the neuron values (activations) numerically stable, ensuring that they neither explode nor vanish.

8.3.1 Layer Normalization (LayerNorm)

The classic approach. For an input vector xx, LayerNorm computes the mean μ\mu and the variance σ2\sigma^2 over all dimensions of that specific vector (independent of the batch).

LayerNorm(x)=x−μσ2+ϵ⋅γ+β\text{LayerNorm}(x) = \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}} \cdot \gamma + \beta

Where γ\gamma and β\beta are learnable scale and shift (bias) parameters.

8.3.2 Root Mean Square Normalization (RMSNorm)

Adopted by modern models such as LLaMA, Gopher, and T5. RMSNorm is based on the hypothesis that recentering (subtracting the mean μ\mu) is not essential for convergence, only rescaling.

RMSNorm(x)=xRMS(x)2+ϵ⋅γ\text{RMSNorm}(x) = \frac{x}{\sqrt{\text{RMS}(x)^2 + \epsilon}} \cdot \gamma RMS(x)=1d∑i=1dxi2\text{RMS}(x) = \sqrt{\frac{1}{d} \sum_{i=1}^{d} x_i^2}

Advantages of RMSNorm: * Computational efficiency: It removes the mean computation, saving operations, which is significant in models with billions of parameters. * Simplicity: It maintains scale invariance without the complexity of mean shifting.

8.4 Feed-Forward Layers (FFN)

While attention aggregates information from different tokens (temporal/contextual mixing), the FFN processes this information for each token individually (feature processing). It is often described as the model’s “associative memory”.

8.4.1 Classic Structure (MLP)

A standard FFN consists of two linear transformations with a nonlinear activation function in the middle. It usually expands the hidden dimension (often by a factor of 4) and then projects it back.

FFN(x)=Activation(xW1+b1)W2+b2\text{FFN}(x) = \text{Activation}(x W_1 + b_1) W_2 + b_2

8.4.2 Modern Structure (SwiGLU / Gated Linear Units)

State-of-the-art models (such as PaLM and LLaMA) use “gated” variants, specifically SwiGLU.

In this configuration, there are three weight matrices instead of two, and the activation works as a soft logic gate:

SwiGLU(x)=(Swish(xWgate)⊗(xWin))Wout\text{SwiGLU}(x) = (\text{Swish}(x W_{gate}) \otimes (x W_{in})) W_{out}
  • WinW_{in}: Projects to the expanded dimension.
  • WgateW_{gate}: Creates an activation “mask”.
  • ⊗\otimes: Element-wise multiplication (Hadamard product).
  • WoutW_{out}: Projects back to the model dimension.

This allows finer control over which information flows through the network.

8.5 Reference Implementation (PyTorch)

Below is an implementation of a modern Transformer Block using Pre-Norm, RMSNorm, and a standard MLP structure for clarity.

import torch
import torch.nn as nn
import torch.nn.functional as F

class RMSNorm(nn.Module):
    def __init__(self, dim: int, eps: float = 1e-6):
        super().__init__()
        self.eps = eps
        # Learnable scale parameter (gamma)
        self.weight = nn.Parameter(torch.ones(dim))

    def forward(self, x):
        # Root Mean Square computation
        var = torch.mean(x ** 2, dim=-1, keepdim=True)
        x_norm = x * torch.rsqrt(var + self.eps)
        return self.weight * x_norm

class FeedForward(nn.Module):
    def __init__(self, dim: int, hidden_dim: int, dropout: float = 0.0):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(dim, hidden_dim),
            nn.GELU(), # Modern activation (Gaussian Error Linear Unit)
            nn.Linear(hidden_dim, dim),
            nn.Dropout(dropout)
        )

    def forward(self, x):
        return self.net(x)

class TransformerBlock(nn.Module):
    def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 4.0, dropout: float = 0.1):
        super().__init__()
        self.norm1 = RMSNorm(dim)
        self.attn = nn.MultiheadAttention(embed_dim=dim, num_heads=num_heads, batch_first=True)

        self.norm2 = RMSNorm(dim)
        hidden_dim = int(dim * mlp_ratio)
        self.ffn = FeedForward(dim, hidden_dim, dropout)

        self.dropout = nn.Dropout(dropout)

    def forward(self, x):
        # 1. Pre-Norm + Attention + Residual
        # Note: The input 'x' is preserved for the sum (skip connection)
        norm_x = self.norm1(x)
        attn_out, _ = self.attn(norm_x, norm_x, norm_x)
        x = x + self.dropout(attn_out)

        # 2. Pre-Norm + FFN + Residual
        # Note: The updated 'x' is preserved again
        norm_x = self.norm2(x)
        ffn_out = self.ffn(norm_x)
        x = x + self.dropout(ffn_out)

        return x

# Instantiation example
# Model dimension: 512, Heads: 8
block = TransformerBlock(dim=512, num_heads=8)
dummy_input = torch.randn(1, 10, 512) # Batch=1, Seq=10, Dim=512
output = block(dummy_input)
print(f"Output shape: {output.shape}")

8.6 Chapter Summary

The effectiveness of the Transformer Block lies in the careful orchestration of its components:

  1. RMSNorm (Pre-Norm): Stabilizes the input before the heavy processing.
  2. Attention: Mixes information across tokens.
  3. FFN: Processes and “reasons” about the mixed information, expanding the dimensionality to capture complex nonlinear relationships.
  4. Residuals: Ensure the original signal is never lost and that gradients flow healthily during training.

8.7 The Contract of a Well-Implemented Block

The block must preserve the shape (B,T,dmodel)(B,T,d_{model}), respect the causal mask, and accept different sequence lengths. Dropout must act only in training mode, and the normalization parameters must follow the device and numeric type of the rest of the model.

In the pre-norm scheme, we can write y=x+Attention⁡(Norm⁡(x))y=x+\operatorname{Attention}(\operatorname{Norm}(x)) and z=y+FFN⁡(Norm⁡(y))z=y+\operatorname{FFN}(\operatorname{Norm}(y)). This notation makes the two residual paths explicit and helps check whether the implementation added each output to the correct input.

Suggested unit test

Pass a random tensor, check the shape and the absence of NaN, run output.sum().backward(), and verify that the main weights received gradients. Then apply a mask and confirm that changing a future token does not change the output of earlier positions.

8.7.1 The Tensor Crossing the Block

The external shape remains (B,T,dmodel)(B,T,d_{model}). Attention mixes information across tokens; the FFN transforms the features of each token independently, using weights shared across positions. Stacking blocks preserves these dimensions but produces progressively more contextualized representations.

8.8 Modern Choices Inside the Block

Early Transformers used LayerNorm and feed-forward networks with ReLU. Modern blocks frequently combine RMSNorm, a pre-norm organization, and gated activations such as SwiGLU. These choices do not change the general function of the block, but they affect stability, capacity, and cost.

RMSNorm normalizes by the quadratic magnitude without subtracting the mean:

RMSNorm⁡(x)=g⊙x1d∑ixi2+ϵ,\operatorname{RMSNorm}(x)=g\odot\frac{x}{\sqrt{\frac{1}{d}\sum_i x_i^2+\epsilon}},

where gg is a learned vector. It has fewer operations than LayerNorm, although the practical advantage depends on the kernel and the hardware.

In SwiGLU, two projections follow distinct paths; one is transformed by the SiLU function and acts as a gate on the other:

SwiGLU⁡(x)=(SiLU⁡(xWg)⊙xWu)Wd.\operatorname{SwiGLU}(x)=\bigl(\operatorname{SiLU}(xW_g)\odot xW_u\bigr)W_d.

The mechanism makes it possible to control which features move forward. Since there are additional projections, the intermediate width is usually chosen to balance parameters with a conventional FFN.

8.8.1 Why Residual Connections Help

In y=x+F(x)y=x+F(x), the derivative contains an identity path in addition to the derivative of FF. This gives the gradient a direct route through many layers and allows a sublayer to learn only the necessary correction. The residual connection does not prevent every optimization problem, but it reduces the dependence on perfectly transforming the signal at every step.

Normalizations are not interchangeable

BatchNorm uses batch statistics and is sensitive to batch size. LayerNorm and RMSNorm operate over the features of each token, a behavior better suited to sequences of varying lengths and batches.