Introduction
In our last lesson, we put in place the crucial scaffolding that makes deep Transformers trainable: residual connections and layer normalization. We saw how these components, particularly when arranged in the modern Pre-LN configuration, create a stable "gradient highway" that allows information to flow smoothly through dozens of layers. With the attention mechanism handling inter-token communication and the Add & Norm layers ensuring stability, we are now ready to add the final core component of a Transformer block.
This lesson focuses on the Position-wise Feed-Forward Network (FFN). You will learn why this component is non-negotiable for a Transformer's expressive power and how its simple architecture belies a critical role. We will explore its position-wise nature, the rationale for its dimensional expansion, and the evolution of its activation functions from ReLU to GELU and SiLU. Finally, we will delve into a powerful interpretation of the FFN as a distributed key-value memory, revealing how Transformers store and retrieve factual and linguistic knowledge.
The Need for a "Thinking" Layer
The self-attention mechanism is exceptional at gathering and mixing contextual information from across a sequence. It allows each token's representation to be influenced by every other token. However, at its core, self-attention computes a weighted average of the value vectors. This is a linear operation with respect to the values. Stacking many such layers without an intermediate non-linear transformation would severely limit the model's capacity; the entire stack would be equivalent to a single, more complex linear transformation. To learn the complex, non-linear functions required for tasks like language understanding or image recognition, the model needs more.
The FFN provides this essential non-linearity. It acts as a "thinking" or "computation" layer. After the attention sublayer has gathered the relevant context for each token, the FFN processes each of these context-aware representations individually to produce a richer, more abstract feature vector.
In a short clip from his "Let's build GPT" lecture, Andrej Karpathy provides a great analogy for this division of labor.
Let's build GPT: from scratch, in code, spelled out.
This video offers a simple but powerful intuition for the FFN's role.
Watch from this segment, where he explains that after tokens "communicate" via self-attention, they need a component to individually "think" on the data they've gathered. This is precisely the role of the FFN.
The Architecture of a Position-wise FFN
The FFN's architecture is remarkably simple, consisting of two linear layers with a non-linear activation function in between. This structure follows an "expand-and-contract" pattern.
For an input vector representing a single token, the FFN computation is:
Let's break this down:
-
Expansion (First Linear Layer): The input vector is projected by a weight matrix and a bias . Crucially, the intermediate dimension is typically much larger than . The standard in the original Transformer paper was an expansion factor of 4, so . This projects the token's representation into a higher-dimensional space. The intuition is that in this larger space, features that are entangled in the smaller
d_modelspace can be more easily separated and manipulated. -
Non-linear Activation: An activation function like ReLU, GELU, or SiLU is applied element-wise to the expanded representation. This is the only source of non-linearity in this sub-block and is what prevents the two linear layers from collapsing into one.
-
Contraction (Second Linear Layer): The activated hidden representation is projected back down to the original dimension by a second weight matrix and bias . The output has the same shape as the input, which is necessary for the residual connection that follows.
A defining characteristic of this network is that it is position-wise. This means the exact same weight matrices () and biases () are applied independently to each token representation in the sequence. This enables massive parallelization on GPUs, as the computation for all tokens can be performed simultaneously.
For a detailed walkthrough of this architecture and its motivation, the following reading is excellent.
Feed-Forward Networks in Transformers: Architecture, Parameters ...
This article from Michael Brenndoerfer's "Language AI Handbook" provides a clear and comprehensive explanation of the FFN.
Please read the following three sections: Start with The Position-Wise Feed-Forward Network to solidify the motivation. Continue with The Two-Layer Architecture section, which breaks down the formula. Finally, read The Hidden Dimension Expansion to understand the rationale behind the 4x expansion factor.
The Evolution of Activation Functions
The original Transformer used the Rectified Linear Unit (ReLU) as its activation function. While computationally efficient, ReLU has a significant drawback known as the "dead ReLU problem," where neurons can stop learning if their inputs are consistently negative.
Modern Transformers have moved to smoother, non-monotonic activation functions that mitigate this issue and often lead to more stable training and slightly better performance. The two most common are:
- GELU (Gaussian Error Linear Unit): Used in models like BERT and its variants. It gates the input by its value's cumulative distribution function (CDF) under a standard Gaussian distribution, creating a smooth approximation of ReLU.
- SiLU (Sigmoid Linear Unit), or Swish: Used in many modern decoders like LLaMA and Mistral. It gates the input by passing it through a sigmoid function.
Both GELU and SiLU avoid the hard zeroing of ReLU, allowing gradients to flow even for negative inputs and preventing neuron death.
FFN Activation Functions: ReLU, GELU, and SiLU for Transformer ...
This resource dives into the mathematics and intuition behind the three main activation functions used in Transformer FFNs.
To understand their evolution and properties, please read the following sections: Start with ReLU: The Original Choice to understand the baseline and its key weakness. Next, read GELU: The Smooth Alternative to learn about the probabilistic gating used in BERT-like models. Finally, read the section on SiLU/Swish: The Modern Standard to see the activation function common in today's most powerful language models.
An Algorithmic Interpretation: FFNs as Key-Value Memories
While the FFN's primary role is to add non-linear expressive power, a fascinating line of research has revealed a deeper, more algorithmic function. The FFN can be interpreted as a massive, distributed key-value memory. This perspective helps explain how transformers store and access factual and semantic knowledge learned from the training data.
In a talk discussing this research, Mor Geva explains the analogy:
- Keys: The rows of the first weight matrix, , can be seen as "keys." Each key is a vector that is trained to detect a specific textual or semantic pattern. The dot product of an input token's representation with a key measures how well that token matches the key's pattern.
- Values: The columns of the second weight matrix, , act as "values." Each value is a vector that, when added to the residual stream, tends to promote certain tokens in the final output vocabulary.
- Retrieval: The non-linear activation acts as a gating mechanism. If an input strongly matches a key (resulting in a high dot-product value), the activation is high, and the corresponding value vector is given a large weight in the final output. If the match is weak, the value's contribution is suppressed.
The output of the FFN is thus a linear combination of all value vectors, weighted by how strongly their corresponding keys were matched by the input.
This video provides a fantastic overview of this concept.
Mor Geva: Transformer Feed Forward Layers are Key-Value Memories, and Build Predictions
This seminar by Mor Geva provides a deep dive into interpreting FFNs as key-value memories, moving beyond a simple "non-linearity" explanation.
Please watch the following segments to grasp this powerful interpretation: First, watch the segment from this point where the key-value memory analogy is introduced. Pay close attention to the diagram illustrating how the input x is multiplied by the k matrix to produce coefficients that weight the v matrix columns. Next, see how these keys learn to capture patterns, from shallow to semantic, in the segment from here. Finally, understand what the 'values' represent by watching from this section, which shows that a value vector often corresponds to a distribution over next-tokens that follow the pattern detected by its key.
This interpretation reveals that the FFN is not just a generic function approximator; it's a structured system where the model learns to store specific linguistic and factual knowledge (e.g., "the capital of France is Paris") in specific "memory cells" (key-value pairs) and retrieves that knowledge based on input context.
The Complete Encoder Block
With the FFN understood, we can now visualize the complete Transformer encoder block, connecting back to our previous lesson. The image below shows a standard Pre-LN encoder architecture, which is used in models like Vision Transformers (ViT).

As you can trace in the diagram, an input sequence of embeddings flows through the block as follows:
- Layer Normalization
- Multi-Head Self-Attention (communication)
- Residual Addition
- Layer Normalization
- MLP / Feed-Forward Network (computation/thinking)
- Residual Addition
This sequence of communication -> computation, stabilized by Norm -> Sublayer -> Add, is the fundamental repeating unit of a Transformer.
Conclusion
This lesson has introduced the final essential component of a Transformer block, the Position-wise Feed-Forward Network. We have moved from a surface-level understanding of it as a "non-linearity" to a much deeper appreciation of its architecture and function.
Here are the key takeaways:
- Essential Non-linearity: The FFN provides the non-linear transformation capability that the linear self-attention mechanism lacks, enabling the model to approximate complex functions.
- Expand-and-Contract Architecture: The FFN uses two linear layers to first expand the token representation into a higher-dimensional space (typically 4x) and then contract it back, with a non-linear activation (like GELU or SiLU) in between.
- Position-wise Operation: The FFN processes each token's representation independently using shared weights, a design that enables massive parallelization and defines its role as an intra-token computation engine.
- Key-Value Memory Interpretation: The FFN can be understood as a sophisticated key-value memory system, where it learns to store factual and linguistic patterns in its weights and retrieve them based on the input context.
We have now examined all the individual parts of a Transformer encoder block: self-attention, positional embeddings, layer normalization, residual connections, and the feed-forward network. In our next lesson, we will put all these pieces together and trace a full forward pass of an input sequence through a complete encoder block, solidifying your understanding of how these components interact to transform input into meaningful representations.