Introduction
In our previous lessons, we have systematically constructed the Transformer encoder block by examining each of its constituent parts: multi-head self-attention for communication, the feed-forward network for computation, positional embeddings for order, and residual connections with layer normalization for stability. Now, with all the components on the table, we are ready to assemble them and trace the journey of an entire sequence of data as it flows through the block.
This lesson directly addresses the learning outcome of tracing a full forward pass. We will shift our perspective from processing a single token to processing a complete sequence in parallel using matrix operations—a key reason for the Transformer's efficiency on modern hardware. You will see precisely how an input matrix of embeddings is transformed step-by-step into an output matrix of richer, contextualized representations, ready for the next layer.
The Anatomy of an Encoder Block
Let's begin by orienting ourselves with the architecture. The diagram below shows a single Transformer encoder block, which will serve as our map for this lesson. Our goal is to trace the path of an input tensor from the bottom ("Inputs") to the output at the top.

The entire process operates on a matrix of input embeddings, which we'll call . This matrix has the shape , where is the length of the input sequence (e.g., number of tokens or image patches) and is the embedding dimension. As we established in previous lessons, this input is the sum of the token (or patch) embeddings and their corresponding positional embeddings.
From Single Token to Matrix Operations
In the last few lessons, we often looked at the computations for a single token . For example, the full set of equations for one token passing through a Pre-LN block looks like this:
-
Attention Sub-layer:
-
FFN Sub-layer:
While correct, this view obscures the parallel nature of the computation. The real power of the Transformer comes from performing these steps for all tokens simultaneously using matrix operations. The following resource provides the explicit equations for both the single-token and the full-matrix forward pass.
This excerpt from the Jurafsky and Martin textbook clearly contrasts the token-level and sequence-level computations.
First, review the section "Putting it all together" (Equations 8.26-8.31), which shows the sequence of operations for a single token i. This should be a familiar recap. Next, read the section "Putting it all together with the parallel input matrix X" (Equations 8.40-8.45). Focus on how each operation is now applied to the entire matrix X (or intermediate matrices T). This transition from vector-wise to matrix-wise operations is the core of this lesson.
A Step-by-Step Forward Pass with Matrices
Let's now trace the forward pass using the matrix formulation, which is how Transformers are implemented in practice. We'll follow the modern Pre-LayerNorm (x + Sublayer(LayerNorm(x))) convention.
Our input is the matrix of shape .
Step 1: The Attention Sub-layer
-
Pre-Normalization: We first apply Layer Normalization to the input matrix . The normalization is done independently for each row (each token's embedding vector).
The output still has the shape . -
Multi-Head Self-Attention: The normalized matrix is now fed into the multi-head attention mechanism.
- Q, K, V Projections: The Query, Key, and Value matrices are computed for all heads by multiplying with the respective weight matrices. For a single head, this is , , and . In an efficient implementation, these are computed for all heads at once.
- Scaled Dot-Product Attention: The attention output is calculated. This is the step where information is mixed across the sequence.
- Concatenation and Final Projection: The outputs from all attention heads are concatenated and passed through a final linear projection to produce the sub-layer's final output, which we'll call . This matrix also has the shape .
-
Residual Connection: The output of the attention sub-layer is added back to the original input .
This video from StatQuest provides a fantastic, animated walkthrough of the matrix math involved in steps 2 and 3.
The matrix math behind transformer neural networks, one step at a time!!!
This video visualizes the matrix multiplications for self-attention, which can make the process more concrete.
Watch how the Q, K, and V matrices are derived from the input matrix from this segment. Then, see the core scaled dot-product attention calculation, from the QK^T multiplication to the softmax, in the section from here. Finally, observe how the attention weights are applied to the V matrix and the residual connection is added from this point.
Step 2: The Feed-Forward Sub-layer
The process for the FFN sub-layer is analogous. We take the intermediate representation as its input.
-
Pre-Normalization: Again, we apply Layer Normalization.
The output has shape . -
Position-wise FFN: The normalized matrix is passed through the FFN. This is applied to each row (token representation) independently.
As we saw previously, the first linear layer expands the dimension from to (e.g., ), and the second contracts it back to . The output matrix has shape . -
Residual Connection: The output of the FFN is added to its input.
The matrix , of shape , is the final output of our encoder block. This output can now be passed as the input to the next identical encoder block in the stack.
The following resource provides a concise table summarizing this flow, along with a PyTorch implementation that brings these steps to life.
The Transformer Architecture: A Deep Dive - Imad Dabbura
This section "Assembling the Encoder Layer" ties everything together beautifully.
Read the full section Assembling the Encoder Layer. Pay close attention to the table that traces the tensor shapes through each step of the forward pass. Also, examine the EncoderLayer code. Note that it implements the Post-LN version (LN(x + sublayer(x))), but the commented-out lines show the Pre-LN alternative we've just discussed. Understanding both is valuable.
Visual and Mathematical Synthesis
To reinforce the entire sequence, this final video walks through the complete encoder pass, connecting the high-level concepts to the specific matrix shapes and operations we've discussed.
L-8 Transformer Encoder: Multi-Head Attention to FFN (Full Math)
This tutorial from Code With Aarohi provides a clear, step-by-step narration of the encoder's data flow.
Watch the explanation of the "Add & Norm" step from this segment, which emphasizes why the tensor shapes must remain consistent. Next, review the walk-through of the feed-forward network from here, showing how it processes the output of the attention layer. Finally, the short summary from this point recaps how the output of one encoder block becomes the input for the next, completing the picture of a stacked encoder.
The key architectural constraint that enables this entire process is that every sub-layer is designed to be residual: its input and output tensors have the exact same shape . This allows for the simple additive residual connections and the stacking of many identical layers to build a deep, powerful network.
Conclusion
In this lesson, we have consolidated our understanding of the Transformer's components by tracing a full forward pass through an encoder block. We moved from a token-by-token perspective to the more practical and efficient matrix-based computation that underpins the architecture.
Here are the key takeaways:
- Matrix-based Parallelism: The entire forward pass for a sequence is executed through a series of matrix multiplications, allowing all tokens to be processed in parallel.
- The Pre-LN Flow: A standard encoder block pass follows the sequence:
LayerNorm -> Multi-Head Attention -> Residual Add, followed byLayerNorm -> Feed-Forward Network -> Residual Add. - Shape Consistency: A critical design principle is that the output of every sub-layer must have the same shape as its input to enable residual connections and layer stacking.
- Division of Labor: The attention sub-layer mixes information across the sequence (inter-token communication), while the FFN sub-layer processes each token's representation independently (intra-token computation).
We have now fully dissected the Transformer encoder. The next step is to understand its counterpart: the decoder. In the next lesson, we will introduce masked self-attention, the crucial mechanism that allows a Transformer decoder to generate sequences autoregressively, one token at a time, without seeing into the future.