Session #9: Transformer Architecture: Encoders
Free University Berlin
2026-04-26
Game plan
This lecture provides an introduction to the transformer architecture with a focus on the encoder.
The embedding process transforms discrete tokens into a continuous vector space \(\mathcal{V} \to \mathbb{R}^d\).
\[ \begin{equation} \mathbf{e}_i = \text{embed}(w_i) = \mathbf{x}_i^\top \mathbf{W}_e \end{equation} \] Where:
\[ \mathbf{W}_e = \begin{bmatrix} \leftarrow & \mathbf{e}_0 & \rightarrow \\ \leftarrow & \mathbf{e}_1 & \rightarrow \\ & \vdots & \\ \leftarrow & \mathbf{e}_{V-1} & \rightarrow \end{bmatrix} \]
Figure 1: RNN vs Encoder
See lecture 7: RNNs and LSTMs for background on RNNs
\[ \left[E_{\mathrm{I}}+P_0, E_{\mathrm{am}}+P_1,E_{\mathrm{an}}+P_2, E_{\mathrm{automaton}}+P_3\right] \]
Vaswani A et al. (2017) Attention Is All You Need. arXiv 1706.03762
\[ \mathbf{p}_i = \left[\sin\left(\frac{i}{10000^{\frac{2j}{d}}}\right), \cos\left(\frac{i}{10000^{\frac{2j}{d}}}\right) \right]_{j=0}^{\frac{d}{2}-1} \]
A positional encoding has the same dimension as an embedding, and calculates a value for each dimension using the sine and cosine formulas.
\[ \mathbf{p}_i = \left[\sin\left(\frac{i}{10000^{\frac{2j}{d}}}\right), \cos\left(\frac{i}{10000^{\frac{2j}{d}}}\right) \right]_{j=0}^{\frac{d}{2}-1} \]
\[ \begin{align} \mathbf{p}_0 &= \left[\sin\left(\frac{0}{10000^{\frac{0}{4}}}\right), \cos\left(\frac{0}{10000^{\frac{0}{4}}}\right), \sin\left(\frac{0}{10000^{\frac{1}{2}}}\right), \cos\left(\frac{0}{10000^{\frac{1}{2}}}\right) \right] =\left[0,1, 0, 1\right] \\ \mathbf{p}_1 &= \left[\sin\left(\frac{1}{10000^{\frac{0}{4}}}\right), \cos\left(\frac{1}{10000^{\frac{0}{4}}}\right), \sin\left(\frac{1}{10000^{\frac{1}{2}}}\right), \cos\left(\frac{1}{10000^{\frac{1}{2}}}\right)\right] = \left[0.8415, 0.5403, 0.0100, 0.9999\right] \\ \mathbf{p}_2 &= \left[\sin\left(\frac{2}{10000^{\frac{0}{4}}}\right), \cos\left(\frac{2}{10000^{\frac{0}{4}}}\right), \sin\left(\frac{2}{10000^{\frac{1}{2}}}\right), \cos\left(\frac{2}{10000^{\frac{1}{2}}}\right)\right] = \left[0.9093, −0.4161, 0.0200, 0.9998\right] \\ \mathbf{p}_3 &= \left[\sin\left(\frac{3}{10000^{\frac{0}{4}}}\right), \cos\left(\frac{3}{10000^{\frac{0}{4}}}\right), \sin\left(\frac{2}{10000^{\frac{1}{2}}}\right), \cos\left(\frac{2}{10000^{\frac{1}{2}}}\right)\right] = \left[0.1411, −0.9900, 0.0300, 0.9996\right] \\ \end{align} \]
The Linearity Property (Relative Positioning)
For any fixed offset \(\Delta k\), the encoding at a shifted position can be represented as a linear transformation of the original:
\[PE_{pos + \Delta k} = \mathbf{M}_{\Delta k} \cdot PE_{pos}\]
To prove this, recall the Angle Addition Formulas that specify how to compute trig functions of sums or differences of angles.
To prove that \(PE_{pos+k}\) is a linear transformation of \(PE_{pos}\), we need to show that there exists a fixed matrix \(M_k\) (that only depends on the offset \(k\), not the position \(pos\)) such that: \[PE_{pos+k} = M_k \cdot PE_{pos}\]
We want to find the encoding at \(pos + k\):
\[\sin(\omega_i(pos + k)) = \sin(\omega_i \cdot pos + \omega_i \cdot k)\]\[\cos(\omega_i(pos + k)) = \cos(\omega_i \cdot pos + \omega_i \cdot k)\]
Plugging into the Angle Addition Formulas:
\[ \begin{align} \sin(\omega_i \cdot pos + \omega_i \cdot k) &= \sin(\omega_i \cdot pos)\cos(\omega_i \cdot k) + \cos(\omega_i \cdot pos)\sin(\omega_i \cdot k)\\ \cos(\omega_i \cdot pos + \omega_i \cdot k) &= \cos(\omega_i \cdot pos)\cos(\omega_i \cdot k) - \sin(\omega_i \cdot pos)\sin(\omega_i \cdot k) \end{align} \]
Notice that the terms \(\cos(\omega_i \cdot k)\) and \(\sin(\omega_i \cdot k)\) are constants once we pick a fixed distance \(k\).
We can rewrite the equations above as a matrix multiplication: \[ \begin{align} \begin{bmatrix} \sin(\omega_i(pos+k)) \\ \cos(\omega_i(pos+k)) \end{bmatrix} &= \begin{bmatrix} \cos(\omega_i k) & \sin(\omega_i k) \\ -\sin(\omega_i k) & \cos(\omega_i k) \end{bmatrix} \begin{bmatrix} \sin(\omega_i pos) \\ \cos(\omega_i pos) \end{bmatrix}\\ &= \begin{bmatrix}\cos(\omega_i k) \sin(\omega_i pos) +\sin(\omega_i k) \cos(\omega_i pos)\\ -\sin(\omega_i k)\sin(\omega_i pos) +\cos(\omega_i k)\cos(\omega_i pos) \end{bmatrix} \end{align} \]
Define \(M_k = \begin{bmatrix} \cos(\omega_i k) & \sin(\omega_i k) \\ -\sin(\omega_i k) & \cos(\omega_i k) \end{bmatrix}\), so that \(PE_{pos+k} = M_k \cdot PE_{pos}\).
\(M_k\) is a rotation matrix: \(\det(M_k) = \cos^2(\omega_i k) + \sin^2(\omega_i k) = 1\), and \(M_k M_k^\top = I\), so \(M_k\) is orthogonal with determinant 1.
Crucially, \(M_k\) depends only on the offset \(k\) (and frequency \(\omega_i\)) — and not on the absolute position \(pos\).
image: https://github.com/hkproj/bert-from-scratch
\[X_i\cdot X_j = (E_i + P_i) \cdot (E_j + P_j)\]
This results in four distinct terms
High Dimensionality: In a 512 or 1024-dimensional space, there is a lot of “room.”
The model the model has room to partially separate certain dimensions primarily for semantic meaning and other dimensions primarily for positional signal.
Learned Projections: The weight matrices (\(W_Q, W_K, W_V\)) act as filters.1 Through training, the model learns to project the “summed” vector into a subspace where the positional information is amplified when it needs to know distance, and the semantic information is amplified when it needs to know meaning.
The cross-terms (like \(E_{v} \cdot P_v\)) tend to be very close to zero because “meaning” vectors and “position” vectors are nearly orthogonal in high-dimensional space
Let \(v\) be the token at position \(P_v\) and \(w\) be the token at position \(P_w\). Then in most cases we have
\[(E_{v} + P_v) \cdot (E_{w} + P_w) \approx \underbrace{(E_{v} \cdot E_{w})}_{\text{Do these words relate?}} + \underbrace{(P_v \cdot P_w)}_{\text{Are they close together?}}\]
Attention: - The transformer purely relies on the attention mechanism to capture the dependency among input tokens - Multihead attention applies multiple heads in parallels - By splitting queries, keys, and values into smaller subspaces, different heads focus on distinct relationships, grammar rules, or word meanings simultaneously before combining the results
The transformer architecture is built around a core encoder block that processes sequential data three three principle components
The input to the encoder layer can be represented by a matrix \(\mathbf{X}\) with \(n\) tokens and \(d\) features (\(n \times d\)): \[ \mathbf{X} = \begin{bmatrix} x_{1,1} & x_{1,2} & \cdots & x_{1,d} \\ x_{2,1} & x_{2,2} & \cdots & x_{2,d} \\ \vdots & & \ddots & \vdots \\ x_{n,1} & x_{n,2} & \cdots & x_{n,d} \\ \end{bmatrix} \]
Each row corresponds to the embedded representation of one token: \(\mathbf{x}_{i} \in \mathbb{R}^d\)
The self-attention mechanism transforms \(\mathbf{X}\) through learned weight matrices \(\mathbf{W}^{Q}\), \(\mathbf{W}^{K}\), and \(\mathbf{W}^{V} \in \mathbb{R}^{d \times d}\) to obtain the query, key, and value matrices:
An input sequence \(\mathbf{X}\) is an \(n \times d\) matrix (\(n\) tokens, \(d\) features).
Each row is a token (sum of embedding and positional matrix)
For each token \(x_i\) (a \(1 \times d\) row vector): \[ \underbrace{q_i}_{1 \times d} = \underbrace{x_i}_{1 \times d} \times \underbrace{W^Q}_{d \times d} \]
Equivalently, we can represent the operations in matrix form
\[ \mathbf{Q} = \mathbf{X}\mathbf{W}^{Q}, \quad \mathbf{K} = \mathbf{X}\mathbf{W}^{K}, \quad \mathbf{V} = \mathbf{X}\mathbf{W}^{V} \]
\[ \underset{(n \times d)}{\mathbf{Q}} = \underset{(n \times d)}{\mathbf{X}} \times \underset{(d \times d)}{\mathbf{W}^{Q}} \quad\quad \text{(etc.)} \]
At a high level
The attention function \(A(Q,K,V)\) is typically caculated in steps. First, we calculate the attention scores as a similarity measure between the query vectors and the key vectors. \[ S_{i,j} = \dfrac{\langle \mathbf{q}_i, \mathbf{k}_j\rangle}{\sqrt{d_k}} = \dfrac{\mathbf{q}_i^T\mathbf{k}_j}{\sqrt{d_k}} \]
$ _i$: the \(i^{th}\) query vector and \(\mathbf{k}_j\): \(j^{th}\) key vector
\(d_k\) is the dimensionality of the key vectors
\(\langle \mathbf{q}_i, \mathbf{k}_j\rangle\) denotes the dot product.
The scaling factor \(\frac{1}{\sqrt{d_k}}\) is introduced to mitigate the effect of increasing dimensionality (See below)
The attention scores \(S_{i,j}\) are then normalized using the softmax function to produce the attention weights: \[ a_{ij} = \dfrac{e^{S_{i,j}}}{\sum_{k=1}^n e^{S_{i,k}}} \]
The \(a_{ij}\) indicate the relative importance of the \(j^{th}\) key vector to the \(i^{th}\) query vector.
The output of the attention mechanism is computed as a weighted sum of the value vectors: \[ \mathbf{z}_{i} = \sum_{j=1}^n a_{ij}\mathbf{v}_j \]
\(\mathbf{v}_j\) is the \(j^{th}\) value vector
\(\mathbf{z}_{i}\) is the output vector corresponding to the \(i^{th}\) query vector.
We can express this in matrix form as
\[ A(\mathbf{Q},\mathbf{K},\mathbf{V})= \mathrm{softmax}\left(\dfrac{\mathbf{QK}^T}{\sqrt{d_k}}\right) \]
The attention mapping is
The Functional Roles: a useful intuition is that they act as two different “filters” applied to the same input data:
\(W^K\) (The Key Matrix): intuitively, learns to describe a token so it can be “found” by relevant queries.
\(W^Q\) (The Query Matrix): intuitively, learns to encode what the current token needs from its context.
This is a simplifying explanation — \(W^Q\) and \(W^K\) are trained jointly and don’t have separately interpretable roles in general.
Empirically, it has been shown that different attention heads may specialize to recognizable syntactic/semantic relations, e.g. heads that reliably attend from verbs to their direct objects, or from determiners to nouns.1
The dot product \(q \cdot k\) for \(d_k\) dimensions is defined as:
\[ S = \sum_{i=1}^{d_k} q_i k_i \]
This is the same computation as a single entry \(\mathrm{score}_{i,j}\) of the \(QK^T\) matrix — here we drop the token indices \(i,j\) since the variance argument holds for any single query–key pair.
To find the variance of \(S\), we first look at the variance of a single term \(q_i k_i\):\[Var(q_i k_i) = E[(q_i k_i)^2] - (E[q_i k_i])^2\]Mean of the product: Since \(q_i\) and \(k_i\) are independent, \(E[q_i k_i] = E[q_i]E[k_i] = 0 \cdot 0 = 0\).
Why variance adds under independence. For any two random variables \(X, Y\): \[ \text{Var}(X+Y) = \text{Var}(X) + \text{Var}(Y) + 2\,\text{Cov}(X,Y) \] The covariance term vanishes when \(X\) and \(Y\) are independent, since \(\text{Cov}(X,Y) = \mathbb{E}[XY]-\mathbb{E}[X]\mathbb{E}[Y] = 0\) whenever \(X \perp Y\). This extends to a sum of \(d_k\) mutually independent terms: all cross-covariance terms vanish, leaving only the individual variances.
\[ \text{Var}(S) = \text{Var}\left(\sum_{m=1}^{d_k} q_m k_m\right) = \sum_{m=1}^{d_k} \text{Var}(q_m k_m) = \sum_{m=1}^{d_k} 1 = d_k \]
Recall the scaling rule for variance: for a constant \(c\), \(\text{Var}(cX) = c^2\,\text{Var}(X)\).
\[ \text{Var}\left(\frac{S}{\sqrt{d_k}}\right) = \left(\frac{1}{\sqrt{d_k}}\right)^2 \text{Var}(S) = \frac{1}{d_k}\cdot d_k = 1 \]
Recall the definition of softmax:
\[ \begin{bmatrix} 1.3 \\ 5.1\\ 2.2 \\ 0.7 \\ 1.1 \end{bmatrix} \rightarrow \dfrac{e^{z_i}}{\sum_{j=1}^K e^{z_j}} \rightarrow \begin{bmatrix} 0.02 \\ 0.90\\ 0.05 \\ 0.01 \\ 0.02 \end{bmatrix} \]
\[ \text{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right) \]
\[ \text{Softmax} \left( \frac{1}{\sqrt{d_k}} \times \underbrace{ \begin{bmatrix} q_1 \cdot k_1 & q_1 \cdot k_2 & \dots & q_1 \cdot k_n \\ q_2 \cdot k_1 & q_2 \cdot k_2 & \dots & q_2 \cdot k_n \\ \vdots & \vdots & \ddots & \vdots \\ q_n \cdot k_1 & q_n \cdot k_2 & \dots & q_n \cdot k_n \end{bmatrix} }_{\text{Raw Scores } (n \times n)} \right) = \underbrace{ \begin{bmatrix} \alpha_{1,1} & \alpha_{1,2} & \dots & \alpha_{1,n} \\ \alpha_{2,1} & \alpha_{2,2} & \dots & \alpha_{2,n} \\ \vdots & \vdots & \ddots & \vdots \\ \alpha_{n,1} & \alpha_{n,2} & \dots & \alpha_{n,n} \end{bmatrix} }_{\text{Attention Weights } (n \times n)} \]
In this resulting matrix:
\[ V = XW^V = \begin{bmatrix} v_{11} & v_{12} & \dots & v_{1d_v} \\ v_{21} & v_{22} & \dots & v_{2d_v} \\ \vdots & \vdots & \ddots & \vdots \\ v_{n1} & v_{n2} & \dots & v_{nd_v} \end{bmatrix}_{n \times d_v} \]
Now that we have a matrix of Attention Weights (\(\alpha\)), we use them to take a weighted average of the information stored in the Value matrix (\(V\)).
The Value Matrix (\(V\)): Just like \(Q\) and \(K\), the Value matrix is created by projecting the input \(X\) through a learnable weight matrix \(W^V\): \[\underbrace{V}_{n \times d_v} = \underbrace{X}_{n \times d} \times \underbrace{W^V}_{d \times d_v}\]
\(d\) is the dimension of the input embeddings (typically, \(d>d_k\))
The output dimension of attention is \(d_v\), i.e., attention’s output width is set entirely by the Value projection
The Value represents the actual “content” of the word.
We take our \(n \times n\) attention weights and multiply them by our \(n \times d_v\) Values.
\[\text{Output} = \underbrace{\text{Softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)}_{n \times n} \times \underbrace{V}_{n \times d_v}\]
To see what happens to Word 1, look at the first row of the multiplication:
\[\text{Output}_1 = \alpha_{1,1}v_1 + \alpha_{1,2}v_2 + \dots + \alpha_{1,n}v_n\]
Layer normalization:
Ba JL et al. (2016) Layer Normalization. arXiv 1607.06450
Two flavors:
The layer performs an Add and Norm operation:
Add is a Residual Connection (also called a Skip Connection).
Output: \[\text{Output} = X + Sublayer(X)\]
strictly element-wise addition, e.g., for token \(i\) and feature \(j\):
\[\text{Output}_{i,j} = x_{i,j} + \text{Sublayer}(X)_{i,j}\]
\[\frac{\partial(X + f(X))}{\partial X} = 1 + f'(X)\]
Norm
The normalization step ensures that values do no not explode1
\[ \text{LayerNorm}(Z) = \gamma \odot \left( \frac{Z - \mu}{\sqrt{\sigma^2 + \epsilon}} \right) + \beta\]
\[\text{Output}_j = (\gamma_j \cdot \hat{x}_j) + \beta_j\]
Singh P and Raman B (2025) The Geometry of Intelligence: Foundations of Transformer Networks in Deep Learning. January 2025. ISBN: 978-981-96-4705-7.
FFN:
\[ FFN(x) = \text{GELU}(xW_1 + b_1)W_2 + b_2 \]
activation functions
After matrix multiplication (linear), a non-linear activation function is applied, which makes the neural network a non-linear function, allowing it to achieve complex behavior. ReLu is the most widely use activation function (simple, fast to compute)
\[ \mathrm{ReLU}(x) = \max(0,x) \]
The first derivative of ReLU is
\[ \dfrac{d}{dx}\mathrm{ReLU}(x) = \begin{cases} x > 0 & 1 \\ x < 0 & 0 \\ x = 0 & \text{undefined but usually set to zero in code}\\ \end{cases} \]
\[\text{GELU}(x) = x \Phi(x) \approx 0.5x \left( 1 + \tanh \left( \sqrt{\frac{2}{\pi}} (x + 0.044715x^3) \right) \right)\]
\[\text{Layer Output} = \text{LayerNorm} \left( \underbrace{X_{\text{post-attn}}}_{\text{Base}} + \underbrace{\text{FFN}(X_{\text{post-attn}})}_{\text{FFN output}} \right) \]
Similar to the previous add & norm layer, this one has two purposes
Take home
This lecture introduced the Encoder architecture. - In the next lecture, we will introduce the decoder architecture and discuss how these models are trained.
Sources for this lecture include