Contents31 sections
Foreword & Mathematical Disclaimer:
Many believe that studying large language models demands mastery of arcane graduate-level mathematics: manifold learning, tensor calculus, and functional analysis.
In reality, the mathematical soul of modern Transformer operators (RoPE, Attention, RMSNorm, SwiGLU) is built almost entirely on high-school foundations: plane vectors, trigonometry, complex numbers, polar coordinates, basic derivatives, and means and variances!
This special topic serves as an essential precursor and deep supplement to Chapter 02 | Implementing Modern Transformer Architecture from Scratch.
Whether you are a high school student, a university freshman, or a practicing engineer whose academic math has faded, as long as you remember , , and the imaginary unit , grab a pen and paper—this guide will walk you through deriving every single core formula behind modern LLMs from first principles!
===================================================================================
高中数学到现代 Transformer 知识跃迁路线图
===================================================================================
【高中数学积木】 【大模型核心算子】
1. 平面向量与点乘 (a·b = |a||b|cosθ) ───────────► 词向量相似度 & Attention 寻人打分
2. 虚数 i 与复数乘法几何旋转 ────────────────────► RoPE 旋转位置编码 (相对距离涌现)
3. 随机变量均值与独立方差加法 ──────────────────► Attention 缩放因子 1/√d_k 推导
4. 导数切线与指数对数运算 ──────────────────────► RMSNorm 尺度不变性 & SiLU 平滑门控
5. 条件概率连乘与对数转化 ──────────────────────► 因果语言模型交叉熵损失 (MLE)
===================================================================================Part 1: Vectors and Spatial Mapping — From 2D Arrows to 512-Dimensional Semantic Spaces
1.1 High-School Plane Vectors: Arrows with Magnitude and Direction
In introductory physics and plane geometry, we first encounter vectors:
- A vector is represented by a directed line segment, such as the arrow from origin to point , denoted as ;
- Magnitude (Length): Calculated via the Pythagorean theorem: ;
- Dot Product (Inner Product): Given two vectors and , their dot product formula is:
Where represents the angle between the two arrows.
💡 Physical Intuition of the High-School Dot Product:
- If both arrows point in the exact same direction (), , yielding the maximum positive value;
- If both arrows are perpendicular / orthogonal (), , yielding 0 (completely uncorrelated);
- If both arrows point in opposite directions (), , yielding the maximum negative value.
This is the ultimate tool LLMs use to measure semantic similarity: the larger the dot product, the closer their spatial orientations, and the more semantically related the two tokens are!
1.2 Scaling Up: From a 2D Plane to 512-Dimensional Hyperspace
High-school chalkboards only draw 2D () or 3D () coordinate frames. In large language models, we simply expand the coordinate axes from 3 to 512 axes! A token embedding is no longer , but an array of 512 real numbers:
1.2.1 How to Calculate Multi-Dimensional Vector Magnitude? High-Dimensional Pythagorean Theorem
Many students find 512-dimensional space bewildering. In reality, its distance calculation shares the exact same mathematical DNA with middle-school Pythagorean geometry:
- 2D Plane Vector length (magnitude):
- 3D Space Vector length (diagonal across a cuboid):
- Generalized to 512D Hyperspace magnitude:
(In higher mathematics, this magnitude is termed the Norm (Euclidean Norm), denoted as )
💡 Crucial Mathematical Identity: Magnitude Equals "Square Root of Self Dot Product"
Examine the summation inside the square root closely:
This constitutes the most foundational identity in vector algebra:
The dot product of any vector with itself equals the square of its Euclidean length!
Concrete Numerical Walkthrough:
Suppose we have a miniature 4-dimensional vector:
- Square each component:
- Sum of squares:
- Take the square root:
This 4D vector starting at the origin possesses an exact spatial length of 5.0!
🔗 Direct Connection to the RMSNorm Operator:
Compare the norm formula with the upcoming Root Mean Square (RMS):
- Vector Norm:
- Root Mean Square (RMS):
RMSNorm fundamentally measures the average energy scale of the high-dimensional vector evenly amortized across every dimension!
1.2.2 High-Dimensional Dot Products and Cosine Similarity
The high-dimensional dot product follows the exact same rule: multiply corresponding elements pairwise and sum them up:
From the dot product definition , dividing by the magnitudes yields the gold-standard metric for comparing token semantic similarity—Cosine Similarity:
- Intuition after Normalization (Unit Vectors):
If we normalize each vector to unit length 1 beforehand (i.e. ), the denominator becomes identically 1:
At this point, semantic similarity between two words equals their direct dot product!
- In 512-dimensional semantic space, vectors for "King" and "Queen" form an acute angle (), while "King" and "Tractor" are nearly orthogonal ()!
1.3 The Physical Essence of Matrix Multiplication: Changing Coordinate Perspectives
Many students memorize matrix multiplication as mechanical row-by-column rituals (C[i][j] = sum(A[i][k] * B[k][j])) without understanding its geometric soul.
Let us return to high-school plane geometry and understand matrix multiplication through the intuitive lens of basis vectors!
1.3.1 Cornerstones of Coordinate Frames: Two Standard Basis Arrows
In a standard 2D Cartesian grid, any point or vector is expressed as a linear combination of two fundamental unit basis vectors:
- Horizontal basis: (step 1 unit right)
- Vertical basis: (step 1 unit up)
What does a vector actually represent?
Intuitive explanation: Walk 3 steps along the horizontal basis, then 2 steps along the vertical basis!
===================================================================================
高中标准网格与向量 (3, 2)
===================================================================================
y (纵向基底 e2)
▲
3 │
2 │ • v = (3, 2) [向右走3步,向上走2步]
1 │ ▲ │
0 ┼───┼───┼───► x (横向基底 e1)
0 1 2 3
===================================================================================1.3.2 What Is a Matrix? Each Column Dictates Where a Basis Vector Lands!
Here is the key revelation: a matrix represents a warped, rotated, and scaled new coordinate grid!
Consider a matrix:
Look closely at the first and second columns of this matrix:
- First Column : Declares where the original rightward basis arrow is mapped!
- Second Column : Declares where the original upward basis arrow is mapped!
When computing matrix multiplication , applying distributive laws reveals:
💡 The Moment of Intuition:
- In the original space, vector was located at "(3, 2) in the old basis";
- Matrix slanted and stretched the entire coordinate frame;
- After transformation, the point occupies the same relative position, but in standard coordinates its new position is !
The physical essence of matrix multiplication is taking a flat grid and performing a global rotation, stretch, and shear (linear mapping)!
===================================================================================
矩阵变换的几何效果 (方格网格被拉伸倾斜)
===================================================================================
【变换前的原始网格】 【经过矩阵 M 变换后的新空间】
y y' (第二列 [1, 2]^T)
▲ ▲
│ /
┌───┼───┐ ┌───/───┐
│ │ │ / / /
├───┼───┤ /───/───/
│ │ │ / / /
────┴───┼───┴────► x ───┴───/───┴────► x' (第一列 [2, 0]^T)1.3.3 Experiencing Three Classic Physical Matrix Transformations
① Pure Rotation Matrix: Rotating Space 90 Degrees Counterclockwise
- First column : Maps the horizontal arrow to point straight up;
- Second column : Maps the vertical arrow to point left;
- Any vector multiplied by it preserves length while rotating counterclockwise!
② Scaling Matrix: Adjusting Dimensions Like an Audio Equalizer
- First column : Amplifies horizontal coordinates by ;
- Second column : Compresses vertical coordinates by half ();
- Any vector multiplied by it gets stretched horizontally and flattened vertically.
③ Projection & Dimensionality Reduction Matrix: Flattening 3D Space into a 2D Shadow
- Input is a 3D coordinate vector ;
- Matrix multiplication output: ;
- Physical effect: Flattens the -axis to zero, preserving only the 2D shadow—just as sunlight projects a 3D person onto flat pavement.
1.3.4 Back to LLMs: Why Does Transformer Multiply Matrices Everywhere?
Now let us bring these insights back into Transformer's 512-dimensional hyperspace:
When the tokenizer converts a word (e.g. "apple") into a 512D embedding, it begins as a raw conglomerate feature bundle:
- It blends fruit features (sweet, red, crisp, juicy);
- It blends technology corporate features (Tim Cook, iPhone, ticker AAPL, Nasdaq);
- It blends classical physics associations (Sir Isaac Newton, falling under an apple tree).
Given this heterogeneous 512D vector, how does the model decide which facets to prioritize in a specific context? Matrix multiplications provide the answer!
===================================================================================
大模型中三大权重矩阵的“聚光灯多视角投影”
===================================================================================
原始 512 维词向量 X (包含水果、公司、物理全部知识)
│
┌─────────────────────────┼─────────────────────────┐
▼ 乘以矩阵 W_q ▼ 乘以矩阵 W_k ▼ 乘以矩阵 W_v
[ 寻人空间投影 ] [ 名片空间投影 ] [ 情报空间投影 ]
│ │ │
产生 Query 向量 产生 Key 向量 产生 Value 向量
(我此刻在找什么特征?) (我身上能提供什么特征?) (如果选我,我给什么干货?)
===================================================================================- Matrix (Query Perspective Lens):
Acts as a specialized geometric lens, rotating and scaling features to amplify dimensions relevant to the current question, producing the Query vector for probing other tokens;
- Matrix (Key Perspective Lens):
Projects raw features into a business-card identifier space, producing the Key vector that exposes public indexable tags to inquiring queries;
- Matrix (Substantive Content Lens):
Extracts core semantic substance, producing the Value vector that gets weighted and mixed into the final attention representation;
- in FFN:
First projects 512D features up into a richer 1,408-dimensional space (for granular knowledge lookup), then uses to project back down to 512 dimensions!
💡 How Does the LLM Learn Such Precise Perspective Projections?
Each number in these weight matrices appears as an ordinary floating-point parameter. Geometrically, however, every parameter governs an axis stretch factor or rotation angle! During pretraining, backpropagation and the calculus chain rule adjust these millions of dials, tuning them into the most perceptive geometric lenses for understanding human language!
Part 2: Complex Numbers & Geometric Rotation — High-School Derivation of RoPE
Rotary Position Embedding (RoPE) is celebrated as one of the most brilliant mathematical inventions in modern LLMs. Behind its formidable reputation lies only high-school complex multiplication and trigonometric addition formulas!
2.1 High-School Complex Numbers: The Rotational Geometry of Imaginary
In algebra, to solve , mathematicians defined the imaginary unit . A complex number has the form ( real, imaginary).
On the complex Gauss plane:
- The horizontal axis is real, vertical is imaginary. Complex is point ;
- Multiply by : , reaching —a counterclockwise rotation;
- Multiply by again: , reaching —another rotation;
- Multiply by again: , reaching —another rotation;
- Multiply by once more: , returning to the start!
Core High-School Mathematical Insight: In complex numbers, multiplication is geometrically identical to rotation!
===================================================================================
复数平面上连续乘 i 的 90度 几何旋转
===================================================================================
虚数轴 (Im)
▲
│ (0, 1) = i
│ ▲
│ │ 乘 i (逆时针 90°)
│ │
(-1, 0) = -1 ◄─────────────┼─────────────► (1, 0) = 1
乘 i (又转 90°) │ │ 实数轴 (Re)
│ │
│ ▼ 乘 i (再转 90°)
│ (0, -1) = -i
▼
===================================================================================2.2 Euler's Formula: Rotating at Arbitrary Angles
What if we wish to rotate by an arbitrary angle rather than fixed increments? Master mathematician Leonhard Euler provided the crown jewel theorem of mathematics—Euler's Formula:
Consider a complex number of unit magnitude :
- When : (pointing along the positive real axis);
- When (): (matching our earlier rotation!);
- When (): , rearranging to Euler's famous identity: !
Thus, is a pure rotation operator: multiplying any complex number by it preserves exact magnitude while rotating counterclockwise by radians!
2.3 Pen-and-Paper Proof: Why Multiplying Complex Numbers Adds Angles
Using standard high-school trigonometric addition formulas, let us derive Euler multiplication by hand:
Let two rotation operators be and . Multiplying them as polynomials:
Since , separating real and imaginary components:
Behold the beauty! Under complex multiplication, intricate geometric rotations simplify into elementary addition in the exponent!
2.4 The Climax: How RoPE Naturally Yields Relative Distance
Now let us derive the mathematical centerpiece of RoPE!
Suppose a sentence contains two tokens:
- Token 1 at position (), with Query vector , represented as complex ;
- Token 2 at position (), with Key vector , represented as complex .
Step 1: Apply Positional Rotation
Rotate each vector according to its positional index:
- Rotate by :
- Rotate by :
Step 2: Compute Attention Inner Product
In vector geometry, the dot product equals the real part of the complex conjugate product:
(Note: denotes complex conjugate, where , and in polar form )
Substitute rotated vectors:
Group real magnitudes and complex exponentials:
Apply common-base exponent addition:
Extract the real part:
Derivation complete! Notice the term in the exponent: the absolute positional indices and naturally collapse into the relative distance difference ! This guarantees:
- If , the relative offset is ;
- If the entire sentence shifts right by 100 tokens (), the offset is still !;
- Their dot product attention score remains strictly identical! This is the rigorous mathematical proof behind RoPE's shift invariance and length extrapolation!
Part 3: Statistics & Variance — Why Attention Must Divide by
In the standard self-attention equation:
初学者往往对分母上的 感到莫名其妙:为什么要平白无故开个根号除一下?
3.1 Foundational High-School Statistics: Expectation and Variance
- In basic statistics, we measure random distributions with two metrics:
- Expectation (Mean) : The average center of mass of the distribution;
- Variance : The degree of dispersion / spread around the mean (Standard deviation ).
Statistical Properties of Two Independent Random Variables:
If two random variables and are independent with zero mean ():
- Variance of Product:
- Variance of Sum:
3.2 Calculating Variance: The Catastrophic Avalanche without Dividing by
In our 0.04B model, each attention head has dimension .
因为前面的数据都经过了归一化,我们合理假设每一个分量都是标准的均值为 0、方差为 1 的变量:
- Under LayerNorm/RMSNorm, each component and behaves as an independent zero-mean unit-variance variable:
Let us derive the expectation and variance of the single-dimension product :
- 每一对单项乘积的方差:
- 64 项相加后的总方差:
- 总打分结果的标准差:
😱 The Catastrophe Occurs:
The variance of the attention score explodes to , meaning its standard deviation is !
- (nearly 500 million!)
- Outcome: The single maximum token captures 99.9999% of attention probability, while all other tokens collapse to 0.0000%!
Even worse is the gradient: the derivative of Softmax is:
When , derivative is ; when , derivative is ! Conclusion: All backpropagated gradients vanish to zero! The network suffers derivative paralysis and stops learning!
3.3 The Antidote: Resetting Variance with Scaling
To prevent gradient death, mathematicians scale the score by , leveraging :
Standard deviation is brought back to ! Scores distribute smoothly between and , Softmax yields healthy probabilities, derivatives stay in active responsive regimes, and parameters update smoothly!
Part 4: Calculus & Limits — RMSNorm Scale Invariance & Causal Masking
4.1 Scale Invariance Derivation of RMSNorm
In Chapter 02 we met RMSNorm:
Why does RMSNorm not require absolute amplitude tracking?
Suppose an preceding layer experiences an unexpected gain spike, amplifying signals by (turning into ):
- Numerator becomes: ;
- Denominator RMS calculation:
- Divide numerator by denominator:
The arbitrary constant 100 cancels out completely! This is mathematical scale invariance: regardless of input scale drift, RMSNorm outputs remain rock-solid.
4.2 Limit Analysis: Why Causal Masks Drive Future Probabilities to Zero
During self-attention, token 2 must never peek at token 3. In code, future positions are masked with negative infinity (). According to exponential properties (), as exponentially:
Substituting into Softmax: the future numerator term strictly converges to 0. Regardless of the denominator, future tokens receive exactly attention weight—a mathematically airtight guarantee against future leakage.
Part 5: Information Theory & Probability Chains — The Origin of Autoregressive Cross-Entropy
How does training a model to predict single "next tokens" produce fluent, cohesive long-form prose and complex reasoning?
5.1 The High-School Conditional Probability Chain Rule
From high-school probability theory, the conditional probability formula states:
Extended to a sequence of tokens , the joint probability of the entire text is the sequential chain product of conditional step probabilities:
5.2 The Magic of Logarithms: Converting Multiplication into Addition
We want the overall probability to be as large as possible (Maximum Likelihood Estimation, MLE). However, multiplying thousands of tiny probabilities () collapses numbers to , underflowing computer floating-point registers to absolute zero!
The monotonically increasing nature of the natural logarithm saves us:
Taking natural logarithms converts multiplication into clean addition! Adding a negative sign transforms maximizing probability into standard deep learning Loss Minimization:
This is the mathematical core of autoregressive training: shifting the target sequence by 1 position and calculating Negative Log-Likelihood (NLL) at each step is mathematically identical to Cross-Entropy Loss!
Part 6: High-School Math to LLM Core Formula Reference Table
Let us synthesize all derivations into a structured reference matrix connecting high-school mathematics directly to modern Transformer operators:
| High-School Math Concept | Classic Mathematical Formula | Industrial LLM Implementation | Core Engineering & Physical Problem Solved | | Plane Vector Dot Product | | Attention Score Matrix | Measures semantic association between tokens in high-dimensional embedding spaces. | | Complex Numbers & Euler Identity | | RoPE Rotary Embeddings | Derives relative distance offsets through pure geometric rotation, enabling robust sequence extrapolation. | | Independent Variable Variance Addition | | Attention Scaling Factor | Neutralizes 64-dimensional variance explosion, preventing Softmax derivative saturation and vanishing gradients. | | Gaussian Exponential Limits | | Causal Mask Assigned to Negative Infinity | Airtight shielding of future tokens, preventing information leakage during autoregressive training. | | Root Mean Square (RMS) | | Pre-RMSNorm Normalization Layers | Delivers scale invariance while discarding redundant mean computation, stabilizing gradient highways across 12 layers. | | Conditional Probability Chain Rule | | Autoregressive Causal Cross-Entropy Loss | Rigorously decomposes whole-document generation into single next-token prediction steps. |
💡 Next Step Guidance:
Armed with these mathematical foundations, return with confidence to Chapter 02 | Implementing Modern Transformer Architecture from Scratch and see how these laws guide billions of transistors in code!
REFERENCES
References
Series
Building an LLM from scratch