Overview

3 A blueprint to modern transformers

```html

This chapter introduces the internal anatomy of modern Transformer language models and explains why understanding that anatomy matters for re-architecting them. It frames the main practical challenge: attention consumes memory through a growing key-value cache during generation, while the MLP block dominates parameters and compute. Using these bottlenecks as a guide, the chapter builds the foundation for choosing the right optimization technique for each component in later chapters.

The discussion begins with DistilGPT2 as a classic Transformer reference point. Its structure is unpacked from the input embeddings through stacked Transformer blocks to the output head, showing how token embeddings and positional embeddings are combined, how data flows through repeated attention and MLP submodules, and how the final logits are produced. Attention is presented as the mechanism for contextualization, using query, key, and value projections across multiple heads, while the MLP is described as the knowledge-processing stage that expands representations, applies a nonlinearity, and contracts them back. The chapter also distinguishes model depth, meaning the number of blocks, from width, meaning the size of the internal MLP expansion, because both dimensions affect performance and optimization choices.

The second half turns to modern Transformers, especially the Llama family, to show how current architectures address the limits of the classic design. It explains Grouped-Query Attention as a memory-saving evolution of multi-head attention, where multiple query heads share fewer key-value projections, making longer context windows feasible without the full cache cost of traditional attention. It also presents GLU-based MLPs, where a learned gate modulates the content pathway before contraction, replacing the fixed behavior of a simple activation and improving how information is filtered. The chapter closes by connecting model structure to optimization strategy, mapping specific components to techniques such as depth pruning, width pruning, attention bypass, and behavior-driven pruning, so the reader can choose the right surgical modification for each part of a model.

```
Embedding creation process in the input block. The wte layer converts each text token into a Token Embedding based on its meaning. The wpe layer generates a Positional Embedding based on the token's position in the sequence. The combination of both produces a vector that contains both semantic and positional information.
Embedding creation process in the input block. The wte layer converts each text token into a Token Embedding based on its meaning. The wpe layer generates a Positional Embedding based on the token's position in the sequence. The combination of both produces a vector that contains both semantic and positional information.
Anatomy of DistilGPT2. On the left, the general architecture is shown: data flows from the Embeddings layer, passes through the stack of six Transformer Blocks, and ends at the output layer. On the right, a "zoom" into one of those blocks reveals a LayerNorm → GPT2Attention → LayerNorm → GPT2MLP flow, where each module processes the information before passing it to the next.
Anatomy of DistilGPT2. On the left, the general architecture is shown: data flows from the Embeddings layer, passes through the stack of six Transformer Blocks, and ends at the output layer. On the right, a "zoom" into one of those blocks reveals a LayerNorm → GPT2Attention → LayerNorm → GPT2MLP flow, where each module processes the information before passing it to the next.
Multi-Head Attention architecture. The input embedding (768 dimensions) is divided into 12 specialized attention heads, each processing 64 dimensions in parallel. Each head focuses on different contextual relationships, before concatenating their outputs into a context-aware embedding that incorporates information from the entire sequence. Each head focuses on different contextual relationships (labels are illustrative; real specialization emerges from training and is not directly interpretable).
Multi-Head Attention architecture. The input embedding (768 dimensions) is divided into 12 specialized attention heads, each processing 64 dimensions in parallel. Each head focuses on different contextual relationships, before concatenating their outputs into a context-aware embedding that incorporates information from the entire sequence. Each head focuses on different contextual relationships (labels are illustrative; real specialization emerges from training and is not directly interpretable).
Attention mechanism for the token "spring." The Query (Q) from "spring" compares with the Keys (K) of all tokens through dot product operations. The resulting scores, after softmax normalization, determine what fraction of each Value (V) contributes to create the enriched embedding.
Attention mechanism for the token "spring." The Query (Q) from "spring" compares with the Keys (K) of all tokens through dot product operations. The resulting scores, after softmax normalization, determine what fraction of each Value (V) contributes to create the enriched embedding.
Attention mechanisms and memory optimization strategies. Multi-Head Attention (MHA) maintains independent K,V pairs for each Q head — one pair per processed token, forming a growing cache. Grouped-Query Attention (GQA) groups Q heads to share K,V pairs (here 6 Q heads in 3 groups, each sharing one K,V pair per token). Multi-Query Attention (MQA) compresses to the extreme: all Q heads share a single K,V pair per token.
Attention mechanisms and memory optimization strategies. Multi-Head Attention (MHA) maintains independent K,V pairs for each Q head — one pair per processed token, forming a growing cache. Grouped-Query Attention (GQA) groups Q heads to share K,V pairs (here 6 Q heads in 3 groups, each sharing one K,V pair per token). Multi-Query Attention (MQA) compresses to the extreme: all Q heads share a single K,V pair per token.
KV Cache memory growth during sequential token generation. The graph compares cache growth for three attention mechanisms using the example from the text: a 6-layer model with 12 attention heads. The solid line shows MHA storing 12 KV pairs per token, requiring 1,152 vectors to cache 8 tokens. GQA 4:1 with 3 KV pairs per token can process 32 tokens with the same 1,152-vector budget (+300%), while MQA with a single KV pair can process 96 tokens (+1100%).
KV Cache memory growth during sequential token generation. The graph compares cache growth for three attention mechanisms using the example from the text: a 6-layer model with 12 attention heads. The solid line shows MHA storing 12 KV pairs per token, requiring 1,152 vectors to cache 8 tokens. GQA 4:1 with 3 KV pairs per token can process 32 tokens with the same 1,152-vector budget (+300%), while MQA with a single KV pair can process 96 tokens (+1100%).
Comparison of the "shapes" of different models. The narrow column represents the embedding dimension, the main box shows the model's depth (its height, proportional to the number of blocks) and its processing width (its width, proportional to the size of the MLP expansion).
Comparison of the "shapes" of different models. The narrow column represents the embedding dimension, the main box shows the model's depth (its height, proportional to the number of blocks) and its processing width (its width, proportional to the size of the MLP expansion).
Processing flow in MLP Modules: classic vs. GLU. While the classic MLP follows a simple expansion-activation-contraction sequence, GLU uses two parallel projections: one up_proj that transforms the content and another gate_proj that creates a dynamic filter.
Processing flow in MLP Modules: classic vs. GLU. While the classic MLP follows a simple expansion-activation-contraction sequence, GLU uses two parallel projections: one up_proj that transforms the content and another gate_proj that creates a dynamic filter.
How activations flow between layers. Each neuron applies its static weights (learned during training) to the input values and passes the result through an activation function (SiLU). The output values, the activations, vary in intensity: high values propagate strong signals, while low values suppress information. These activations become the inputs for the next layer, creating the continuous flow of information through the model.
How activations flow between layers. Each neuron applies its static weights (learned during training) to the input values and passes the result through an activation function (SiLU). The output values, the activations, vary in intensity: high values propagate strong signals, while low values suppress information. These activations become the inputs for the next layer, creating the continuous flow of information through the model.

Summary

  • Transformers consist of repeating blocks, each containing two core modules: an attention module for contextualizing information and an MLP module for processing knowledge.
  • The two fundamental dimensions for rearchitecting a model are its depth (the number of stacked Transformer blocks) and its width (the size of the expansion within the MLP modules).
  • Modern architectures like Llama evolved from the classical design by incorporating key innovations such as Grouped-Query Attention (GQA) to reduce memory consumption and Gated Linear Units (GLU) to create more sophisticated MLP processing.
  • A model's static structure defines its components, while its dynamic behavior is revealed through its activations during inference.
  • By understanding the specific function of each component, you can strategically map techniques like Depth Pruning, Width Pruning, and Attention Bypass to the parts of the model where they will have the most impact.

FAQ

What is the main goal of Chapter 3 in Rearchitecting LLMs?The chapter explains the anatomy of modern Transformers so you can identify which model components to optimize later. It builds the foundation for choosing the right re-architecture technique for each project.
Why does the chapter start with DistilGPT2 instead of a modern model?DistilGPT2 is a lightweight classic Transformer that still preserves the essential structure of the original architecture. It is ideal for understanding the core components before moving to modern improvements.
What are the three main sections of a GPT-style model structure?The model structure can be divided into input, Transformer blocks, and output. The input creates embeddings, the blocks process information, and the output projects it to token predictions.
What role do the wte and wpe layers play in DistilGPT2?wte creates token embeddings from token IDs, while wpe adds positional information so the model knows where each token appears in the sequence. Together, they form the input embedding.
How does the attention mechanism differ from the MLP block?Attention contextualizes tokens by letting them interact with other tokens in the sequence, while the MLP transforms that contextualized information into richer representations using learned knowledge.
Why is the KV cache important, and why can it become a memory bottleneck?The KV cache stores Keys and Values from previous tokens so the model does not recompute them during generation. It grows with every token and can quickly consume GPU memory, especially with long contexts and many attention heads.
What is Grouped-Query Attention (GQA), and why is it useful?GQA reduces memory use by grouping query heads so they share fewer Key and Value heads. It keeps much of the quality of standard multi-head attention while allowing much longer context windows.
How does the classic MLP in DistilGPT2 work?It expands the hidden state from 768 to 3072 dimensions, applies GELU activation, then contracts back to 768 dimensions. The activation breaks linearity so the module can learn more complex patterns.
What is GLU, and how is it different from a classic MLP?GLU uses two parallel projections: one for content and one for a learned gate that controls what information passes through. This makes filtering dynamic and context-dependent, unlike the static activation in a classic MLP.
How does the chapter map model components to optimization techniques?Transformer blocks are linked to depth pruning, classic and GLU MLPs to width pruning, attention modules to attention bypass methods, and activations to fair or behavior-driven pruning. This map helps match each architecture part with the appropriate optimization strategy.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Rearchitecting LLMs Rearchitecting LLMs ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Rearchitecting LLMs Rearchitecting LLMs ebook for free