For the complete documentation index, see llms.txt. This page is also available as Markdown.

20.2 Mathematical Foundations of Transformers with Code Examples

Mathematical Foundations of Artificial Intelligence

In 2017, Vaswani et al. proposed a sequence transduction model based entirely on attention mechanisms, discarding recurrence and convolutions—the Transformer. This section strictly follows the original paper to reconstruct all its mathematical foundations and supplements necessary background knowledge.

Many core machine learning models fundamentally rely on Linear Algebra principles for representation and computation. In practice, data rarely appears as simple single values; it typically manifests as datasets, i.e., collections of large numbers of data points. Linear algebra provides tools for effectively organizing, processing, and analyzing such data, enabling practitioners to represent structured data (such as tabular data) and unstructured data (such as images or video) through objects like vectors, matrices, and tensors.

Uncertainty Quantification (UQ) aims to quantify and reduce uncertainties in modeling and simulation of physical systems; when certain factors of a system are unknown, it attempts to provide confidence levels for research results.

Statistician George Box once said, "All models are wrong, but some are useful."

Attention Definition

The mathematical definition of Scaled Dot-Product Attention proposed by Vaswani et al. in the 2017 Transformer paper has at its core a weighted sum, implemented through Query, Key, and Value matrices. The standard definition of attention is as follows:

Attention(Q,K,V)=softmax(QKdk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\Biggl(\frac{Q K^\top}{\sqrt{d_k}}\Biggr) V

Where:

QRn×dk,Query matrixKRm×dk,Key matrixVRm×dv,Value matrixdk,Dimension of key vectors, used for scalingsoftmax(),Normalize each row to obtain weightsSimilarity matrix: S=QK,Scaling: Sscaled=Sdk,Weight matrix: A=softmax(Sscaled),Output: Attention(Q,K,V)=AV\begin{array}{rl} Q \in \mathbb{R}^{n \times d_k}, & \text{Query matrix} \\ K \in \mathbb{R}^{m \times d_k}, & \text{Key matrix} \\ V \in \mathbb{R}^{m \times d_v}, & \text{Value matrix} \\ d_k, & \text{Dimension of key vectors, used for scaling} \\ \mathrm{softmax}(\cdot), & \text{Normalize each row to obtain weights} \\ \text{Similarity matrix: } S = Q K^\top, & \\ \text{Scaling: } S_\mathrm{scaled} = \frac{S}{\sqrt{d_k}}, & \\ \text{Weight matrix: } A = \mathrm{softmax}(S_\mathrm{scaled}), & \\ \text{Output: } \mathrm{Attention}(Q,K,V) = A V & \end{array}

Definition of Vectors

Mathematically, a vector is an ordered array that represents a quantity with both magnitude and direction. For example, a two-dimensional vector can be written as:

v=[v1v2],v1,v2R\mathbf{v} = \begin{bmatrix} v_1 \\ v_2 \end{bmatrix}, \quad v_1, v_2 \in \mathbb{R}

Generally, a vector of length d:

v=[v1v2vd]Rd\mathbf{v} = \begin{bmatrix} v_1 \\ v_2 \\ \vdots \\ v_d \end{bmatrix} \in \mathbb{R}^d

Vectors have the following basic operations:

  • Addition: element-wise addition

u+v=[u1+v1u2+v2ud+vd]\mathbf{u} + \mathbf{v} = \begin{bmatrix} u_1 + v_1 \\ u_2 + v_2 \\ \vdots \\ u_d + v_d \end{bmatrix}
  • Scalar multiplication: each component of the vector multiplied by a scalar

cv=[cv1cv2cvd]c \mathbf{v} = \begin{bmatrix} c v_1 \\ c v_2 \\ \vdots \\ c v_d \end{bmatrix}
  • Dot product: measures the similarity between two vectors

uv=i=1duivi\mathbf{u} \cdot \mathbf{v} = \sum_{i=1}^{d} u_i v_i

Weighted Sum

Given vectors v₁,…,vₘ and corresponding weights α₁,…,αₘ, where the weights are non-negative and sum to 1, the output vector o is their weighted sum.

o=i=1mαivi,αi0,i=1mαi=1\mathbf{o} = \sum_{i=1}^{m} \alpha_i v_i, \quad \alpha_i \ge 0, \quad \sum_{i=1}^{m} \alpha_i = 1

This is the basic operation of selectively aggregating information from multiple sets of vectors. Attention performs exactly this kind of weighted sum, but the weights are determined by the query vector.

Query, Key, Value Vectors

Query vector: qRdkKey vector set: k1,k2,,kmRdkValue vector set: v1,v2,,vmRdvSimilarity: si=qki,i=1,,mWeights: αi=exp(si)j=1mexp(sj),i=1,,mOutput vector: output=i=1mαivi\begin{array}{rl} \text{Query vector: } & q \in \mathbb{R}^{d_k} \\ \text{Key vector set: } & k_1, k_2, \dots, k_m \in \mathbb{R}^{d_k} \\ \text{Value vector set: } & v_1, v_2, \dots, v_m \in \mathbb{R}^{d_v} \\ \text{Similarity: } & s_i = q \cdot k_i, \quad i = 1, \dots, m \\ \text{Weights: } & \alpha_i = \frac{\exp(s_i)}{\sum_{j=1}^{m} \exp(s_j)}, \quad i = 1, \dots, m \\ \text{Output vector: } & \text{output} = \sum_{i=1}^{m} \alpha_i v_i \end{array}

Similarity and Softmax

Using dot product to measure the similarity between query and key:

si=qkis_i = q \cdot k_i

Then converting these similarities to probabilities:

αi=exp(si)j=1mexp(sj)\alpha_i = \frac{\exp(s_i)}{\sum_{j=1}^{m} \exp(s_j)}

Thus, the values corresponding to the most relevant keys receive larger weights.

Vector-Matrix Form

Stacking m value vectors into matrix V, key matrix K, and query matrix Q, we obtain the matrix form of Attention:

VRm×dv,KRm×dk,QRn×dkS=QKSscaled=SdkA=softmax(Sscaled)Attention(Q,K,V)=AV\begin{array}{rl} V \in \mathbb{R}^{m \times d_v}, \quad K \in \mathbb{R}^{m \times d_k}, \quad Q \in \mathbb{R}^{n \times d_k} & \\ S = Q K^\top & \\ S_\mathrm{scaled} = \frac{S}{\sqrt{d_k}} & \\ A = \mathrm{softmax}(S_\mathrm{scaled}) & \\ \mathrm{Attention}(Q,K,V) = A V & \end{array}

Program Example

The following example learns dynamic associations of character sequences through the attention mechanism in continuous vector space, completing the autoregressive generation of the "你好世界" (Hello World) sequence.

Example program output:

The above code implements a miniature GPT (autoregressive language model): given "你" it predicts "好", given "你好" it predicts "世", and so on. After 1000 epochs of training, the cross-entropy loss dropped from 2.033882 to 0.000001, and the model precisely learned the shift relationship of the sequence ['你', '好', '世', '界']['好', '世', '界', '你'].

The model strictly conforms to the standard mathematical definition of Scaled Dot-Product Attention:

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

The correspondence in the code is as follows.

Q, K, V Generation

Q=WQx,K=WKx,V=WVxQ = W_Q \, x,\quad K = W_K \, x,\quad V = W_V \, x

In the source code, Q = self.W_Q(x), K = self.W_K(x), V = self.W_V(x) — all three are obtained through linear projection from the same input x, which is self-attention. Since:

dmodel=512,nheads=8d_{\mathrm{model}} = 512, \quad n_{\mathrm{heads}} = 8
dk=dhead=dmodelnheads=5128=64d_k = d_{\mathrm{head}} = \frac{d_{\mathrm{model}}}{n_{\mathrm{heads}}} = \frac{512}{8} = 64

The projection results are split into 8 heads, each with dimension

dk=64d_k = 64

(code: Q.view(B, T, self.n_heads, self.d_head).transpose(1, 2)).

The output only shows Q, K, V, scores, and alpha for the first attention head (head=0), allowing readers to trace the complete computation chain.

Similarity and Scaling

S=QK,Sscaled=SdkS = Q K^\top, \qquad S_\mathrm{scaled} = \frac{S}{\sqrt{d_k}}

Corresponding to the source code scores = Q @ K.transpose(-2, -1) and scores_scaled = scores / math.sqrt(self.d_head).

Causal Mask

The upper triangle is set to -∞, forcing position i to only attend to positions 0,…,i: this is the fundamental constraint of autoregressive models — when predicting the next token, future information must not be accessed in advance. The -inf in the scaled matrix is a direct manifestation of this constraint.

Softmax Normalization

A=softmax(Sscaled)A = \mathrm{softmax}(S_\mathrm{scaled})

Corresponding to alpha = F.softmax(scores_scaled, dim=-1). Since

e=0e^{-\infty} = 0

the weights at masked positions are zero; the remaining positions are non-negative and sum to 1, forming a valid probability distribution:

Position 0 (你):[1.000,0,0,0]Position 1 (好):[0.073,0.927,0,0]Position 2 (世):[0.273,0.475,0.251,0]Position 3 (界):[0.069,0.333,0.514,0.084]\begin{array}{rl} \text{Position 0 (你)} &: [1.000,\, 0,\, 0,\, 0] \\ \text{Position 1 (好)} &: [0.073,\, 0.927,\, 0,\, 0] \\ \text{Position 2 (世)} &: [0.273,\, 0.475,\, 0.251,\, 0] \\ \text{Position 3 (界)} &: [0.069,\, 0.333,\, 0.514,\, 0.084] \end{array}

Weighted Sum Output

output=AV\mathrm{output} = A V

Corresponding to out = alpha @ V, followed by merging heads and projecting output through W_O.

Feed-Forward Network (FFN)

dff=4×dmodel=2048d_\mathrm{ff} = 4 \times d_\mathrm{model} = 2048

Consistent with the original paper.

Residual Connections and Layer Normalization

Equivalent to the

x+Sublayer(LayerNorm(x))x + \mathrm{Sublayer}(\mathrm{LayerNorm}(x))

Pre-LN variant.

Scale Comparison

This example uses only 4 tokens

dmodel=512,nlayers=6,nheads=8d_\mathrm{model} = 512, \quad n_\mathrm{layers} = 6, \quad n_\mathrm{heads} = 8

This is completely consistent with the base configuration of the original Transformer paper, demonstrating that even with an extremely small-scale sequence, as long as the mathematical structure is correct, the Transformer can converge perfectly.

Exercises

  1. What limitation of traditional recurrent neural networks in processing long sequences does the self-attention mechanism in the Transformer architecture address? Please explain the core idea of the attention mechanism in your own words.

Last updated