The Transformer Architecture
local graph
Module 4 — The Transformer Architecture
Section titled “Module 4 — The Transformer Architecture”The transformer, as referenced in the previous modules, is the structural foundation of virtually every modern large language model, and understanding how it moves information through its layers is essential for almost every decision that follows in the development process. Introduced in 2017 as an alternative to recurrent networks for machine translation, the design has since become the default choice for language modeling at every meaningful scale (Vaswani et al., 2017). Its defining feature is the attention mechanism, which allows any position in a sequence to draw directly on any other position without passing information through intermediate time steps. This property changed what neural networks could learn from text and made it practical to train on sequences that were previously too long to handle efficiently. The discussion that follows walks through how attention works and how multiple attention operations cooperate within a single transformer block, before examining the feed-forward and normalization components that stabilize the signal as it moves deeper into the network.
The Attention Mechanism
Section titled “The Attention Mechanism”At the heart of the transformer sits a single operation that determines how information moves between positions in a sequence. Self-attention lets each token in a sequence look directly at every other token and combine the information it finds there into a new representation of itself. Before the transformer, language models depended on recurrent networks that processed tokens one at a time, passing a compressed summary forward through each step. That serial design made it difficult for information from distant parts of a sentence to influence later predictions, because the signal had to survive many intermediate transformations. Attention removes that dependency entirely by treating every pair of positions as directly connected, which is why the mechanism scaled so well when combined with modern parallel hardware (Vaswani et al., 2017).
0.05 0.15 0.50 0.25 0.05 ↓ ↓ ↓ ↓ ↓┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐│ The │ │ cat │ │ sat │ │ on │ │ mat │└─────┘ └─────┘ └─────┘ └─────┘ └─────┘ Weights sum to 1.0Figure 1-8. Attention Weights Across a Token Sequence
The mechanism works by producing projections of each token’s current representation. One projection represents what the token is looking for and is called the query. Another represents what the token offers to other positions searching the sequence and is called the key. A third holds the content the token will contribute if another position decides it is relevant, and is called the value. For any pair of positions, the model computes a similarity between one token’s query and another token’s key, typically through a dot product. These similarities are scaled and passed through a softmax function to produce a set of weights that sum to one, describing how much each position should contribute to the output at that query position. The weighted sum of value vectors across the sequence then becomes the updated representation for that position. A single attention operation therefore rewrites every token as a blend of information drawn from the whole sequence, with the blending proportions learned from data.
The scaling factor in scaled dot-product attention matters more than it first appears. As the dimension of the query and key vectors grows, the raw dot products tend to grow in magnitude as well. Without scaling, the softmax output concentrates almost entirely on a single position, producing vanishing gradients that stall training. Dividing by the square root of the key dimension keeps the softmax in a regime where gradients can still flow, which is a small adjustment with outsized consequences for stability (Vaswani et al., 2017).
Multi-Head Attention
Section titled “Multi-Head Attention”A single attention operation can only represent one kind of relationship at a time. A layer that used only one attention function would struggle to capture the many different forms of structure present in language, such as syntactic agreement between a verb and its subject or coreference between a pronoun and an earlier antecedent. Multi-head attention addresses this limitation by running several attention operations in parallel within the same layer. Each head has its own independently learned projections, which allow it to attend to a different aspect of the sequence than its neighbors, and each produces its own output vector for every position.
When the heads have all produced their output vectors, the results are concatenated and passed through a final linear projection that combines them into a single representation. In effect, the layer maintains several parallel conversations about the same sequence at once, each focused on a different form of dependency, and then merges their findings before moving on to the next computation. Empirical analysis of trained transformers has shown that different heads tend to specialize, with some tracking simple positional relationships and others focusing on longer-range syntactic or semantic dependencies. This specialization is not imposed by the designer but emerges during training, as the optimizer discovers that distributing work across heads produces lower loss than forcing them all into identical roles.
One important property of multi-head attention is that increasing the number of heads does not automatically increase the model’s total computation. In the standard design, the hidden dimension is split across the heads, so each head operates on a smaller slice of the representation. The model therefore gains the ability to represent multiple relationship types without paying a proportional cost in arithmetic, which is part of why the design scaled so gracefully as researchers built larger variants.
Feed-Forward Layers and Layer Normalization
Section titled “Feed-Forward Layers and Layer Normalization”Attention accounts for only half of what each transformer block does. After the attention sublayer produces its output, the result passes through a position-wise feed-forward network that processes each token independently of the others. The feed-forward sublayer is structurally simple. It consists of two linear transformations separated by a non-linear activation function, typically a variant of the rectified linear unit. The first projection expands the representation to a much higher dimensionality, often four times the hidden size, and the second projection compresses it back down to the original width. This expansion gives the model room to perform richer transformations on each token’s representation before returning it to the shared dimensionality used across the rest of the network. Formally, the sublayer is
where is the activation function.
Although it looks modest compared to attention, the feed-forward sublayer accounts for a substantial share of a transformer’s total parameters. Much of the factual and procedural knowledge a model acquires during training is stored in these matrices, and interpretability research has found that individual neurons in feed-forward layers often correspond to recognizable features or concepts that the network has learned to detect. Attention and feed-forward computation therefore play complementary roles, with attention gathering information from across the sequence and the feed-forward sublayer transforming each position’s representation in isolation.
Both sublayers are wrapped in residual connections, which add the sublayer’s input directly to its output before passing the result forward. This design was introduced for very deep convolutional networks to address the problem that gradients tend to weaken as they travel backward through many layers, which makes deep networks difficult to train (He et al., 2016). By providing a direct additive path from each layer’s input to its output, residual connections give gradients a shorter route to earlier layers and let each sublayer focus on producing a small refinement to its input instead of recomputing the representation from scratch. The residual path also gives rise to a useful conceptual picture of the transformer as a stack of incremental edits applied to a running representation, where each layer adds a correction based on what attention and feed-forward computation have revealed about the current state.
Wrapped around the residual structure in each sublayer is layer normalization, which rescales the values flowing through the network so that they maintain a stable distribution across positions and across training steps. Layer normalization computes the mean and variance of a representation across its feature dimensions for a single token at a time and uses those statistics to standardize the activations before applying learned scale and gain parameters (Ba et al., 2016). Because it treats each token independently, layer normalization is compatible with the variable sequence lengths and autoregressive generation that language models rely on, which is a property that batch normalization does not share. In practice, most modern transformers apply layer normalization before each sublayer instead of after, a configuration commonly called pre-norm that has been shown to improve training stability and reduce the need for a carefully tuned learning rate warmup schedule at scale (Xiong et al., 2020).
How Information Flows Through the Full Stack
Section titled “How Information Flows Through the Full Stack”A single transformer block is only one step in a longer computation. Modern language models stack dozens of identical blocks on top of one another, and the full behavior of the network emerges from how information is progressively transformed as it passes through that stack. At the input, each token is represented by its embedding vector together with a positional signal that tells the model where the token sits in the sequence. That initial representation then enters the first transformer block, which updates it based on the surrounding context. The output of the first block becomes the input to the second, and so on until the final block produces the representations that are used to predict the next token.
Although each block is structurally identical, research on the internal behavior of trained transformers suggests that different layers tend to perform qualitatively different kinds of work. Early layers often concentrate on building up local and syntactic features, combining nearby tokens into representations that reflect basic grammatical structure. Middle layers tend to operate on more abstract patterns, combining information from distant positions to build representations that reflect meaning across a clause or paragraph. Later layers refine these representations into a form that directly supports next-token prediction, sharpening the distribution over the vocabulary that the output head will eventually produce. This progression is not hardcoded, yet it emerges reliably in trained models because the residual structure encourages each block to produce incremental refinements to the running representation instead of overwriting it (Elhage et al., 2021).
A useful way to picture this is to think of the residual stream as a shared channel that every block reads from and writes to. Attention heads contribute information gathered from other positions, and feed-forward sublayers contribute transformations based on each position’s local content. The representation at any given depth is the accumulated sum of all the contributions that have been added to the stream up to that point. This view explains why residual connections are so important for learning. They preserve information across depth and make it possible for later layers to access features produced by much earlier ones, which supports the kind of compositional reasoning that language modeling depends on.
The final layer of the stack feeds into an output projection that maps each position’s representation into a vector of scores across the vocabulary. A softmax function then converts those scores into a probability distribution, which is the model’s prediction for the next token at that position. During training, the distribution is compared against the actual next token to produce a loss signal that flows backward through the full stack, adjusting every weight in every block to make good predictions more likely in the future. During inference, the distribution at the final position is sampled to select the next token, which is then appended to the sequence and fed back into the model to produce the next prediction.
flowchart TD
T1[The] & T2[cat] & T3[sat] & T4[on] --> E["Token embeddings<br/>token + position"]
E --> RS1(( ))
subgraph RS[Residual stream]
direction TB
RS1 --- RS2(( )) --- RS3(( )) --- RS4(( ))
end
RS1 -- read --> B1["Transformer block 1<br/>attention<br/>MLP"]
B1 -- write --> RS2
RS2 -- read --> B2["Transformer block 2<br/>attention<br/>MLP"]
B2 -- write --> RS3
RS3 -- read --> BN["Transformer block N<br/>attention<br/>MLP"]
BN -- write --> RS4
RS4 --> OP["Output projection<br/>unembed + layer norm"]
OP --> VD["Vocabulary distribution<br/>softmax over tokens"]
Figure 1-9. Transformer Stack with Residual Stream and Output Projection
Understanding information flow at this level makes many later design decisions intelligible. Questions about how deep a model should be, how wide each layer should be, how long a context window can reasonably grow, and how the model’s behavior changes as scale increases all connect back to the basic picture of a residual stream being progressively refined by stacked attention and feed-forward computation. The same picture also frames the failure modes that appear during training, where unstable gradients or poorly scaled activations can propagate through the stack and disrupt the orderly accumulation of information that successful models depend on.
The transformer achieves its power through a small set of carefully combined ideas that work together to move information efficiently between positions and across depth. Attention relates every token to every other token in a single step. Multi-head attention lets the model track several kinds of relationships at once. Feed-forward sublayers transform each position independently to refine what attention has gathered. Residual connections and layer normalization keep the signal stable as it flows through many layers of computation. The interaction of these ideas produces a network that can learn to model language with a level of fluency and breadth that earlier architectures could not approach.