Linear Algebra & Deep Learning Foundations for Sequence Models
Vector Spaces, Projections, Matrix Factorization, Numerical Softmax Stability, and the Limitations of Recurrence
Module 1: Linear Algebra & Deep Learning Foundations for Sequence Models
Before examining the Transformer architecture, we must understand the mathematical substrate upon which all modern sequence modeling rests: high-dimensional vector spaces, affine transformations, numerical stability in probability distributions, and the empirical failures of recurrent neural networks.
1.1 Vector Spaces, Dot Products, and Inner Product as Semantic Similarity
In natural language processing, discrete textual symbols (tokens) are mapped into continuous dense representations:
Where typically ranges from (GPT-2 Small) to (LLaMA-3 8B) up to (GPT-4 / Gemma large).
From Text to Vectors: The Embedding Lookup Walk-through
How does a raw word like "cat" transform into an activation vector in ?
- Tokenization: The raw string is mapped to a discrete vocabulary index via a lookup dictionary (e.g.,
"cat"ID ). - One-Hot Encoding: The index is represented as a sparse one-hot vector , where position is and all other entries are .
- Linear Projection / Table Indexing: The model stores an embedding matrix . Multiplying mathematically extracts the -th row of :
In practice, deep learning frameworks do not perform sparse matrix multiplication; they execute an array lookup into contiguous memory (nn.Embedding(vocab_size, d_model)).
Geometric Meaning of the Dot Product
Given two vectors , the Euclidean inner product is defined algebraically and geometrically as:
Where is the angle between the two vectors in -dimensional space.
Architecture FlowchartGenerating architectural diagram...
- When , the vectors are collinear and convey maximum directional alignment.
- When , the vectors are orthogonal; their dot product is zero, representing semantic independence.
- When , the vectors are diametrically opposed.
Cosine Similarity vs. Unnormalized Dot Product
While cosine similarity normalizes vectors:
Transformers deliberately use unnormalized dot products in self-attention because vector magnitude carries vital information—such as token rarity, syntactic salience, and prediction confidence.
1.2 Linear Projections & Learned Transformations (Q, K, V Geometry)
A raw token embedding cannot simultaneously serve as a search query, an index key, and an informative payload without representational interference.
Therefore, the Transformer applies three distinct linear transformations via learnable weight matrices:
Architecture FlowchartGenerating architectural diagram...
Concrete Numerical Toy Example of Q, K, V Projections
To ground these matrices in concrete arithmetic, consider a toy setting with and : Suppose token and token . Given projection matrices:
- Calculate Query for Token 1:
- Calculate Key for Token 2:
- Calculate Unscaled Dot Product:
- Scale by :
This demonstrates how learned projections transform raw token embeddings so that high alignment is learned dynamically rather than determined by arbitrary lexical coordinates.
Rank and Projection Subspaces
Because have rank at most , they project the high-dimensional representation into specialized lower-dimensional subspaces:
- encodes the interrogative intention of token .
- encodes the addressable metadata of token .
- The dot product evaluates how well token 's features satisfy token 's search demand.
1.3 Matrix Decomposition: SVD and Low-Rank Approximations
Any weight matrix of rank can be factored via Singular Value Decomposition (SVD):
Where:
- is an orthogonal matrix of left singular vectors.
- is a diagonal matrix of non-negative singular values .
- is an orthogonal matrix of right singular vectors.
Architecture FlowchartGenerating architectural diagram...
The Eckart-Young-Mirsky Theorem
For any integer , the optimal rank- approximation minimizing Frobenius error is obtained by truncating the sum at the top singular values:
This theorem directly justifies modern Low-Rank Adaptation (LoRA) and weight compression: overparameterized Transformer weight updates reside in an intrinsic subspace of remarkably low rank ().
Mathematical Mechanics of LoRA (Low-Rank Adaptation)
During fine-tuning, instead of updating all parameters in , LoRA freezes and injects a low-rank decomposition:
Where:
- and with rank .
- is a constant scaling hyperparameter (typically or ).
- Initialization Proof: is initialized with random Gaussian noise , while is initialized strictly to zero (). Consequently: This guarantees that fine-tuning begins exactly at the pre-trained model's output without introducing sudden catastrophic disruption.
1.4 The Softmax Operator, Overflow Prevention, and Temperature Scaling
The Softmax function converts unnormalized logits into a valid categorical probability distribution :
Numerical Catastrophe: Floating-Point Overflow
In IEEE 754 standard 32-bit float (fp32), the maximum representable value is . For 16-bit half precision (fp16 or bf16), overflow occurs at (fp16). If any , , leading to NaN during backward pass gradients.
Shift-Invariance & Safe Softmax
Softmax is strictly invariant to uniform scalar translation:
In all production engines (PyTorch, FlashAttention, TensorRT-LLM), is subtracted before exponentiation:
Guaranteeing and strictly bounding the exponent between .
Temperature Scaling Regimes
When generating text or computing attention, we introduce temperature :
- : Default calibrated model probabilities.
- (Argmax / Greedy): As temperature approaches zero, for all non-maximal logits. The probability distribution collapses into a Dirac delta (one-hot vector) centered on the single highest logit:
- (Uniform Random): As temperature grows arbitrarily large, . All tokens become equally probable regardless of model knowledge:
Architecture FlowchartGenerating architectural diagram...
Softmax Jacobian and Gradient Dynamics
The derivative of with respect to logit is:
When one logit dominates (), and , causing the gradient to vanish. This is why dot products in attention must be scaled by .
1.5 Sequential Bottlenecks: Why RNNs and LSTMs Failed at Scale
Prior to 2017, sequence learning relied on Recurrent Neural Networks (Elman RNNs, LSTMs, GRUs). The hidden state was computed recursively:
Architecture FlowchartGenerating architectural diagram...
1. Inability to Parallelize Across Sequences
Because has a strict temporal dependency on , training an -token sequence requires sequential matrix multiplications. On modern SIMD/GPU hardware with thousands of parallel tensor cores, this introduces catastrophic hardware under-utilization ( sequential steps).
2. Vanishing and Exploding Gradients Across Long Paths
By the chain rule, backpropagating an error from step back to step involves repeated products of the recurrent transition Jacobian:
If the largest eigenvalue of , , the gradient magnitude decays exponentially with path length:
If , the gradient explodes towards infinity. While LSTMs introduced additive cell memory paths to alleviate this, the computational graph length remained .
3. The Transformer Breakthrough: Maximum Path Length
The Transformer solves this fundamentally:
- Computational Path Length: Between any token and token , the path length through Self-Attention is strictly (one matrix multiplication), eliminating exponential gradient decay.
- Parallelism: All tokens across the entire sequence are processed concurrently via batch matrix multiplication on GPU tensor cores.
Core Academic References
- Golub & Van Loan (2013): Matrix Computations (4th ed.). Johns Hopkins University Press.
- Bengio, Simard & Frasconi (1994): Learning long-term dependencies with gradient descent is difficult. IEEE Transactions on Neural Networks, 5(2): 157–166.
- Hochreiter & Schmidhuber (1997): Long Short-Term Memory. Neural Computation, 9(8): 1735–1780.
- Goodfellow, Bengio & Courville (2016): Deep Learning: Numerical Computation & Numerical Stability. MIT Press.