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(dkQK⊤)V
Where:
Q∈Rn×dk,K∈Rm×dk,V∈Rm×dv,dk,softmax(⋅),Similarity matrix: S=QK⊤,Scaling: Sscaled=dkS,Weight matrix: A=softmax(Sscaled),Output: Attention(Q,K,V)=AVQuery matrixKey matrixValue matrixDimension of key vectors, used for scalingNormalize each row to obtain weights
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,v2∈R
Generally, a vector of length d:
v=v1v2⋮vd∈Rd
Vectors have the following basic operations:
Addition: element-wise addition
u+v=u1+v1u2+v2⋮ud+vd
Scalar multiplication: each component of the vector multiplied by a scalar
cv=cv1cv2⋮cvd
Dot product: measures the similarity between two vectors
u⋅v=i=1∑duivi
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=1∑mαivi,αi≥0,i=1∑mα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.
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(dkQK⊤)V
The correspondence in the code is as follows.
Q, K, V Generation
Q=WQx,K=WKx,V=WVx
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=8
dk=dhead=nheadsdmodel=8512=64
The projection results are split into 8 heads, each with dimension
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=dkS
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)
Corresponding to alpha = F.softmax(scores_scaled, dim=-1). Since
e−∞=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 (你)Position 1 (好)Position 2 (世)Position 3 (界):[1.000,0,0,0]:[0.073,0.927,0,0]:[0.273,0.475,0.251,0]:[0.069,0.333,0.514,0.084]
Weighted Sum Output
output=AV
Corresponding to out = alpha @ V, followed by merging heads and projecting output through W_O.
Feed-Forward Network (FFN)
dff=4×dmodel=2048
Consistent with the original paper.
Residual Connections and Layer Normalization
Equivalent to the
x+Sublayer(LayerNorm(x))
Pre-LN variant.
Scale Comparison
This example uses only 4 tokens
dmodel=512,nlayers=6,nheads=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
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.