/dev/posts/

Attention and transformers diagrams

Atlas of Stochastic Parrot Anatomy

Published:

Updated:

Some diagrams about attention in artificial neural networks and transformers architectures (as used in LLMs, vision transformers, VLMs).

Table of content

Introduction

These diagrams were made by reading the papers describing the models and often cross-referencing the source code. In many cases, I found that the paper give a really high-level overview of the design/architecture but lacks a really detailed description of the architecture: key elements are peppered in the experimental result (as prose), buried in appendices, or completely absent from the paper and must be painfully recovered from the reference implementation. In several instances, I thought I had understood the architecture properly only to find out by reading a follow-up paper that I had missed some important detail.

Useful references:

Note: diagram reuse

These diagrams are released as CC0 (“No Rights Reserved”). Feel free to reuse/adapt these diagrams with attribution.

These diagrams are made with Ditaa. You can get the source of each diagram by replacing the .png extension with .ditaa.

Ditaa diagrams are much easier to modify and tweak than the previous versions (hand crafted SVGs). Moreover the source files can be used as plain ASCII art diagrams, which might be useful in some contexts. I can't really align the texts as I would like though.

Transformer encoder/decoder

Diagram of the original Transformer model

The original (encoder-decoder) Transformer architecture features separate input text and output text which are processed by the decoder and encoder respectively. The decoder uses (unmasked) self-attention and produce final token embeddings. The encoder uses both self-attention (often masked/causal) and cross attention (to the output of the final encoder block).

Encoder-only Transformer LLMs

Diagram of BERT, 2018

This diagram depicts one the two pre-training tasks of BERT (Masked Language Model): some tokens are masked and the model must predict them.

Decoder-only Transformer LLMs

GPT-1

Diagram of GPT-1, 2017

In contrast to subsequent models, it uses Post-Norm (the LayerNorm is after the residual branch instead of being at the beginning of the residual branch).

GPT-2

Diagram of GPT-2, 2019
Diagram of causal Multi-Head Self-Attention (MHSA) as used in GPT-2

Llama 3

Diagram of Llama-3, 2024 (or for example DeepSeek LLM, 2024)

LLama 3 is an example of a typical “modern” LLM. Compared to GPT-2, it uses RMSNorm instead of LayerNorm, GQA instead of MHA, RoPE instead of learned positional encoding, a SiLU FFN, untied weights for token unembedding and does not use biases.

Attention

Attention operation

Diagram of dot-product attention

The d_t query vectors (Q_i) independently attend to the d_s key-value pairs (K_i, V_i). Each query vector (Q_i) is transformed into a weighted sum (and more precisely a convex combination) of the d_s value vectors (V_i). The attention weights W_{i,j} are related to the (dot-product) similarity between the Q_i queries and the K_j keys.

Diagram of dot-product attention with QK Norm

Dot-product attention with QK norm is actually cosine attention with a learnable temperature parameter.

SHA

Diagram of Single-Head Attention (SHA)

An typical attention module, includes projections for the query (Q), keys (K) and values (V) as well as an output projection.

MHA

Diagram of Multi-Head Attention (MHA)

With MHA, the attention is split between different attention heads. Each attention head can attend to different aspects of the tokens. A conventional design uses d_K = d_V = d_m / n_h.

Alternative (equivalent) diagram of Multi-Head Attention (MHA) using shared projections

The previous diagram represents per head QKV projections (Q_h = X_Q \, W_{Q,h} + b_{Q,h}). In practice, the QKV projections are usually implemented as a packed projection (Q = X_Q \, W_Q + b_Q). This second representation is especially useful in the context of LoRA: the low-rank factorization is done on the packed projection matrix W'_Q = W_Q + A_Q B_Q and not per-head in the original paper. See TensLoRA: Tensor Alternatives for low-rank adaptation for discussion on this topic.

Alternative (equivalent) diagram of Multi-Head Attention (MHA) with per-head output projection

MHA can (equivalently) be understood as having per head output projections. When used in a residual structure, each attention head output projection is added to the residual stream (y = x + \sum_h h(x) + b).

MQA

Diagram of Multi-Query Attention (MQA)

MQA reduces the size of the KV cache by using the same K and V for all attention heads.

GQA

Diagram of Group-Query Attention (GQA)

GQA is an intermediate between MHA (n_h=1) and MQA (n_g=1). The same K and V are shared between several attention heads.

MLA

Diagram of Multi-head Latent Attention (MLA)

In MLA, a shared compressed latent representation of both keys and values (C_{KV}) is stored in cache.

Diagram of optimized Multi-head Latent Attention (MLA) at inference time (absorbed matrices)

Through some linear algebra manipulations, we can do the operations in the compressed latent space.

Diagram of Multi-head Latent Attention (MLA) with RoPE

Query (Q) is decomposed into a content query (Q_C) and a positional one (Q_R). Same for the key. The cache stores the positional key K_R and the compressed (content) KV C_{KV}.

Sparse attention

Diagram of DeepSeek Sparse Attention (DSA) assuming a MHA base

DSA uses a indexer heads to select K positions (Top K) to attend to for a given position (sparse attention). Here DSA is instanciated on top of MHA for simplicity.

Diagram of DSA indexer with RoPE

The DSA paper instantiates DSA on top of MLA with RoPE. This diagram show how RoPE is integrated into the DSA indexer.

Self-attention

Diagram of causal Multi-Head Self-Attention (MHSA)

In self-attention, the source sequence and the target sequence are the same (and therefore d_t = d_s). For auto-regressive models (eg. LLMs), causal attention prevents a position from attending to future positions.

Deformable attention

Diagram of a (multi-head) Deformable attention module as found in Deformable DETR

Deformable DETR uses deformable attention. For each query, each attention heads attends to a restricted number (K) of sampling positions of a feature map. Both the sampling positions and the attention weights are learned projections of the query.

Diagram of a (multi-head) multi-scale Deformable attention module as found in Deformable DETR

Multi-scale Deformable attention module extends Deformable attention with support for multi-scale feature maps. For each query, each attention head attends to K sampling position per scale level.

Positional encoding

RPB

Diagram of Multi-head Attention (MHA) with (learned) Relative Position Bias (RPB) as found in Swin

In RPB, learned (or fixed) positional encoding is adding to the attention scores (before the softmax). These biases depend on the relative position of the tokens.

Q/K positional encoding

Diagram of positional encoding as found in DETR or Maskformer

In this scheme, (learned or fixed) positional encoding is added before Q and K projection. The same positional encoding is used for all attention heads and for all attention blocks. For self-attention, the same positional embeddings are used for Q and K projections.

RoPE

Diagram of Multi-head Attention (MHA) with Rotary Position Embeddings (RoPE)

When using RoPE, the positional information is typically included in the Q and K of each attention block. The positional information is encoded by applying 2D rotations to pairs of features at different frequencies.

FFN

This sections compares different FFN modules.

Monolithic FFN

A diagram of a FFN using GELU

A typical design uses d_h = 4 × d_x.

Diagram of a FFN using using SwiGLU (Swish Gated Linear Unit)

Mixture of Experts

Diagram of the FFN branch of Mixtral featuring routed experts (Top 2)

Mixtral replaces the FFN with sparsely-gated Mixture of Experts (MoE) where only two experts are active for each token (top 2).

Diagram of the FFN branch DeepSeekMoE featuring routed experts (Top K) plus shared (ungated) “experts”

DeepSeekMoE replaces the FFN with sparsely-gated Mixture of Experts (MoE) where only K experts out of N are active for each token (top K). In addition, they include a small number of “shard experts“ which are always active (and are not gated).

Note: Evolution of MoE design in following DeepSeek versions

In DeepSeek V2, the n_routed_experts routed experts are distributed on n_group groups/devices (with n_routed_experts/n_group experts each). A first selection of topk_group devices is done and a total of num_experts_per_tok experts is selected among the (topk_group×n_routed_experts/n_group) experts of the selected groups.

In DeepSeek V3, the gating uses a sigmoid activation function (normalized) instead of softmax.

In DeepSeek V4, the gating uses sqrt(softplus(.)).

Additional sub-blocks

PLE

Diagram of PLE (Per-Layer Embedding) sub-block as found in Gemma 4

Gemma 4 uses per-layer token embedding (PLE). It is included through an additional gated residual sub-block at the end of the transformer block. This (comparatively-)small-dimension per-layer token embedding is combined with a down projection of the global token embedding.

Speculative decoding

MTP

Diagram of the original Multi-token Prediction (MTP) scheme (2024)

The original MTP design forks several independent prediction heads before the last transformer block, predicting respectively tokens at position n+1, n+2, etc.

Diagram of the Multi-token Prediction (MTP) as used in DeepSeek V2

DeepSeek-V2 uses a chained MTP. The MTP prediction for token at position n+k uses the sampled tokens at positions n+1 to n+1-k.

EAGLE

Diagram of the EAGLE 3 (2025)

EAGLE-3 is an auto-regressive draft model. It takes as input the hidden features of the main model at three different levels and the token embeddings.

Perceiver

Vanilla Perceiver

Diagram of Perceiver, 2021

The Perceiver pattern can be used to handle large input sequences. It mitigates the quadratic complexity (wrt. sequence length N) of the self-attention mechanism (Q \, K^T). It introduces a sequence of learned latent vectors of size M \ll N which are used to extract information from the input through cross-attention. The resulting features are then used in a typical transformer. This reduces the complexity from \mathcal{O}(L \, N^2) to \mathcal{O}(M \, N + L \, M^2) . This process can be repeated several times either using the same input data (in order to extract more information from it) or additional data.

Perceiver IO

Diagram of Perceiver IO, 2021

Perceiver IO adds another cross-attention block (decoder) where output queries attend to the latent features. For simple tasks, the output queries can be learned. For other tasks, the output queries can contains features describing the “task”. It is usually better to omit the skip connection around the output cross-attention (as depicted here) in this case.

Perceiver Resampler

Diagram of Perceiver Resampler as found in Flamingo, 2021

The Perceiver Resampler uses a Perceiver architecture to downscale a high number of visual token (eg. coming from a video) into a fixed number (R) of visual tokens. R latent queries attend to the visual tokens and to themselves in a mixed self/cross-attention operation.

Visual Transformers

ViT

Diagram of ViT, 2020

The input image is partitioned into (non-overlapping) patches of P×P pixels. These patches are seen as a sequence of tokens: each patch is first projected in the model embedding space and the resulting patch tokens are processed using a classic transformer decoder model. A special learned class token ([CLS]) is inserted at the beginning of the sequence: the final features of this token are fed into a classification head.

DeiT

Diagram of DeiT, 2020

DeiT follows the architecture of ViT modified for the efficient distillation from a teacher model (eg. a ConvNet). An additional learned distillation token ([DIST]) is introduced. The student model is trained to match the teacher's predicted class through the distillation token (hard-label distillation), while simultaneously tracking the ground truth label through the class model.

At inference, the reference source code takes the mean of the logits of both heads.

Swin

Diagram of Swin transformer, 2021

Swin encourages some form of locality by restricting the attention within windows of 4×4 patches and by using a hierarchical structure (patch merging). It produces a pyramid of multi-scale feature maps.

MAE

Diagram of Masked Autoencoders (MAE), 2021

MAE (Masked autoencoders) uses self-supervised (pre-)training using an autoencoder network. The input image is severely degraded by masking a large proportion of patches. The masked patches are omitted from the sequence in the encoder and replaced by a learned masked token in the decoder. The network is trained must reconstruct the masked patches.

DINO

Diagram of DINO, 2021

DINO (Distillation with no labels) uses self-supervised learning method through self-distillation (for pre-training). A student network is trained to follow the output of a teacher model (distillation). The student and the teacher receive a different “part” (crop/transformation) of the same image and produce a probability distribution in a high-dimensional “prototype” space. The student is trained to produce prototype distribution similar to the the distribution produced by the teacher, even if has received a different view of the same image. This forces the network to extract semantic information out of the image. The trick is that the teacher network is derived from previous version of the student network (self-distillation).

Notice the usage of weight normalization (torch.nn.utils.weight_norm, torch.nn.utils.parametrizations.weight_norm) in the output layer.

DINOv2

Diagram of the DINOv2, 2021

DINOv2 use the same style of self-distillation training as DINO but adds an iBOT-style objective. An additional head (the iBOT head) with the same architecture is added to the network. The second student head processes images where some patch tokens have been masked: it must learn to reproduce the prototypes produced by the teacher network (with unmasked data) for these masked patches.

The teacher network is not displayed in this diagram.

Detection

DETR

Diagram of the DETR (2020)

DETR is a transformer-based detection head which can plugged to an existing visual backbone (such as a ViT or a CNN). Compared to other detection heads, it does not requires Non Max Suppression (NMS) on the resulting bounding boxes because it is trained to avoid creating duplicate detections.

Deformable DETR

Diagram of the Deformable DETR (single-scla)e (2020)

Deformable DETR but replaces the MHA in the encoder self-attention and the decoder cross-attention with multi-head Deformable attention modules. A variant, not depicted here use mutli-scale deformable attention (attending to multi-scale feature maps).

Some variants (not depicted here) mentioned in the paper are:

Segmentation

Maskformer

Overview of Maskformer (2021)

Maskformer uses a multi-scale backbone (/4, /8, /16, /32). The multi-scale feature maps are fed into a pixel decoder (FPN-like CNN) which produce final pixel embeddings as /4 scale. A transformer decoder uses fixed segment queries which attends to the low-resolution feature map (/32). The output of the transformer decoder is fed into two heads in order to produce two outputs. First, a classification head produces class prediction (classification) for each candidate mask/segment. Second, a MLP is used to produce per-mask embeddings for each segment query: the spatial masks (logits) are obtained by matching (dot product) the per-mask embeddings produced by the MLP with the pixel embeddings produced by the pixel decoder.

Diagram of Maskformer (2021)

This diagrams details the FPN-like pixel decoder.

VLM

CLIP

Diagram of CLIP, 2021

In CLIP (Contrastive Language–Image Pre-training), is trained using cross-modal contrastive learning. A visual model and a text models are jointly pre-trained using pairs (image, label) pairs. For each batch of B (image, label) pairs, the output of the visual encoder (a ViT or CNN) and the text encoder (an auto-regressive transformer decode model) are projected into a shared multi-modal embedding space. The model is trained to maximize the similarity of the representations of matching images and labels (and minimize the similarity of the representations of unmatched images and labels).

See SigLIP for an alternative (simpler) loss function.

BLIP-2

Diagram of the first stage BLIP-2, 2023

In the first stage of pre-training, the Qformer (Querying Transformer) learns to extract useful information from the output of frozen image decoder. The Qformer is initialized from an pre-trained LLM transformer (here BERT).

Image Text Matching Image Text Contrastive Learning Image Grounded Text Generation
Input (image, text) pairs (true and false matches) Batches of matching (image, text) pairs Batches of (image, text) pairs
Goal Binary classification (true/false ma tch) Similarity for matching (image, pairs) Maximize text probability
Self attention mask None Blocked between text and images Multimodal causal
Mask, query → query allowed allowed allowed
Mask, query → text allowed blocked blocked
Mask, text → query allowed blocked allowed
Mask, text → text allowed allowed causal
Diagram of the second stage BLIP-2 (when using a decoder LLM), 2023

In the second stage of pre-training, the Qformer is plugged into an existing frozen LLM and must learn to adapt the information from the visual encoder to visual tokens (soft visual prompt) understood by the LLM.

LLaVA

Diagram of the first stage LLaVA, 2023

LLaVA uses a simple linear layer for projecting the visual patches (coming from a frozen image encoder) into the LLM token feature space. In the first stage (pre-training), only this small layer is trained (both vision encoder and LLM are frozen). In the second stage (fine tuning), both the linear adapter and the LLM are fine-tuned while the visual encoder stay frozen.

Diagram of the first stage LLaVA 1.5, 2023

LLaVA 1.5 uses a (still very simple) FFN/MLP instead of the plain linear adapter.

PaliGemma has basically the same architecture as LLaVA 1.0 but use Prefix-LM masking: is allows non causal communication for the prefix (prompt and image tokens) but the suffix (text output) is causal. The pre-training process is different as well.

Decision models

CLM

Diagram of CLM (Contrastive Language Models) v0.1, 2026

CLM is basically CLIP applied to state/action pairs with a frozen LLM instead of the image encoder and a deep projection network. After some pre-training, it is used a zero-shot action classifier.

This diagram represent the first pre-training phase (contrastive pre-training). After, that the model is also trained to distinguish the correct action among a selection of possible choices (synthetic hard negatives).

Appendix, mathematical formulas

Attention

Unscaled dot-product attention formula:

\mathrm{Attention}(Q,K,V) = \mathrm{softmax} \left (Q \; K^T \right) V

Note: dot-product attention explained

This is best explained for a single query vector q \in \mathbb{R}^{d_k}.

We have a sequence of keys K_j \in \mathbb{R}^{d_k}, each associated with a value V_j \in \mathbb{R}^{d_v}. These (K_j, V_j) key-value pairs can be understood as as as an associative map (similar to a hash map, a tree map, etc.):

K_j \rightarrow V_j

The query vector q represents a search/lookup/query on this index and is said to attend to the (K_j, V_j) key value pairs. Similar to RAG systems, we want to find the “best” (K_j, V_j) pairs according to our query. In practice, each (K_j, V_j) is scored based on the similarity between the query q and each key K_j and the query q is transformed into a weighted sum (and more precisely a convex combination) of the value vectors V_i:

\mathrm{Attention}(q, K, V) = \sum_j w_j V_j \text{ with } w_{j} \ge 0 \text{ and } \sum_j w_{j} = 1

Similar to many RAG systems, the dot product similarity is used to measure the similarity between q and K_j:

q \cdot K_j = \sum_k q_k \, K_{j,k} \in \mathbb{R}

These scores (logits) are mapped to non-negative weights (e^{q \cdot K_j} \in \mathbb{R}^+) which are then normalized such that the final weights w_j sum to one, (\sum_j w_j = 1):

\begin{align*} w_j &= \frac{e^{q \cdot K_j}}{\sum_{j'} e^{q \cdot K_{j'}}} \\ w &= \mathrm{softmax}(q \, K^T) \end{align*}

The attention uses these w_j weights to compute a weighted sum (a convex combination) of the values V_j:

\mathrm{Attention}(q, K, V) = \sum_j w_j \, V_j = w \, V = \mathrm{softmax}(q \, K^T) V

In practice, we have several query vectors Q_i which independently attend to the (K_j, V_j) key-value pairs.

The attention formula can be extended for multiple queries:

\mathrm{Attention}(Q, K, V) = W \, V = \mathrm{softmax}(Q \, K^T) V

where W = \mathrm{softmax}(Q \, K^T) is the matrix of attention weights (a row stochastic matrix).

Example: dot-product attention

Lets take 3 key-value pairs (K_j, V_j) and a query q:

\begin{align*} \text{Keys} & & \text{Values} & \\ K_0 & = \begin{pmatrix} 1 & 0 & 0\end{pmatrix} & V_0 &= \begin{pmatrix} 5 & 5 & 0 & 0& 0 \end{pmatrix} \\ K_1 & = \begin{pmatrix} 0 & 1 & 0\end{pmatrix} & V_1 &= \begin{pmatrix} 0 & 0 & 1 & 0 & 0 \end{pmatrix} \\ K_3 & = \begin{pmatrix} 0 & 0 & -1 \end{pmatrix} & V_2 &= \begin{pmatrix} 0 & 0 & 0 & -1 & 1 \end{pmatrix} \\ \text{Query} & & \text{Result} & \\ q & = \begin{pmatrix}0.8 & 0.1 & 0.1\end{pmatrix} & \text{???} \end{align*}

The scores (logits) are computed as the dot product between q and each key K_j:

\begin{align*} q \cdot K_0 &= 0.8 & \text{for} && V_0 &= \begin{pmatrix} 5 & 5 & 0 & 0& 0 \end{pmatrix} \\ q \cdot K_1 &= 0.1 & \text{for} && V_1 &= \begin{pmatrix} 0 & 0 & 1 & 0 & 0 \end{pmatrix} \\ q \cdot K_1 &= -0.1 & \text{for} && V_2 &= \begin{pmatrix} 0 & 0 & 0 & -1 & 1 \end{pmatrix} \end{align*}

We take the exponential and normalize the values to obtain the attention weights:

\begin{align*} \text{Logits} && \text{Exp.} & & \text{Weights} & & \text{Values} & \\ 0.8 && 2.226 && 0.525 && V_0 &= \begin{pmatrix} 5 & 5 & 0 & 0& 0 \end{pmatrix} \\ 0.1 && 1.105 && 0.261 && V_1 &= \begin{pmatrix} 0 & 0 & 1 & 0 & 0 \end{pmatrix} \\ -0.1 && 0.905 && 0.214 && V_2 &= \begin{pmatrix} 0 & 0 & 0 & -1 & 1 \end{pmatrix} \\ \text{Sum:} && 4.236 && 1.000 && \end{align*}

The result is the weighted sum of the values:

\begin{align*} \text{Weights} &&&& &\text{Values} \\ 0.525 && × &&& \begin{pmatrix} 5 & 5 & 0 & 0& 0 \end{pmatrix} && = \begin{pmatrix}2.627 & 2.627 & 0 & 0. & 0. \end{pmatrix}\\ 0.261 && × &&& \begin{pmatrix} 0 & 0 & 1 & 0 & 0 \end{pmatrix} && = \begin{pmatrix}0. & 0. & 0.261 & 0. & 0. \end{pmatrix}\\ 0.214 && × &&& \begin{pmatrix} 0 & 0 & 0 & -1 & 1 \end{pmatrix} && = \begin{pmatrix}0. & 0. & 0. & -0.214 & 0.214\end{pmatrix}\\ \text{Sum} &&&&&&& = \begin{pmatrix}2.627 & 2.627 & 0.261 & -0.214 & 0.214\end{pmatrix} \end{align*}

When using multiple queries, each query Q_i independently attends to the (K_j, V_j).

For example for queries:

\begin{align*} Q_0 &= \begin{pmatrix}0.8 & 0.1 & 0.1\end{pmatrix} \\ Q_1 &= \begin{pmatrix}1. & 0. & 0. \end{pmatrix} \\ Q_2 &= \begin{pmatrix}0. & 1. & 0. \end{pmatrix} \\ Q_3 &= \begin{pmatrix}0. & 0. & 1. \end{pmatrix} \end{align*}

We have:

\begin{align*} Q & = \begin{pmatrix} Q_1 \\ Q_2 \\ Q_3 \\ Q_4 \end{pmatrix} = \begin{pmatrix} 0.8 & 0.1 & 0.1 \\ 1. & 0. & 0. \\ 0. & 1. & 0. \\ 0. & 0. & 1. \\ \end{pmatrix} \\ K &= \begin{pmatrix} K_1 \\ K_2 \\ K_3 \end{pmatrix} = \begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & -1 \\ \end{pmatrix} \\ V &= \begin{pmatrix} V_1 \\ V_2 \\ V_3 \end{pmatrix} = \begin{pmatrix} 5 & 5 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & -1 & 1 \\ \end{pmatrix} \end{align*}

Each row i of Q is a query Q_i. Each row j of K and V represent a key-value pair (K_j, V_j) (and therefore K and V have the same number of rows). Each query Q_i must have the same number of features (columns) as the queries K_j.

The attention logits are given by:

Q \, K^T = \begin{pmatrix} 0.8 & 0.1& -0.1 \\ 1. & 0. & 0. \\ 0. & 1. & 0. \\ 0. & 0. & -1. \\ \end{pmatrix}

The value Q_{i,j} at row i and column j represents the dot-product similarity between Q_i and K_j:

(Q \, K^T)_{i,j} = Q_i \cdot K_j = \sum_k Q_{i,k} \, K_{j,k}

The attention weights are obtained by normalizing each row:

W = \mathrm{softmax}(Q \, K^T) = \begin{pmatrix} 0.525 & 0.261 & 0.214 \\ 0.576 & 0.212 & 0.212 \\ 0.212 & 0.576 & 0.212 \\ 0.422 & 0.422 & 0.155 \\ \end{pmatrix}

Each row W_i contains the attention weights for a given query Q_i. Inside each row (i.e. for a given query Q_i), the weights sum to 1 (row stochastic matrix).

The attentions results are computed as weighted sums of the values V_j:

\mathrm{softmax}(Q \, K^T) \, V = \begin{pmatrix} 2.627 & 2.627 & 0.261 & -0.214 & 0.214 \\ 2.881 & 2.881 & 0.212 & -0.212 & 0.212 \\ 1.060 & 1.060 & 0.576 & -0.212 & 0.212 \\ 2.112 & 2.112 & 0.422 & -0.155 & 0.155 \\ \end{pmatrix}

Scaled dot-product attention formula:

\mathrm{Attention}(Q,K,V) = \mathrm{softmax} \left (\frac{Q \, K^T}{\sqrt{d_k}} \right) V

with d_k the size of the key (and query) vectors.

Dot-product attention with QK-Norm normalizes the query and key vectors using L2 norm:

\mathrm{softmax} \left ( \gamma \; \mathrm{Norm}_2(Q) \, \mathrm{Norm}_2(K)^T \right) V

where \mathrm{Norm}_2(x) = x / \| x \|_2 normalizes the row vectors (using L2 norm) and \gamma is a learnable parameter (inverse of temperature).

Generalized attention formula:

\mathrm{Attention}(Q,K,V) = \mathrm{softmax} \left (\mathrm{sim}(Q, K) \right) V

where \mathrm{sim}(Q, K) gives a matrix of scores/logits (\mathrm{sim}(q, k)) for each (query, key) pair.

Masked attention

In causal (masked) attention, a given position can attend only to itself and to the previous positions. I cannot attend to future positions. Mathematically, this masking operation can be seen as setting the logits of future position to - \infty,

\mathrm{Attention}(Q,K,V) = \mathrm{softmax} \left( \frac{Q \, K^T}{\sqrt{d_k}} + \mathrm{Mask} \right) V

with

\mathrm{Mask} = \begin{pmatrix} 0 & - \infty & - \infty & - \infty & - \infty \\ 0 & 0 & - \infty & - \infty & - \infty \\ 0 & 0 & 0 & - \infty & - \infty \\ 0 & 0 & 0 & 0 & - \infty \\ 0 & 0 & 0 & 0 & 0 \\ \end{pmatrix}

producing a (lower) triangular attention matrix after the \mathrm{softmax}:

\mathrm{softmax} \left( \frac{Q \, K^T}{\sqrt{d_k}} + \mathrm{Mask} \right) = \begin{pmatrix} a_{1,1} & 0 & 0 & 0 & 0 \\ a_{2,1} & a_{2,2} & 0 & 0 & 0 \\ a_{3,1} & a_{3,2} & a_{3,3} & 0 & 0 \\ a_{4,1} & a_{4,2} & a_{4,3} & a_{4,4} & 0 \\ a_{5,1} & a_{5,2} & a_{5,3} & a_{5,4} & a_{5,5} \\ \end{pmatrix}

SHA

A single-head attention layer (SHA) projects the input feature vectors (X_q, X_v, X_v) into the key and value spaces:

\begin{align*} Q & = X_Q \, W_Q + b_Q \\ K & = X_K \, W_K + b_K \\ V & = X_V \, W_V + b_V \\ A &= \mathrm{softmax} \left( \frac{Q \, K^T}{\sqrt{d_k}} + \mathrm{Mask} \right) \\ H &= A \, V \\ Y &= H \, W_O + b_O \end{align*}

MHA

A multi-head attention layer (MHA) is composed of several independent attention heads, each projecting the input feature vectors (X_q, X_v, X_v) into key and value spaces:

\begin{align*} Q_h & = X_Q \, W_{Q,h} + b_{Q,h} \\ K_h & = X_K \, W_{K,h} + b_{K,h} \\ V_h & = X_V \, W_{V,h} + b_{V,h} \\ A_h &= \mathrm{softmax} \left( \frac{Q_h \, K_h^T}{\sqrt{d_k}} + \mathrm{Mask} \right) \\ H_h &= A_h \, V_h \end{align*}

and the output of the different heads are concatenated before the output projection,

\begin{align*} H & = \mathrm{Concat}(H_1, \ldots) \\ Y &= H \, W_O + b_O \end{align*}

MLA

In Multi-head Latent Attention (MLA), the inputs are (down) projected (compressed) into a latent space:

\begin{align*} C_{Q} &= X_{Q} \, W_{DQ} \\ C_{KV} &= X_{KV} \, W_{DKV} \end{align*}

These projections are then up projected (decompressed) using different parameters per attention head:

\begin{align*} Q_h &= C_{Q} \, W_{UQ,h} \\ K_h &= C_{KV} \, W_{UK,h} \\ V_h &= C_{KV} \, W_{UV,h} \end{align*}

and the rest is as usual:

\begin{align*} H_h &= A_h \, V_h \\ H & = \mathrm{Concat}(H_1, \ldots) \\ Y &= H \, W_O \end{align*}

But instead of caching the keys and values (K and V), we only need to cache the down-projections (C).

Note: optimization, Q/K absorption

At inference, we can absorb the Q and K up-projections (W_{UQ} and W_{UK}).

The attention logits (S) are computed as

\begin{align*} Q_h \, K_h^T &= C_Q \, W_{UQ,h} \, (C_{KV} \, W_{UK,h})^T \\ &= C_Q \, (W_{UQ,h} \, W_{UK,h}^T) \, C_{KV}^T \\ &= C_Q \, W_{UQ/UK,h} \, C_{KV}^T \end{align*}

So when computing the attention for a query q, we have:

q_,h \, K_,h^T = c_Q \, W_{UQ/UK,h} \, C_{KV}^T

We can compute c'_{Q,h} = c_Q \, W_{UQ/UK} and then compute c'_{Q,h} \, C_{KV}^T without forming the keys (K_h explicitly).

Note: optimization, V/O absorption

At inference, we can absorb the V up projections with the output projection as well (W_{UV,h} and W_{O,h}.)

We have:

\begin{align*} Y &= H \, W_O = \sum_{h} \overbrace{H_h \, W_{O,h}}^{Y_h} \\ H_h &= A_h \, V_h \\ V_h &= C_{KV} \, W_{UV,h} \\ \end{align*}

Which gives:

\begin{align*} Y_h &= A_h \, C_{KV} \, (W_{UV,h} \, W_{O,h}) \\ &= A_h \, C_{KV} \, W_{UV/O,h} \end{align*}

We can apply the attention in the latent space (A_h \, C_{KV}) and project this with W_{UV/O,h}.

Deformable attention

Multi-head Deformable attention module:

\mathrm{DeformAttention}(q, p, X) = \sum_{m=1}^M \, \left[ \sum_{k=1}^K A_{m,k} \, X(p + \delta p_{m,k}) W_{V,m} \right] W_{\text{out},m}

with

\begin{align*} \delta p_{m,k} = q \, W_{\text{P},m,k} \\ A_{m,k} = \frac{ q \, W_{\text{A},m,k} }{ \sum_{k'} q W_{ \text{A},m,k'} } \\ \end{align*}

Residual

Residual blocks have the following structure:

y = x + f(x)

where

Token embedding

The tokens embedding layer projects tokens into the model feature space. Assuming that the input tokens X are represented using one-hot encoding, this can be written as:

\mathrm{Embedding}(X) = X \, E

In GPT-2, positional encoding is done at this stage by adding a learned positional biases:

\mathrm{Embedding}(X) = X \, E + P

Token unembedding projects back the final token representations into the vocabulary space, producing token logits. GPT-2 uses tied unembedding i.e. the unembedding parameters are shared with the embedding parameters:

\mathrm{Unembedding}(X) = X \, E^T

Recent LLM use untied unmebedding i.e. U is a different set of learned parameters.

\mathrm{Unembedding}(X) = X \, U

Transformer blocks

A GPT-2 transformer block is:

\begin{align*} X' & = X + \mathrm{LayerNorm}(\mathrm{Attention}(X)) \\ Y & = X' + \mathrm{LayerNorm}(\mathrm{FFN}(X')) \end{align*}

A more recent transformer block is typically:

\begin{align*} X' & = X + \mathrm{Attention}(\mathrm{RMSNorm}(X)) \\ Y & = X' + \mathrm{FFN}(\mathrm{RMSNorm}(X')) \end{align*}

A MoE architecture:

\begin{align*} X' & = X + \mathrm{Attention}(\mathrm{RMSNorm}(X)) \\ Y & = X' + \mathrm{MoE}(\mathrm{RMSNorm}(X')) \end{align*}

Position encoding

In relative position bias (RPB), as attention bias B is added to the attention scores (pre-softmax) where the values of B depends on the relative positions of the tokens:

Q = \mathrm{softmax} \left (\frac{Q \; K^T}{\sqrt{d_k}} + B \right) \; V

In Swin, we have 2D RPB:

B_{i,j} = \hat{B}_{h_i - h_j + W - 1, w_i - w_j + H -1}

where h_i and w_i are the coordinates associated with visual token i and \hat{B} is a (2 \, H -1, 2 \, W -1) matrix.

Alternatively, RPB can use a fixed function for \hat{B} instead of learned biases.

FFN

In GPT-2, the FFN is:

y = \left[ \mathrm{GELU}(x \, W_\text{up} + b_\text{up}) \right] \, W_\text{down} + b_\text{down}

Recent LLMs typically use a FFN module based on SwiGLU (Swish Gated Linear Unit) and without bias:

y = \left[ \mathrm{SiLU} ( x \, W_\text{gate} ) \odot ( x \, W_\text{up} ) \right] W_\text{down}

Gemma models use GEGLU (Gaussian Error Gated Linear Unit) FFN:

y = \left[ \mathrm{GELU} ( x \, W_\text{gate} ) \odot ( x \, W_\text{up} ) \right] W_\text{down}

Normalization

LayerNorm:

y_f = \gamma_f \, \frac{ x_f - \mathbb{E}_i[ x_f ] }{\sqrt{\text{Var}[x_f] + \epsilon}} + \beta_f

where f is a feature index.

GroupNorm:

y_f = \gamma_f \, \frac{ x_f - \mathbb{E}_{i \in G(f)}[ x_f ] }{\sqrt{\text{Var}[x_f] + \epsilon}} + \beta_f

RMSNorm:

y_f = \gamma_f \, \frac{x_f}{\sqrt{\mathbb{E}_f[ x_f^2 ] + \epsilon}}

In LLMs/Transformers, each position is normalized independently.

In convolutional networks (CNNs), normalization is done across the whole image:

y_{h,w,c} = \gamma_c \, \frac{ x_c - \mathbb{E}_{h,w,c}[ x_{h,w,c} ] }{\sqrt{\text{Var}[x_{h,w,c}] + \epsilon}} + \beta_c

where h,w are pixel indices and c is the channel index.

Appendix, diagram notations

Learned parameters are represented at the right of each layer:

Examples:

Tensor dimensions are indicated in parentheses:

Ohter hyper-parameters:

References

Transformers:

Autoregressive LLMs:

Vision models:

Detection:

Segmentation:

Decision models:

Misc: