πŸ”’ Prerequisite β€’ Mathematics

Linear Algebra for AI

Neural networks are built on matrix operations. Every layer, every transformation, every attention mechanism is linear algebra at its core. Understanding vectors and matrices unlocks the language of modern AIβ€”from embeddings to transformers.

⏱ Estimated reading time: 25-30 minutes

🎯 What You'll Learn

  • What vectors represent and how to perform operations on them
  • How dot products measure similarity (the foundation of attention)
  • What matrices are and why they represent transformations
  • How matrix multiplication works and why it's the core of neural networks
  • Key concepts: norms, normalization, broadcasting, and tensor shapes

1 Why Linear Algebra Matters for AI

Everything in deep learning is a tensorβ€”a multi-dimensional array of numbers. Images, text, audio, model weightsβ€”all are represented as tensors. Linear algebra is the mathematical language for manipulating these structures.

πŸ“ Everything is a Tensor

Images: [batch, channels, height, width] e.g., [32, 3, 224, 224] Text: [batch, sequence_length, embedding] e.g., [16, 512, 768] Audio: [batch, channels, samples] e.g., [8, 1, 16000] Weights: [input_features, output_features] e.g., [768, 3072]

πŸ€– The AI Connection

A single neural network layer is literally: y = Wx + b β€” a matrix multiplication plus a bias. When you hear "GPT has 175 billion parameters," those are 175 billion numbers stored in matrices. Modern GPUs exist specifically because they're incredibly fast at matrix operations.

πŸ’‘ Why Matrices?

Matrices let us apply the same transformation to many inputs at once (parallelization). Instead of processing one data point, we process a whole batch. This is why AI models run efficiently on GPUsβ€”they're designed for parallel matrix operations.

2 Vectors: The Building Blocks

A vector is an ordered list of numbers. In AI, vectors represent practically everything: words, images, features, gradients, and model parameters. The key insight is that vectors live in a space where geometric intuitions apply.

v = [v₁, vβ‚‚, v₃, ..., vβ‚™]
A vector with n components (lives in n-dimensional space)

Geometric Interpretation

      ↑ y
      β”‚
    4 ┼─────────────→ v = [3, 4]
      β”‚           β•±
      β”‚         β•±
      β”‚       β•±  ← Length (magnitude) = √(3Β² + 4Β²) = 5
      β”‚     β•±
      β”‚   β•±
      β”‚ β•± ← Direction = arctan(4/3) β‰ˆ 53Β°
    ──┼─────────────→ x
      0             3
      
    A 2D vector has both magnitude (length) and direction.
    AI uses vectors with hundreds or thousands of dimensions!
                    

A vector represents a point in space or a direction with magnitude

Vector Operations

πŸ“ Addition

[1, 2, 3] + [4, 5, 6] = [5, 7, 9]

Add corresponding elements. Geometrically: chain the arrows head-to-tail.

πŸ“ Scalar Multiplication

2 Γ— [1, 2, 3] = [2, 4, 6]

Multiply each element. Geometrically: stretch or shrink the vector.

πŸ“ Subtraction

[5, 7, 9] - [1, 2, 3] = [4, 5, 6]

Subtract corresponding elements. Gives the "difference" vector.

πŸ“ Element-wise Multiplication

[1, 2, 3] βŠ™ [4, 5, 6] = [4, 10, 18]

Multiply corresponding elements. Also called Hadamard product.

πŸ€– Word Embeddings

In NLP, every word is represented as a vector (typically 256-1024 dimensions). Similar words have similar vectors. The famous example:
vector("king") - vector("man") + vector("woman") β‰ˆ vector("queen")
This works because vector arithmetic captures semantic relationships!

3 Dot Product: Measuring Similarity

The dot product (also called inner product or scalar product) is perhaps the most important operation in AI. It takes two vectors and returns a single number that measures how "aligned" they are.

a Β· b = a₁b₁ + aβ‚‚bβ‚‚ + ... + aβ‚™bβ‚™ = Ξ£α΅’ aα΅’bα΅’
Multiply corresponding elements, then sum everything

πŸ“ Step-by-Step Example

a = [1, 2, 3] b = [4, 5, 6] a Β· b = (1 Γ— 4) + (2 Γ— 5) + (3 Γ— 6) = 4 + 10 + 18 = 32

Geometric Meaning

a Β· b = |a| Γ— |b| Γ— cos(ΞΈ)
Dot product = magnitudes Γ— cosine of angle between them

πŸ’‘ What is Cosine (cos)?

Cosine is a function that converts an angle into a number between -1 and +1. It measures "how much two directions align":

β€’ cos(0Β°) = 1 β†’ same direction (perfect alignment)
β€’ cos(90Β°) = 0 β†’ perpendicular (no alignment)
β€’ cos(180Β°) = -1 β†’ opposite directions

You don't need to calculate angles directlyβ€”the formula above does it for you. Just remember: cosine β‰ˆ "how aligned are these vectors?"

This formula reveals what the dot product actually measures:

  • a Β· b > 0: Vectors point in similar directions (angle < 90Β°)
  • a Β· b = 0: Vectors are perpendicular/orthogonal (angle = 90Β°)
  • a Β· b < 0: Vectors point in opposite directions (angle > 90Β°)
    Same direction       Perpendicular        Opposite direction
    (a Β· b > 0)          (a Β· b = 0)          (a Β· b < 0)
    
        β†— b                  ↑ b                    β†— a
       β•±                     β”‚
      β•±                      β”‚
     β†— a                   β†’ a                   ↙ b
    
    "Similar"            "Unrelated"           "Dissimilar"
                    

The dot product measures alignment between vectors

Cosine Similarity

To measure similarity independent of vector length, we normalize by the magnitudes:

cos(ΞΈ) = (a Β· b) / (|a| Γ— |b|)
Cosine similarity: ranges from -1 (opposite) to +1 (same direction)

πŸ“ Computing Cosine Similarity

a = [1, 2, 3] b = [4, 5, 6] |a| = √(1Β² + 2Β² + 3Β²) = √14 β‰ˆ 3.74 |b| = √(4Β² + 5Β² + 6Β²) = √77 β‰ˆ 8.77 cos(ΞΈ) = 32 / (3.74 Γ— 8.77) = 32 / 32.79 β‰ˆ 0.975 These vectors are very similar! (close to 1)

πŸ€– Where Dot Products Appear in AI

Attention Mechanisms: "How relevant is token A to token B?" is computed as a dot product of their representations.
Semantic Search: Find documents similar to a query by comparing embedding dot products.
Recommendations: "How much will user U like item I?" is often a dot product of their embeddings.
Every neural network layer uses dot products to combine inputs with weights.

4 Matrices: Tables of Numbers

A matrix is a 2D grid of numbers arranged in rows and columns. Think of it as a collection of vectors, or as a transformation that can rotate, scale, or project vectors.

                         ← n columns β†’
                         
         β”Œ                           ┐
     ↑   β”‚  a₁₁   a₁₂   ...   a₁ₙ   β”‚
     β”‚   β”‚  a₂₁   aβ‚‚β‚‚   ...   aβ‚‚β‚™   β”‚
  m rows β”‚  ...   ...   ...   ...   β”‚
     β”‚   β”‚  aβ‚˜β‚   aβ‚˜β‚‚   ...   aβ‚˜β‚™   β”‚
     ↓   β””                           β”˜
     
     Matrix A has shape (m Γ— n): m rows, n columns
     Element aα΅’β±Ό is in row i, column j
                    

A matrix is a 2D array of numbers with m rows and n columns

πŸ“ Notation Examples

A ∈ ℝ³ˣ² means A is a 3Γ—2 matrix (3 rows, 2 columns) β”Œ ┐ A = β”‚ 1 2 β”‚ A₁₁ = 1, A₁₂ = 2 β”‚ 3 4 β”‚ A₂₁ = 3, Aβ‚‚β‚‚ = 4 β”‚ 5 6 β”‚ A₃₁ = 5, A₃₂ = 6 β”” β”˜

Special Matrices

πŸ“ Identity Matrix (I)

β”Œ ┐ I = β”‚ 1 0 0 β”‚ β”‚ 0 1 0 β”‚ β”‚ 0 0 1 β”‚ β”” β”˜

1s on diagonal, 0s elsewhere. A Γ— I = I Γ— A = A (does nothing).

πŸ“ Transpose (Aα΅€)

β”Œ ┐ β”Œ ┐ A = β”‚ 1 2 β”‚ Aα΅€ = β”‚ 1 3 5 β”‚ β”‚ 3 4 β”‚ β”‚ 2 4 6 β”‚ β”‚ 5 6 β”‚ β”” β”˜ β”” β”˜

Rows become columns, columns become rows. Shape (mΓ—n) β†’ (nΓ—m).

πŸ“ Zero Matrix

β”Œ ┐ 0 = β”‚ 0 0 0 β”‚ β”‚ 0 0 0 β”‚ β”” β”˜

All elements are zero. A + 0 = A.

πŸ“ Diagonal Matrix

β”Œ ┐ D = β”‚ d₁ 0 0 β”‚ β”‚ 0 dβ‚‚ 0 β”‚ β”‚ 0 0 d₃ β”‚ β”” β”˜

Non-zero only on diagonal. Scales each dimension independently.

Matrix as Transformation

A key insight: multiplying a vector by a matrix transforms that vector. Different matrices perform different transformations: rotation, scaling, projection, etc.

Original vectors:           After transformation by A:

    ↑ y                         ↑ y
    β”‚    β†’                      β”‚      β†—
    β”‚   β•±                       β”‚    β•±
    β”‚  ↑                        β”‚  β†—
    β”‚                           β”‚β†—
    └──────→ x                  └──────→ x
    
    A matrix can rotate, stretch, shrink, flip, or shear vectors.
                    

Matrices transform vectors in various ways

πŸ€– Weight Matrices in Neural Networks

Each layer in a neural network has a weight matrix W. When input x passes through, the matrix transforms it: z = Wx. The network learns what transformation to apply by adjusting the values in W during training. A "7 billion parameter model" has 7 billion numbers distributed across many weight matrices.

5 Matrix Multiplication

Matrix multiplication is THE fundamental operation in deep learning. Every neural network layer, every attention head, every linear transformation is a matrix multiplication. Master this, and you understand the computational heart of AI.

The Rule: Dot Products of Rows and Columns

Cα΅’β±Ό = (row i of A) Β· (column j of B)
Each element of C is a dot product
        A (2Γ—3)         B (3Γ—2)         C (2Γ—2)
    β”Œ         ┐     β”Œ       ┐     β”Œ                   ┐
    β”‚ 1  2  3 β”‚  Γ—  β”‚ 7  8  β”‚  =  β”‚ C₁₁   C₁₂        β”‚
    β”‚ 4  5  6 β”‚     β”‚ 9  10 β”‚     β”‚ C₂₁   Cβ‚‚β‚‚        β”‚
    β””         β”˜     β”‚ 11 12 β”‚     β””                   β”˜
                    β””       β”˜
    
    C₁₁ = [1,2,3] Β· [7,9,11]  = 1Γ—7 + 2Γ—9 + 3Γ—11 = 58
    C₁₂ = [1,2,3] Β· [8,10,12] = 1Γ—8 + 2Γ—10 + 3Γ—12 = 64
    C₂₁ = [4,5,6] Β· [7,9,11]  = 4Γ—7 + 5Γ—9 + 6Γ—11 = 139
    Cβ‚‚β‚‚ = [4,5,6] Β· [8,10,12] = 4Γ—8 + 5Γ—10 + 6Γ—12 = 154
    
             β”Œ         ┐
        C =  β”‚ 58   64 β”‚
             β”‚ 139 154 β”‚
             β””         β”˜
                    

Each element of C comes from a dot product of a row from A and column from B

Shape Rules (Critical!)

(m Γ— n) Γ— (n Γ— p) = (m Γ— p)
Inner dimensions must match! Result has outer dimensions.

⚠️ The #1 Bug in Deep Learning

Shape mismatches cause most errors in neural network code. If A is (64, 512) and B is (256, 128), you cannot multiply themβ€”the inner dimensions (512 and 256) don't match. Always check shapes: print(tensor.shape) is your best debugging tool.

πŸ“ Shape Practice

Can we multiply? What's the result shape? (3 Γ— 4) Γ— (4 Γ— 2) = (3 Γ— 2) βœ“ Valid, inner = 4 (5 Γ— 3) Γ— (3 Γ— 7) = (5 Γ— 7) βœ“ Valid, inner = 3 (2 Γ— 5) Γ— (3 Γ— 4) = ??? βœ— Invalid! 5 β‰  3 (4 Γ— 4) Γ— (4 Γ— 4) = (4 Γ— 4) βœ“ Square matrices

⚠️ Pitfall: Matrix Multiplication Dimensions

You can only multiply matrices A and B if the inner dimensions match:

β€’ Matrix A is (m Γ— n)
β€’ Matrix B is (n Γ— p)
β€’ The result is (m Γ— p)

If the inner dimensions do not match, the multiplication is not defined.

Valid examples:
β€’ (2Γ—3) Β· (3Γ—4) β†’ (2Γ—4) βœ“ (inner dimensions: 3 and 3 match)
β€’ (5Γ—2) Β· (2Γ—1) β†’ (5Γ—1) βœ“ (inner dimensions: 2 and 2 match)

Invalid examples:
β€’ (2Γ—3) Β· (2Γ—4) β†’ ❌ (inner dimensions: 3 and 2 do not match)
β€’ (4Γ—5) Β· (3Γ—2) β†’ ❌ (inner dimensions: 5 and 3 do not match)

Matrix-Vector Multiplication

A special and very common case: multiplying a matrix by a vector. This is exactly what happens in a neural network layer.

     Neural Network Layer: y = Wx + b
     
         W (3Γ—2)         x (2Γ—1)           b (3Γ—1)      y (3Γ—1)
     β”Œ         ┐       β”Œ     ┐           β”Œ     ┐     β”Œ     ┐
     β”‚ w₁₁ w₁₂│       β”‚ x₁  β”‚           β”‚ b₁  β”‚     β”‚ y₁  β”‚
     β”‚ w₂₁ wβ‚‚β‚‚β”‚   Γ—   β”‚ xβ‚‚  β”‚     +     β”‚ bβ‚‚  β”‚  =  β”‚ yβ‚‚  β”‚
     β”‚ w₃₁ w₃₂│       β””     β”˜           β”‚ b₃  β”‚     β”‚ y₃  β”‚
     β””         β”˜                        β””     β”˜     β””     β”˜
     
     y₁ = w₁₁·x₁ + w₁₂·xβ‚‚ + b₁
     yβ‚‚ = w₂₁·x₁ + wβ‚‚β‚‚Β·xβ‚‚ + bβ‚‚
     y₃ = w₃₁·x₁ + w₃₂·xβ‚‚ + b₃
     
     Transforms 2D input β†’ 3D output
                    

A neural network layer is just a matrix-vector multiplication

Important Properties

πŸ“ Not Commutative!

AB β‰  BA (in general) Order matters! Applying transform A then B is different from B then A.

πŸ“ Associative

(AB)C = A(BC) Order of operations doesn't matter (useful for optimization).

πŸ€– Why GPUs Excel at Matrix Multiplication

Matrix multiplication is "embarrassingly parallel"β€”each element of the output can be computed independently. A GPU has thousands of cores that can compute these dot products simultaneously. A 4090 GPU can perform ~80 trillion operations per second, mostly matrix multiplications. This is why training large models requires GPUs.

6 Key Concepts for AI

Vector Norms (Length/Magnitude)

The norm of a vector measures its "size" or length. Different norms measure size differently.

||v||β‚‚ = √(v₁² + vβ‚‚Β² + ... + vβ‚™Β²)
L2 norm (Euclidean length) β€” most common
||v||₁ = |v₁| + |vβ‚‚| + ... + |vβ‚™|
L1 norm (Manhattan distance)

Normalization

Normalizing a vector means scaling it to have length 1 (a unit vector). This is crucial for stable training and fair comparisons.

vΜ‚ = v / ||v||β‚‚
Divide by length to get a unit vector

πŸ“ Normalizing a Vector

v = [3, 4] ||v||β‚‚ = √(9 + 16) = 5 vΜ‚ = [3/5, 4/5] = [0.6, 0.8] Check: |vΜ‚| = √(0.36 + 0.64) = √1 = 1 βœ“

πŸ€– Layer Normalization

Transformers use "layer normalization" which normalizes activations. This stabilizes training by keeping values in a reasonable range. Without normalization, values can explode (overflow) or vanish (underflow) as they pass through many layers.

Broadcasting Advanced

Broadcasting is a NumPy/PyTorch feature that lets you perform operations on arrays with different shapes. The smaller array is "broadcast" (virtually replicated) to match the larger one. (You'll use this laterβ€”just know it exists for now.)

πŸ“ Broadcasting Examples

# Matrix + Vector (vector added to each row) A = [[1, 2, 3], v = [10, 20, 30] [4, 5, 6]] A + v = [[11, 22, 33], [14, 25, 36]] # Scalar operations A * 2 = [[2, 4, 6], [8, 10, 12]] # Different but compatible shapes (3, 4, 1) + (1, 4, 5) β†’ (3, 4, 5) ← expanded to match

Common Tensor Shapes in AI

πŸ“ Shape Reference

# Data Shapes Image batch: (batch, channels, height, width) [32, 3, 224, 224] Text batch: (batch, sequence_len, embed_dim) [16, 512, 768] Audio batch: (batch, samples) [8, 16000] # Model Parameter Shapes Linear layer: (in_features, out_features) [768, 3072] Embedding table: (vocab_size, embed_dim) [50000, 768] Attention weights: (batch, heads, seq, seq) [16, 12, 512, 512] # Named Dimensions (helpful convention) B = batch size T = sequence length (time) D = embedding dimension H = number of attention heads V = vocabulary size

7 Practice Problems

Test your understanding with these problems!

✏️ Problem 1: Dot Product

Compute: [2, -1, 3] Β· [4, 2, -1]
Click to reveal solution β–Ό
[2, -1, 3] Β· [4, 2, -1] = (2 Γ— 4) + (-1 Γ— 2) + (3 Γ— -1) = 8 + (-2) + (-3) = 3

✏️ Problem 2: Matrix Multiplication Shape

If A is (4, 3) and B is (3, 5), what is the shape of AB?
Click to reveal solution β–Ό
(4 Γ— 3) Γ— (3 Γ— 5) = (4 Γ— 5) Inner dimensions (3, 3) match βœ“ Result has shape (4, 5)

✏️ Problem 3: Matrix Multiplication

Compute AB where: A = [[1, 2], B = [[5, 6], [3, 4]] [7, 8]]
Click to reveal solution β–Ό
AB₁₁ = [1,2]Β·[5,7] = 5+14 = 19 AB₁₂ = [1,2]Β·[6,8] = 6+16 = 22 AB₂₁ = [3,4]Β·[5,7] = 15+28 = 43 ABβ‚‚β‚‚ = [3,4]Β·[6,8] = 18+32 = 50 AB = [[19, 22], [43, 50]]

✏️ Problem 4: Cosine Similarity

Find the cosine similarity between [1, 0] and [1, 1]
Click to reveal solution β–Ό
a = [1, 0], b = [1, 1] a Β· b = 1Γ—1 + 0Γ—1 = 1 |a| = √(1Β² + 0Β²) = 1 |b| = √(1Β² + 1Β²) = √2 β‰ˆ 1.414 cos(ΞΈ) = 1 / (1 Γ— 1.414) β‰ˆ 0.707 This corresponds to a 45Β° angle.

🎯 Key Takeaways

  • Vectors are ordered lists of numbers that represent points or directions in space
  • Dot products measure similarity/alignmentβ€”they're the foundation of attention
  • Matrices are 2D arrays that represent transformations
  • Matrix multiplication (mΓ—n) Γ— (nΓ—p) = (mΓ—p)β€”inner dimensions must match
  • A neural network layer is just: y = Wx + b (matrix multiply + bias)
  • Shape debugging is the most common taskβ€”always check tensor.shape

You're Ready!

With these linear algebra foundations, you're prepared for the AI course. You'll use these ideas throughout:

  • Module 2.1-2.2: Neural network architecture (matrix operations)
  • Module 3.1: Embeddings (vectors representing meaning)
  • Module 3.2-3.3: Attention mechanisms (dot products for similarity)
  • Module 4.1-4.2: Generative models (latent vector spaces)