From Self-Attention to Multi-Head Attention: A Guide to Reading LLM Architecture Diagrams
This article explains how to read LLM architecture diagram collections by focusing on two core building blocks: self-attention and multi-head attention (MHA). It covers how Q/K/V projections, scaling, masks, and softmax normalization produce context-aware representations; how MHA runs multiple attention heads in parallel subspaces; the historical motivation of attention in encoder–decoder RNNs before the Transformer; and a practical workflow for reading architecture cards, including KV caching, grouped-query attention, sliding-window attention, and implementation checkpoints for masks, shapes, and numerical stability.
1. Why Architecture Diagram Collections Matter: Turning Abstract Computation Flows into Comparable Structures
Large language models are built from large numbers of repeated modules. Reading paper formulas alone often leads to a state of “understanding the concepts but being unable to assemble the whole.” The core value of an architecture diagram collection is that it converts abstract computation flows into comparable visual cards: how the input passes through the embedding layer, attention layers, feed-forward networks, residual connections, and normalization layers to finally produce an output distribution. Information commonly shown on these cards—attention modules, feed-forward expansion ratios, normalization placement, and positional encoding schemes—helps developers quickly build a mental model of a model’s structure.
Some visualization materials are even produced as physical cards, with reference objects placed next to them to convey size and proportion. The popularity of such materials shows that developers need not only formulas but also “structural maps.” However, one point must be emphasized: an architecture diagram is a tool for understanding, not proof of implementation correctness. A card can show how modules relate to each other, but it cannot replace checking tensor shapes, masking logic, numerical stability, and training dynamics. This article uses self-attention and multi-head attention as its main thread to explain the most critical module type in LLM architecture diagram collections, supplemented by historical context and engineering trade-offs.
2. Self-Attention: Letting Each Token Dynamically Review Visible Context
The fundamental question of self-attention is: how should the representation at a given position in a sequence make use of information from other positions? In the attention mechanism, each token produces a query vector Q, a key vector K, and a value vector V. Q expresses “what I am looking for,” K expresses “what cues I can offer,” and V is the content actually aggregated. During computation, Q is first scored for similarity against all visible K vectors; the scores are then scaled, masked, and normalized to obtain attention weights; finally, V is weighted-summed with these weights to form a new context-aware representation.
A simplified scaled dot-product self-attention flow looks like this:
Input representation X, shape [sequence length n, hidden dimension d]Q = X @ WqK = X @ WkV = X @ WvScores S = Q @ K^T / sqrt(d_k)If a visibility mask exists, set invisible positions to negative infinityAttention weights A = softmax(S, normalized over the last dimension)Context representation O = A @ VOutput = O @ Wo
The scaling factor mitigates the problem that as dimensionality grows, dot-product values become large and the softmax saturates. The mask determines “visibility”: in causal decoders, each position can only attend to itself and tokens to its left; during training, a causal mask enables parallel computation while preventing access to future information. When handling variable-length sequences, a padding mask blocks meaningless padding positions. The direct benefit of self-attention is that any two visible positions can interact over a short path, without the step-by-step information passing required by recurrent structures.
But self-attention is not free. Its score matrix scales quadratically with sequence length, so long sequences bring significant compute and memory pressure. For this reason, real architectures often include variants such as sliding-window attention and sparse attention, which trade a restricted visible range for efficiency. When understanding these variants, the key is still to return to three questions: who is visible, how the weights are normalized, and how the aggregated representation flows into subsequent layers.
3. Multi-Head Attention: Modeling Relationships in Parallel Across Multiple Subspaces
Multi-head attention (MHA) is the standard way self-attention is organized in Transformer-style architectures. Rather than running self-attention once, it runs multiple “heads” in parallel: each head has its own learned projections that map the input into a different subspace, computes self-attention independently, and then the outputs of all heads are concatenated and combined through an output projection to form a richer representation.
Illustrative pseudocode:
for i in 1..h:Q_i = X @ Wq_iK_i = X @ Wk_iV_i = X @ Wv_ihead_i = softmax(Q_i @ K_i^T / sqrt(d_head) + mask) @ V_iMHA output = concat(head_1, ..., head_h) @ Wo
Each head’s dimension is typically smaller than the total hidden dimension, keeping overall computation in the same order of magnitude as single-head attention, while the parallel heads provide multiple subspaces for modeling relationships. Different heads may attend to local collocations, long-range dependencies, positional patterns, or specific syntactic relations—but this division of labor should not be overly anthropomorphized. A more accurate understanding is that the multi-head structure increases the diversity of representation transformations, which are then fused by the output projection.
In architecture diagrams, MHA typically appears together with residual connections, normalization layers, and feed-forward networks. When reading a card, pay attention to the number of heads, per-head dimension, whether a causal mask is used, whether normalization is applied before or after attention, the feed-forward expansion ratio, and how positional encoding is injected. These details affect both training stability and inference efficiency. In practice, decoding commonly uses a key-value cache: the K/V of already generated tokens are cached, so a new token only needs to compute its own Q and interact with the cache. The more heads there are, the larger the cache, and the more pronounced the memory pressure of long-context inference becomes. To reduce this cost, the industry commonly adopts variants such as grouped-query attention and multi-query attention, which let multiple query heads share a small number of key-value heads; sliding-window attention reduces long-sequence overhead by limiting the visible range.
4. Historical Motivation: Attention Predates the Transformer
A common misconception is that “the Transformer came first, then attention.” In fact, the attention mechanism appeared earlier than the Transformer and multi-head attention. One of its direct contexts was the encoder–decoder recurrent neural network used for translation. In older systems, the encoder RNN read the source sentence token by token, compressing the information into a sequence of hidden states—or, in the simplest version, into a final state; the decoder RNN then generated the target sentence from this limited summary.
This approach works for short sentences and simple scenarios, but it has a clear bottleneck: a hidden state cannot store an unlimited amount of information or context. Once the information needed for the next output word resides at some other position in the input sentence, relying solely on a fixed summary tends to lose detail. The attention mechanism lets the decoder directly review the entire input sequence and assign weights to relevant positions when generating each target word, bypassing the constraint that “all information must be squeezed into one state.” Early attention mostly used additive scoring; later, scaled dot-product attention became widely adopted because of its efficient implementation. Self-attention further applied this idea of “direct review” within a sequence, enabling dynamic interaction between any positions; multi-head attention then extended that interaction across multiple representation subspaces.
5. How to Read an Architecture Diagram Collection: From Module Checklists to Data Flow
When facing an LLM architecture card, read it by data flow rather than by module names. First, look at how the input enters the model: how token embeddings, positional information, normalization, and dropout policies are combined. Second, examine the attention layer: number of heads, per-head dimension, masking pattern, whether grouped-query or sliding-window attention is used, and how the key-value cache structure is represented. Third, examine the feed-forward network: expansion ratio, activation function, and residual connection placement. Fourth, examine normalization: pre-norm or post-norm, and whether additional scaling is used. Fifth, examine the output layer: whether embedding weights are shared and how the output projection is organized.
Architecture diagram collections are well suited for horizontal comparison, but the conclusions of any comparison must be grounded in verifiable details. For example, two diagrams may both depict “multi-head attention,” yet differ completely in head count, dimensions, masking, and caching strategy; two diagrams may both depict “residual connections,” yet the normalization order may affect training stability. Reference objects on physical cards only help convey display size—they cannot serve as a basis for technical parameters.
6. Implementation and Debugging Checkpoints
When implementing self-attention and MHA, it is advisable to run unit checks with small random tensors: do the rows of the attention weights sum to 1 over visible positions; are the weights at future positions zero under a causal mask; are the shapes consistent after multi-head splitting and concatenation; does the scaling factor match the per-head dimension; and are extreme values handled before the softmax? During training, also monitor the relationship among sequence length, batch size, and memory usage. For long-sequence scenarios, prioritize evaluating general approaches such as sliding-window attention, key-value cache compression, or grouped-query attention.
7. Conclusion
LLM architecture diagram collections break complex models down into comparable structural units, and self-attention and multi-head attention are the most critical computational modules among them. Through Q/K/V projections, visibility masks, and weight normalization, self-attention lets each token dynamically aggregate context; MHA enhances representational capacity through multiple parallel subspaces, at the cost of cache and long-sequence overhead. Understanding the historical motivation of attention helps clarify why it can relieve the fixed-summary bottleneck of recurrent encoder–decoders. For developers, reading an architecture diagram is only the first step—true engineering capability shows up in mask correctness, numerical stability, caching strategy, and long-sequence trade-offs.
