1. Variable-size Sequence Representation¶
Consider a sequence of $n$ words: $(x_1,\ldots,x_n)$, where $x_i \in \mathbb{R}^d$ is a unique vector that defines the word (e.g., a one-hot encoding of the vocabulary).
For instance, I don't like avocado thank broken up into tokens gives the following 6 tokens ["I", "do", "n't", "like", "avocado", "thank"]
How should we predict the next word?
1.1. Written language is a sequence of words¶
A sentence is clearly a sequence of words
I don't like avocado thank
Our task is to predict the next word
I don't like avocado thank => you
However, sometimes, one can undertand the meaning of a sentence from just its words without their relative ordering (bag of words):
{avocado, like, thank, I, do, n't}
Statistically, using just the set of words above, we can even predict the next word: "you"
Just learning a set of words rather than their relative order in the sequence is statistically easier, since the absence of order requires fewer samples. Consider the above example. How many more training examples are needed if we have to discern between:
I don't like avocado thank
avocado I don't like thank
I avocado don't like thank
Is there a neural network that, for any $i,j$, it allows $x_i$ and $x_j$ to interact on the same neural network layer without the need for padding?
MLPs need fixed-size inputs
- One potential solution for variable-size inputs is padding
- We make the MLP take as many tokens as we can, then pad the unused tokens with zeros
CNNs focus on local dependencies
- Consider a 1D convolutional neural network
- CNNs use (local) convolutional filters that each process a small window of nearby tokens, learning representations locally.
- For example, a 1D CNN might use a filter of size 3, meaning each convolution operation considers three neighboring tokens at a time.
- When inputs are distant from each other (e.g., $x_1$ and $x_n$), the interaction between these inputs is achieved through multiple layers of convolution. Each layer of convolution increases the receptive field (i.e., the portion of the input that influences the output), but the rate of growth depends on the filter size and the stride.
2. The Transformer neural network¶
Today, we will cover the transformer network.
- A transformer is essentially a graph neural network (GNN) with
- a specially constructed graph ("fully" connected with relevance weights on the edges)
- a few tricks that allow it to also learn how the words (tokens) are ordered in the sequence.
2.1. Tokenization: From Sentences to Sequences¶
- The tokens in a sentence are a sequence $x_1,\ldots,x_n$.
This sequence is represented by embeddings $\mathbf{E} \in \mathbb{R}^{V \times d_x}$ where $V$ is the vocabulary size and $d_x$ is the embedding dimension, often $d_x = 4096$.
Formally, each token $x_i$ is mapped to an embedding vector $\mathbf{e}_i = \mathbf{E}_{x_i} \in \mathbb{R}^{d_x}$, where $\mathbf{E}_{x_i}$ denotes the $x_i$-th row of the embedding matrix $\mathbf{E}$.
The token embedding matrix $\mathbf{E}$ is a learnable parameter matrix that is updated during model training via backpropagation: $\mathbf{E} \leftarrow \mathbf{E} - \alpha \nabla_{\mathbf{E}} \mathcal{L}$, where $\alpha$ is the learning rate and $\mathcal{L}$ is the loss function.
2.1.1. Step-by-step Tokenization¶
- The first step is to break the sentence "I don't like avocado thank" into tokens: you can try tiktoken here.
For OpenAI's GPT4 tiktoken, "I don't like avocado thank" => ("I", "_don't", "_like", "_avocado", "_thank") is the sequence.
Important: These are all different tokens:
- "_thank" in "avocado thank"
- "thank" in "thank you"
- "Thank" in "Thank you"
- "Thak" in "Thak you" is two tokens ("Th", "ak").
- In training we corrupt the training data so that the model sees misspelled words and understands that the two tokens ("Th", "ak") act like "Thank".
A tokenizer will transform the sequence into token indices. For OpenAI's GPT4o, "I don't like avocado thank" is the sequence $(40, 4128, 1299, 97176, 11172)$.
Let $\mathcal{T}: \text{String} \rightarrow \mathbb{Z}^n$ be the tokenization function that maps a string to a sequence of token indices, where $n$ is the sequence length. Then, $\mathcal{T}(\text{"I don't like avocado thank"}) = (40, 4128, 1299, 97176, 11172)$.
The sequence embedding is then $[\mathbf{E}_{40}, \mathbf{E}_{4128}, \mathbf{E}_{1299}, \mathbf{E}_{97176}, \mathbf{E}_{11172}] \in \mathbb{R}^{5 \times d_x}$.
- OpenAI's GPT4 has 50257 tokens, which implies an embedding matrix $\mathbf{E} \in \mathbb{R}^{50257 \times d_x}$ to represent these tokens.
- For $d_x = 4096$, just the token embeddings have $50257 \times 4096 = 205,852,672$ parameters.
- During training, the gradient $\nabla_{\mathbf{E}} \mathcal{L}$ for a loss $\mathcal{L}$ is sparse, as only the rows corresponding to tokens in the current batch are updated.
There are some special tokens to represent beginning, end, and other control signals in the sequence:
<bos>: Beginning of sequence marker<eos>: End of sequence marker<pad>: Padding token used to ensure uniform sequence length in batches<unk>: Unknown token for handling out-of-vocabulary words<mask>: Used in masked language modeling tasksThe tokenization process is reversible through detokenization, where token indices are mapped back to their string representations: $\mathcal{T}^{-1}: \mathbb{Z}^n \rightarrow \text{String}$.
Modern tokenizers like BPE (Byte Pair Encoding) or WordPiece adaptively learn subword units that balance vocabulary size with representation flexibility.
Tokenization is language-dependent, with different languages requiring different tokenization strategies. Languages with non-Latin scripts or without clear word boundaries (e.g., Chinese, Japanese) present additional challenges.
#Example of GPT-4 tokenization:
# If tiktoken is not installed uncomment the following line
#!pip install tiktoken
import tiktoken
# Initialize the encoder for GPT-4
encoding = tiktoken.get_encoding("cl100k_base") # This is the GPT-4 encoding
# The example sentence
text = "I don't like avocado thank"
# Encode the text into tokens
tokens = encoding.encode(text)
# Decode each token to see the token boundaries
token_texts = [encoding.decode_single_token_bytes(token).decode('utf-8', errors='replace') for token in tokens]
print(f"Text: {text}")
print(f"Token IDs: {tokens}")
print(f"Tokens: {token_texts}")
print(f"Token count: {len(tokens)}")
Text: I don't like avocado thank Token IDs: [40, 1541, 956, 1093, 68346, 9901] Tokens: ['I', ' don', "'t", ' like', ' avocado', ' thank'] Token count: 6
#Example of tokenization of Llama 2:
# If transformers is not installed uncomment the following line
#!pip install transformers
from transformers import AutoTokenizer
# Load the Llama 2 tokenizer
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/llama-tokenizer",legacy=False)
# The example sentence
text = "I don't like avocado thank"
# Encode the text into tokens
tokens = tokenizer.encode(text)
# Get the actual token texts
token_texts = tokenizer.convert_ids_to_tokens(tokens)
print(f"Text: {text}")
print(f"Token IDs: {tokens}")
print(f"Tokens: {token_texts}")
print(f"Token count: {len(tokens)}")
Text: I don't like avocado thank Token IDs: [1, 306, 1016, 29915, 29873, 763, 1029, 542, 912, 6452] Tokens: ['<s>', '▁I', '▁don', "'", 't', '▁like', '▁av', 'oc', 'ado', '▁thank'] Token count: 10
2.2. A GNN for a sequence of $n$ tokens¶
A Message-passing GNN can produce node embeddings for arbitrary sized graphs. Could we use Message-passing GNNs to produce sequence representations of arbitrary size?
Consider the following self-attention graph $G = (V,E,X)$, with
Vertex set $V=\{1,\ldots,n\}$
Vertex attributes $X= \{x_i\}_{i \in V}$.
- And edges $E$ as a function of the vertex attributes $X$:
The adjacency matrix (edge weights) of $G$ is ${\bf A}$, such that element ${\bf A}_{ij}$ is a function of the vertex attributes of $i,j \in V$: $${\bf A}_{ij} = \alpha(x_i,x_j; {\bf W}_\alpha),$$ where $\alpha(\cdot, \cdot; {\bf W}_\alpha)$ is a neural network parameterized by ${\bf W}_\alpha$.
- We will call $\alpha$ the self-attention mechanism, a value between (0,1).
- It is called self-attention because it maps elements of $x_1,\ldots,x_n$ on themselves.
Consider the sentence
I don't like avocado, thank
The feature set of the vertices is a vector that describe the word $$X=\{(x_\text{avocado}), (x_\text{like}), (x_\text{thank}), (x_\text{I}), (x_\text{don't})\}$$
And recall that
$${\bf A}_{ij} = \alpha(x_i,x_j; {\bf W}_\alpha),$$
2.3. The need for positional encodings¶
- Running a GNN on the fully connected graph above will give a representation output that does not respect the order of the words in the sentence
I.e., the tokens get the same representation no matter their order in the sentence.
I don't like avocado thankavocado I don't like thankI avocado don't like thank
- In the the GNN lectures we have seen how symmetry-breaking allows us to produce positional representations for nodes.
If every node has a distinct feature related to its position in the text, then nodes are distinct and can represent a sequence: $$X'=\{(x_\text{avocado} + pos(4)), (x_\text{like} + pos(3)), (x_\text{thank} + pos(5)), (x_\text{I} + pos(1)), (x_\text{don't} + pos(2))\}$$
Let's illustrate edges of the self-attention graph $G$ with adjacency matrix ${\bf A}$:
Note that the edges of $G$ are a function of the input sequence $x'_1,\ldots,x'_n$.
Proposition: If $\Gamma_G({\bf A}_{1,1}, {\bf A}_{1,2},\ldots,{\bf A}_{n,n},x'_1,\ldots,x'_n)$ is a graph representation of $G$.
- Then, $\Gamma_G$ is also a permutation-equivariant representation of the sequence $x'_1,\ldots,x'_n$.
Proof: If $\Gamma_G({\bf A}_{1,1}, {\bf A}_{1,2},\ldots,{\bf A}_{n,n},x'_1,\ldots,x'_n)$ is a graph representation, it must be equivariant to joint permutations:
$$\Gamma_G({\bf A}_{1,1}, {\bf A}_{1,2},\ldots,{\bf A}_{n,n},x'_1,\ldots,x'_n)_{i,\cdot} = \Gamma_G({\bf A}_{\pi \circ 1,\pi \circ 1}, {\bf A}_{\pi \circ 1,\pi \circ 2},\ldots,{\bf A}_{\pi \circ n,\pi \circ n},x'_{\pi \circ 1},\ldots,x'_{\pi \circ n})_{\pi^{-1} \circ i,\cdot}, \: \forall \pi \in \mathbb{S}_n.$$
Since ${\bf A}_{\pi \circ i,\pi \circ j} = \alpha(x'_{\pi \circ i},x'_{\pi \circ j}; \cdot)$, the representation $\Gamma_G$ only depends on $x'_1,\ldots,x'_n$ and is, by its definition, invariant to a shuffling of the input sequence $x'_{\pi' \circ 1},\ldots,x'_{\pi' \circ n}$, $\forall \pi' \in \Pi_n$.
3. Positional Encodings (part 1)¶
To incorporate sequence order information into the transformer architecture, we add positional encodings $\mathbf{P} \in \mathbb{R}^{n \times d}$ to the input embeddings:
$$\mathbf{X}' = \mathbf{X} + \mathbf{P}$$
In the original transformer model, these positional encodings are computed using sinusoidal functions:
$$\mathbf{P}_{i,2j} = \sin\left(\frac{i}{10000^{2j/d}}\right)$$
$$\mathbf{P}_{i,2j+1} = \cos\left(\frac{i}{10000^{2j/d}}\right)$$
where:
- $i$ represents the position index in the sequence
- $j$ denotes the dimension index in the embedding space
- $d$ is the dimensionality of the embedding
This sinusoidal encoding scheme has several advantageous properties:
- It allows the model to extrapolate to sequence lengths not seen during training
- It provides a unique encoding for each position
- The relative position information is preserved through linear dependencies between different positions
Note: Modern transformer architectures have evolved to use rotational positional embeddings, which we will examine in a later section.
import torch
import matplotlib.pyplot as plt
import numpy as np
import math
import matplotlib
# Enable LaTeX rendering in matplotlib
matplotlib.rcParams.update({
'text.usetex': True,
'font.family': 'serif',
'font.serif': ['Computer Modern Roman']
})
# Create positional encodings
d_model = 20 # Embedding dimension
seq_len = 20 # Focus on first 20 positions
# Initialize positional encoding matrix
pe = torch.zeros(seq_len, d_model)
position = torch.arange(0, seq_len).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2) * -(math.log(10000.0) / d_model))
# Compute encodings
pe[:, 0::2] = torch.sin(position * div_term) # Apply sine to even indices
pe[:, 1::2] = torch.cos(position * div_term) # Apply cosine to odd indices
# Create a high-resolution x-axis for smooth curves
positions_highres = np.linspace(0, seq_len-1, 1000)
# Interpolate the positional encodings for smooth curves
# We'll use a simple linear interpolation for visualization
def interpolate(pos, pe_matrix, dim):
pos_floor = int(np.floor(pos))
pos_ceil = int(np.ceil(pos))
if pos_floor == pos_ceil:
return pe_matrix[pos_floor, dim].item()
# Linear interpolation
frac = pos - pos_floor
return (1-frac) * pe_matrix[pos_floor, dim].item() + frac * pe_matrix[pos_ceil, dim].item()
# Visualization
plt.figure(figsize=(12, 6))
# Plot the first 5 dimensions
for dim in range(5):
smooth_values = [interpolate(pos, pe, dim) for pos in positions_highres]
plt.plot(positions_highres, smooth_values, label=f"dim {dim}", alpha=0.7)
# Add vertical lines at integer positions to show P_{i,*}
for i in range(seq_len):
plt.axvline(x=i, color='gray', linestyle='--', alpha=0.3)
# Highlight the positional encoding values at this integer position
for dim in range(5):
plt.plot(i, pe[i, dim].item(), 'o', markersize=6,
color=plt.gca().lines[dim].get_color(),
markeredgecolor='black', markeredgewidth=1)
# Add x-ticks at integer positions only
plt.xticks(np.arange(0, seq_len))
# Use LaTeX formatted title
plt.title(r"Positional Encoding Values $\mathbf{P}_{i,\cdot}$ at Integer Positions")
plt.xlabel(r"Position index ($i$)")
plt.ylabel(r"Encoding value")
plt.xlim(0, seq_len-1)
plt.ylim(-1.1, 1.1)
plt.grid(True, alpha=0.3)
plt.legend(loc="upper right")
plt.tight_layout()
plt.show()
4. Transformer Block = Attention Graph Representations + Positional Encodings¶
The transformer architecture was first introduced by (Vaswani et al., 2017) The key idea is Transformer block = self-attention graph + a graph neural network with positional encoding:
Formally, a transformer block operates on a sequence of token embeddings $\mathbf{X} = [\mathbf{x}_1, \mathbf{x}_2, \ldots, \mathbf{x}_n]^T \in \mathbb{R}^{n \times d}$ where $n$ is the sequence length and $d$ is the embedding dimension.
4.1. Self-Attention as Multiple Graphs (Multiple Attention Heads)¶
The multi-head self-attention mechanism constructs multiple weighted graphs in parallel:
Query, Key, Value projections for each head $h \in \{1, 2, ..., H\}$:
- $\mathbf{Q}^h = \mathbf{X}\mathbf{W}_Q^h \in \mathbb{R}^{n \times d_k},$
- $\mathbf{K}^h = \mathbf{X}\mathbf{W}_K^h \in \mathbb{R}^{n \times d_k},$
- $\mathbf{V}^h = \mathbf{X}\mathbf{W}_V^h \in \mathbb{R}^{n \times d_v},$
where $\mathbf{W}_Q^h, \mathbf{W}_K^h \in \mathbb{R}^{d \times d_k}$ and $\mathbf{W}_V^h \in \mathbb{R}^{d \times d_v}$ are learnable parameter matrices for head $h$, with $d_k = d_v = d/H$ typically.
Attention scores for each head (creating $H$ separate graph adjacency matrices):
- $\mathbf{A}^h = \text{softmax}\left(\frac{\mathbf{Q}^h(\mathbf{K}^h)^T}{\sqrt{d_k}}\right) \in \mathbb{R}^{n \times n}$
where $\mathbf{A}_{ij}^h$ represents the weighted edge from token $j$ to token $i$ in the attention graph for head $h$.
Message passing via weighted sum for each head:
- $\mathbf{Z}^h = \mathbf{A}^h\mathbf{V}^h \in \mathbb{R}^{n \times d_v}$
Concatenation of outputs from all heads:
- $\mathbf{Z}_{\text{concat}} = [\mathbf{Z}^1; \mathbf{Z}^2; \ldots; \mathbf{Z}^H] \in \mathbb{R}^{n \times Hd_v} = \mathbb{R}^{n \times d} (\text{if }d_v = d/H)$
Final projection to produce multi-head attention output:
- $\mathbf{Z} = \mathbf{Z}_{\text{concat}}\mathbf{W}^Z \in \mathbb{R}^{n \times d}$
where $\mathbf{W}^Z \in \mathbb{R}^{d \times d}$ is a learnable output projection matrix.
4.1.1. Multi-Query Attention (MQA) and Grouped Query Attention (GQA)¶
As LLMs are deployed for inference at scale, a key bottleneck emerges: the KV cache. During autoregressive generation, the key and value tensors for all past tokens must be recomputed or cached per attention head. With $H$ heads, the KV cache scales as $O(H \cdot n \cdot d_k)$, which becomes prohibitively expensive for long sequences and large batches.
Two widely-adopted variants reduce this cost:
Multi-Query Attention (MQA) — Shazeer (2019)¶
MQA uses a single shared key and value projection across all query heads. Only the query projections remain head-specific:
$$\mathbf{Q}^h = \mathbf{X}\mathbf{W}_Q^h \in \mathbb{R}^{n \times d_k}, \quad h = 1,\ldots,H$$ $$\mathbf{K} = \mathbf{X}\mathbf{W}_K \in \mathbb{R}^{n \times d_k}, \quad \mathbf{V} = \mathbf{X}\mathbf{W}_V \in \mathbb{R}^{n \times d_v} \quad \text{(shared across all heads)}$$
The attention output for head $h$ is: $$\mathbf{Z}^h = \text{softmax}\!\left(\frac{\mathbf{Q}^h \mathbf{K}^T}{\sqrt{d_k}}\right)\mathbf{V}$$
- The KV cache is reduced by a factor of $H$ compared to standard MHA, since there is only one key and value matrix.
- However, MQA can degrade model quality on complex reasoning tasks due to the loss of diversity in key/value representations.
Grouped Query Attention (GQA) — Ainslie et al. (2023)¶
GQA interpolates between MHA and MQA by dividing the $H$ query heads into $G$ groups ($1 \leq G \leq H$), where each group of $H/G$ query heads shares a single key and value projection:
$$\mathbf{Q}^h = \mathbf{X}\mathbf{W}_Q^h, \quad h = 1, \ldots, H$$ $$\mathbf{K}^g = \mathbf{X}\mathbf{W}_K^g, \quad \mathbf{V}^g = \mathbf{X}\mathbf{W}_V^g, \quad g = 1, \ldots, G$$
For query head $h$ in group $g = \lceil hG/H \rceil$, the attention output is: $$\mathbf{Z}^h = \text{softmax}\!\left(\frac{\mathbf{Q}^h (\mathbf{K}^g)^T}{\sqrt{d_k}}\right)\mathbf{V}^g$$
Trade-offs:
- GQA is the de facto standard in modern LLMs.
- A typical choice is $G = H/8$ (e.g., $H=32$ query heads, $G=4$ KV heads in Llama 3 8B).
- GQA achieves near-MHA quality while reducing memory bandwidth by up to $H/G\times$ during inference: very important for serving at scale.
4.1.2. Flash Attention 2 — Dao et al. (2022, 2023)¶
Standard attention has a memory bandwidth bottleneck: computing $$\mathbf{A}^h = \text{softmax}\!\left(\tfrac{\mathbf{Q}^h(\mathbf{K}^h)^T}{\sqrt{d_k}}\right)$$ requires materializing the full $n \times n$ attention matrix in high-bandwidth memory (HBM / GPU global memory). For sequence length $n$, this requires $O(n^2)$ HBM reads/writes, which is extremely slow relative to compute throughput.
Flash Attention reorders the attention computation using tiling to keep intermediate results in the fast on-chip SRAM, avoiding repeated round-trips to HBM. Flash Attention 2 further improves parallelism and reduces non-matrix-multiply FLOPs.
Memory Hierarchy Motivation¶
Modern GPUs have a two-level memory hierarchy:
- HBM (High-Bandwidth Memory): Large ($\sim$40–80 GB on an A100), but slow bandwidth relative to compute ($\sim$2 TB/s).
- SRAM (on-chip shared memory): Tiny ($\sim$20 MB on an A100), but extremely fast ($\sim$19 TB/s).
Standard attention is memory-bandwidth bound, not compute-bound: most time is spent moving the $n \times n$ matrix between HBM and SRAM. Flash Attention eliminates this by never fully materializing $\mathbf{A}^h$.
Tiling Algorithm¶
Partition $\mathbf{Q}$, $\mathbf{K}$, $\mathbf{V}$ into blocks of size $B_r \times d_k$ and $B_c \times d_k$ that fit in SRAM. For each tile of queries, iterate over tiles of keys and values, accumulating the output using the online softmax trick:
Online softmax computes $\text{softmax}(\mathbf{a}) \cdot \mathbf{V}$ incrementally without materializing all scores:
For each block $j$ of keys/values, maintain running statistics: $$m_j = \max(m_{j-1},\, \text{rowmax}(\mathbf{S}_j)), \quad \ell_j = e^{m_{j-1}-m_j} \ell_{j-1} + \text{rowsum}(e^{\mathbf{S}_j - m_j})$$ $$\mathbf{O}_j = \text{diag}(\ell_j)^{-1}\!\left(e^{m_{j-1}-m_j}\,\text{diag}(\ell_{j-1})\,\mathbf{O}_{j-1} + e^{\mathbf{S}_j - m_j}\mathbf{V}_j\right)$$
where $\mathbf{S}_j = \mathbf{Q}_i \mathbf{K}_j^T / \sqrt{d_k}$ is the partial score block. This produces numerically identical results to standard softmax attention.
Complexity Comparison¶
| Method | HBM reads/writes | Memory for $\mathbf{A}$ |
|---|---|---|
| Standard Attention | $O(n^2 d)$ | $O(n^2)$ |
| Flash Attention 2 | $O(n^2 d^2 / M)$ where $M$ = SRAM size | $O(n)$ |
In practice, Flash Attention 2 tends to be 2–4× faster than standard attention for typical sequence lengths (1K–8K) and uses up to 10× less memory.
4.2. Feed-Forward Network (FFN / MLP Block)¶
Role of the FFN in the Transformer¶
Each transformer block alternates between two complementary operations:
- Multi-head self-attention (MHSA): processes relationships between tokens $\to$ which tokens should influence which others.
- Feed-forward network (FFN / MLP): applies a a transformation to each token separately (equivariant to token sequence permutations).
Architecture¶
The canonical FFN is a two-layer MLP applied independently to each token embedding $\mathbf{z}_i \in \mathbb{R}^d$:
$$\text{FFN}(\mathbf{z}_i) = \sigma\!\left(\mathbf{z}_i \mathbf{W}_1 + \mathbf{b}_1\right)\mathbf{W}_2 + \mathbf{b}_2$$
where:
- $\mathbf{W}_1 \in \mathbb{R}^{d \times d_{\text{ff}}}$ is the up-projection (also called the expansion matrix)
- $\mathbf{W}_2 \in \mathbb{R}^{d_{\text{ff}} \times d}$ is the down-projection (compression back to model dimension)
- $\mathbf{b}_1 \in \mathbb{R}^{d_{\text{ff}}}$, $\mathbf{b}_2 \in \mathbb{R}^{d}$ are bias vectors
- $\sigma$ is a non-linear activation function (discussed below)
- $d$ is the model dimension (e.g., 768, 4096, 8192 in GPT-2 / Llama 2 / Llama 3)
- $d_{\text{ff}} = m \times d$ is the standard hidden dimension (expansion factor of $m$)
This creates a bottleneck expand-compress architecture:
$$d \xrightarrow{\;\text{expand}\;} m d \xrightarrow{\;\text{compress}\;} d$$
The expansion to $m d$ allows the network to project the token representation into a much richer intermediate space, where non-linear transformations can capture complex patterns, before compressing back to the residual stream dimension $d$.
Activation Functions¶
The choice of $\sigma$ has evolved significantly from the original transformer paper:
| Activation | Formula | Used in |
|---|---|---|
| ReLU | $\max(0, x)$ | Original Transformer (Vaswani et al., 2017) |
| GELU | $x \cdot \Phi(x)$ where $\Phi$ is the Gaussian CDF | BERT, GPT-2 |
| SwiGLU | $\text{Swish}(xW_1) \odot (xW_3)$ | Llama 2/3, PaLM, Gemma |
SwiGLU (Shazeer, 2020) is the dominant choice in modern LLMs. It is a Gated Linear Unit (GLU) variant that introduces a third weight matrix $\mathbf{W}_3$ as a learned gate:
$$\text{FFN}_{\text{SwiGLU}}(\mathbf{z}_i) = \left(\text{Swish}(\mathbf{z}_i \mathbf{W}_1) \odot (\mathbf{z}_i \mathbf{W}_3)\right) \mathbf{W}_2,$$
where $\text{Swish}(x) = x \cdot \sigma(x)$ and $\odot$ is elementwise multiplication.
SwiGLU consistently outperforms ReLU and GELU across scales:
- SwiGLU gating mechanism gives the FFN fine-grained control over which intermediate features to pass through.
Parameter Count Example (Qwen 3.5)¶
- Qwen 3.5 122B A10 Mixture of Experts
- Q4_K_M quantization
- 48 Heads
- 256 non-shared Experts
- One shared Expert
- LAYER 4 — Total: 2.515 B parameters
Attention (projections) — 37.749 M | 1.5% of layer¶
| Tensor | Shape | Dtype | # Params | % Layer |
|---|---|---|---|---|
blk.4.attn_qkv.weight |
(48*256)×3072 | Q6_K | 37.749 M | 1.5% |
FFN (MoE experts) — 2.417 B | 96.1% of layer¶
| Tensor | Shape | Dtype | # Params | % Layer |
|---|---|---|---|---|
blk.4.ffn_down_exps.weight |
256×3072×1024 | Q6_K | 805.306 M | 32.0% |
blk.4.ffn_gate_exps.weight |
256×1024×3072 | Q4_K | 805.306 M | 32.0% |
blk.4.ffn_gate_inp.weight |
256×3072 | F32 | 786.432 K | 0.0% |
blk.4.ffn_up_exps.weight |
256×1024×3072 | Q4_K | 805.306 M | 32.0% |
FFN (shared expert) — 9.437 M | 0.4% of layer¶
| Tensor | Shape | Dtype | # Params | % Layer |
|---|---|---|---|---|
blk.4.ffn_down_shexp.weight |
3072×1024 | Q8_0 | 3.146 M | 0.1% |
blk.4.ffn_gate_shexp.weight |
1024×3072 | Q8_0 | 3.146 M | 0.1% |
blk.4.ffn_up_shexp.weight |
1024×3072 | Q8_0 | 3.146 M | 0.1% |
Layer norms — 3.072 K | 0.0% of layer¶
| Tensor | Shape | Dtype | # Params | % Layer |
|---|---|---|---|---|
blk.4.attn_norm.weight |
3072 | F32 | 3.072 K | 0.0% |
Other (per-layer) — 50.780 M | 2.0% of layer¶
| Tensor | Shape | Dtype | # Params | % Layer |
|---|---|---|---|---|
blk.4.attn_gate.weight |
8192×3072 | Q4_K | 25.166 M | 1.0% |
blk.4.ffn_gate_inp_shexp.weight |
3072 | F32 | 3.072 K | 0.0% |
blk.4.post_attention_norm.weight |
3072 | F32 | 3.072 K | 0.0% |
blk.4.ssm_a |
64 | F32 | 64 | 0.0% |
blk.4.ssm_alpha.weight |
64×3072 | F32 | 196.608 K | 0.0% |
blk.4.ssm_beta.weight |
64×3072 | F32 | 196.608 K | 0.0% |
blk.4.ssm_conv1d.weight |
12288×4 | F32 | 49.152 K | 0.0% |
blk.4.ssm_dt.bias |
64 | F32 | 64 | 0.0% |
blk.4.ssm_norm.weight |
128 | F32 | 128 | 0.0% |
blk.4.ssm_out.weight |
3072×8192 | Q8_0 | 25.166 M | 1.0% |
4.3. Complete Transformer Block¶
Combining these components with layer normalization:
- Self-attention with residual connection:
- $\mathbf{Z}' = \text{LayerNorm}(\mathbf{X}' + \text{MultiHead}(\mathbf{X}'))$
- Feed-forward with residual connection:
- $\mathbf{Y} = \text{LayerNorm}(\mathbf{Z}' + \text{MLP}(\mathbf{Z}'))$ where $\mathbf{Y}$ is the output of the transformer block that serves as input to the next block.
- Note that $\text{MLP}(\mathbf{Z}')$ applies the MLP over all $n$ token embeddings in parallel.
4.3.1. Layer Normalization¶
Layer normalization (LayerNorm) plays a key role in stabilizing and accelerating training of transformer networks. It normalizes the inputs across feature dimensions rather than batch dimensions, enabling sequences with variable lengths.
For an input vector $\mathbf{x} \in \mathbb{R}^d$, LayerNorm computes:
$$\text{LayerNorm}(\mathbf{x}) = \gamma \odot \frac{\mathbf{x} - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta$$
where:
- $\mu = \frac{1}{d}\sum_{i=1}^{d} x_i$ is the mean across features
- $\sigma^2 = \frac{1}{d}\sum_{i=1}^{d} (x_i - \mu)^2$ is the variance
- $\gamma, \beta \in \mathbb{R}^d$ are learnable scale and shift parameters
- $\epsilon$ is a small constant for numerical stability
Layer normalization plays a key role in stabilizing the learning process.
4.4. Complete Architecture: Multiple Transformer Layers¶
Transformer Architecture (Decoder-only architecture)¶
Input Processing¶
- Sequence Input: Tokens $(x_1,x_2,\ldots,x_n)$ are the token embeddings that are inputs to the architecture
- Positional Encoding: Added to embeddings to retain sequence order information
- Combination: Position and token embeddings are added together ($\oplus$)
Core Architecture¶
- Transformer Encoding Blocks: Multiple identical blocks stacked vertically. Each block has its own parameters.
- Information Flow: Sequential processing through encoding layers, with each layer's output serving as input to the next layer
- Residual Connections: Facilitate gradient flow during training
Encoding Block Components¶
- Multi-head Attention: Allows the model to focus on different parts of the input sequence simultaneously
- Add & Norm: Residual connection followed by layer normalization
- Feed Forward Network: Position-wise fully connected layer for transformation
- Second Add & Norm: Additional residual connection and normalization
Output¶
- Sequence Representation: Final outputs $(h_1,h_2,\ldots,h_n)$ represent final contextualized embeddings of the input sequence
- Representation Utilization: These can be used for various downstream tasks (classification, generation, etc.)
The architecture's strength lies in its ability to capture long-range dependencies and contextual relationships within sequential data through its self-attention mechanism, while maintaining computational efficiency through parallelization.
5. Autoregressive Training (Decoder-only Architecture)¶
5.1. Autoregressive Predictions with Causal Masking¶
The "causal" mask (temporal mask) learns the conditional probability distribution of next-token prediction.
This mechanism shapes how information flows through the self-attention layers during both training and inference.
We will train the transformer to predict future tokens based on past tokens using the conditional probability:
$$f(x_t | x_{<t}; \theta) := \text{softmax}(h_t(\theta') \mathbf{W}_H + b_H)_{x_t},$$
where:
- $(h_1,h_2,\ldots,h_n)$ are the final outputs of the autoregressive transformer
- $x_t$ represents the token at position $t$
- $x_{<t}$ denotes all preceding tokens in the sequence
- $\theta$ encompasses the model parameters to be optimized and $\theta' = \theta \backslash \{\mathbf{W}_H , b_H\}$
5.1.1. Causal Masking Implementation (Self-supervised objective)¶
The decoder architecture implements this autoregressive constraint through several key components:
Initialization: The process begins with a designated start token that signals the commencement of generation.
Input Processing: At each step $t$, the decoder processes:
- All previously tokens
- These are ground truth tokens during training
- These are previously-generated tokens during inference
- All previously tokens
Attention Constraint: A constraint enforced during self-attention computation is:
- For any attention head $m$, the attention weight $\alpha^{(m)}(x_t, x_{t+j}; \cdot) = 0$, $\forall j > 0$
- This prevents any token from attending to tokens that occur later in the sequence
Technical Implementation: This constraint is implemented by:
- Creating an attention mask matrix with zeros in the lower triangle (including diagonal) and negative infinity elsewhere
- Applying this mask to the attention scores before softmax normalization
- Resulting in zero attention weights for all future positions after softmax
Termination Criterion: The generation process continues iteratively until the model produces an <end of sentence> token, signaling completion.
This causal masking technique ensures a self-supervised objective so that the model learns to generate sequences autoregressively.
The attention graph is:
5.2. Pre-Training Objective: Negative Log-Likelihood¶
- The score function in transformer models typically is the negative log-likelihood (NLL).
Mathematical Formulation¶
For a sequence of tokens $x_1, x_2, ..., x_n$, the negative log-likelihood is defined as: $$\mathcal{L}(\theta) = -\sum_{t=1}^{n} \log f(x_t | x_{<t}; \theta) = -\sum_{t=1}^{n} \log \text{softmax}(h_t(\theta') \mathbf{W}_H + b_H)_{x_t},$$ Where:
- $\theta$ encompasses the model parameters to be optimized and $\theta' = \theta \backslash \{\mathbf{W}_H , b_H\}$
- $f(x_t | x_{<t}; \theta) \in [0,1]$ is the conditional probability the model assigns to token $x_t$ given all previous tokens $x_{<t}$
This probabilistic intepretation is useful for language models:
Direct Probability Interpretation: The loss directly measures how well the model predicts the true next token. These probabilities can be tweaked in during inference as we will see later (in test).
Differentiability: NLL is fully differentiable with respect to model parameters.
The next-token prediction objective creates certain biases in the model that must be dealt with by post-processing or fine-tuning:
- A strong token-position correlation in training biases the model towards certain tokens at certain positions.
- Today's LLM assistants are based on next-token prediction models but they have a lot of post-processing and fine tuning.
Extensions and Variations¶
Modern transformer implementations often incorporate extensions to the basic NLL objective:
- Label Smoothing: Label smoothing modifies the target distribution by redistributing probability mass from the true label to other classes, preventing models from becoming overconfident in their predictions. Szegedy et al. (2016) in Section 7, introduced this technique to improve generalization, and subsequent work by Müller et al. (2019) demonstrated its effectiveness in transformer-based architectures
- Focal Loss (Lin et al., 2017): Focal loss dynamically scales the NLL to focus on hard examples by down-weighting easy ones.
- Contrastive Objectives: Type of self-supervised pre-training objective that augments NLL with additional terms that encourage better representations, such as learning discriminative representations by contrasting positive and negative pairs.
These refinements help address specific challenges in training large language models while maintaining the core next-token prediction NLL objective.