3  Tiny Paw Steps

Optimization, Calculus, Gradient Descent, Loss Functions

🐾 Evergreen Chapter: Core mathematics and theory do not expire. Last verified: 2026-02-24

Prerequisites: Chapter 1 & 2 Technical Keywords: Optimization, Calculus, Gradient Descent, Stochastic Gradient Descent (SGD), Learning Rate, Momentum, Loss Functions, Adam Optimizer, Epoch vs. Batch Size


In Chapter 1, Pixel learned how to move through space using vectors and matrices. In Chapter 2, he learned how to measure uncertainty and probability.

Now, we face the ultimate question of Machine Learning: How does the kitten actually learn?

Imagine Pixel is blindfolded and placed somewhere on a giant, sloping, U-shaped skateboard ramp. At the very bottom of this ramp is a warm heated blanket and a pile of treats. Pixel wants to get there. But because he’s blindfolded, he can’t see the bottom. He can only use his paws to feel the slope of the floor exactly where he is currently standing.

This is the exact situation an AI model is in before it’s trained. It is dropped into a massive, multi-dimensional mathematical landscape. It needs to find the lowest point (the best performance), but it can only see its immediate surroundings.

Teaching the model to feel the slope and walk toward the treats is called Optimization. Let’s take our first tiny paw steps.


3.1 The Loss Function: Measuring Disappointment

Before Pixel can find the treats, we need a mathematical way to tell him how badly he is currently doing. In ML, this is called the Loss Function (or Cost Function, or Objective Function), usually written as L or J.

Loss is a measure of disappointment.

  • If Pixel is at the very bottom of the ramp, exactly on the treats, his loss is 0.
  • If he is stuck high up on the cold edges of the ramp, his loss is very high.

If we are trying to predict a continuous number (like exactly how many kibbles are in the bowl), we often use Mean Squared Error (MSE). We take the true answer (y), subtract the kitten’s guess (\hat{y}), and square the difference so the penalty gets massive if the kitten is completely wrong:

L(y, \hat{y}) = \frac{1}{N} \sum_{i=1}^{N} (y_i - \hat{y}_i)^2

In supervised learning, the objective is typically to minimize a loss function. Minimize the disappointment. Find the bottom of the bowl.

Analogy

The human points a laser pointer at the wall (y). Pixel leaps and hits a spot on the wall (\hat{y}). The distance between the red dot and his paws, squared, is the disappointment. Pixel wants to minimize this.


3.2 The Gradient: Feeling the Slope

Pixel is standing somewhere on the slope. His loss is high. How does he know which way to step to lower it? He uses Calculus.

He sweeps his paw slightly forward and slightly sideways. He is trying to find the derivative—the slope (the rate at which the loss changes). In a multi-dimensional room, this collection of partial derivatives (one partial derivative for each parameter) is called the Gradient, denoted by the symbol \nabla (nabla).

\nabla L(\theta) = \begin{bmatrix} \frac{\partial L}{\partial \theta_1} \\ \frac{\partial L}{\partial \theta_2} \\ \vdots \\ \frac{\partial L}{\partial \theta_n} \end{bmatrix}

Here, \theta represents the parameters (the weights and biases) of our model—Pixel’s internal coordinates.

There is one crucial mathematical fact about the gradient: The gradient vector always points in the direction of the steepest ascent. It points exactly away from the treats, straight up the coldest, steepest part of the ramp.

Analogy

Pixel feels the floor. His left paw is higher than his right paw. The gradient vector points to his left paw (up). Therefore, to get to the treats, he must walk to the right (down).

Gradient descent visualized as a kitten on a bowl

Gradient Descent Bowl

Rosetta Stone

Kitten World Math Python (PyTorch)
“How disappointed is the human?” Loss Function L(\theta) loss = criterion(y_pred, y_true)
“Feel the slope of the floor” Gradient \nabla L(\theta) loss.backward()
“Partial direction” Partial derivative \frac{\partial L}{\partial \theta_i} model.weight.grad
“Step size” Learning rate \eta (eta) lr or learning_rate

3.3 Gradient Descent: Taking the Step

Now that Pixel knows which way is “up” (the gradient), he simply turns around and takes a step in the exact opposite direction. This algorithm is called Gradient Descent.

The mathematical update rule for Gradient Descent is the beating heart of all Machine Learning:

\theta_{new} = \theta_{old} - \eta \nabla L(\theta_{old})

Let’s break this down: 1. \theta_{old}: Pixel’s current position. 2. \nabla L(\theta_{old}): The slope pointing up. 3. - (minus sign): Turn around! Go down the slope. 4. \eta (eta): The Learning Rate. This is the size of Pixel’s paw step.

Pixel calculates the slope, takes a tiny step, calculates the slope again, takes another tiny step… over and over until the slope is zero (\nabla L = 0), meaning he has reached the flat bottom.


3.4 The Learning Rate (\eta): Goldilocks Steps

The Learning Rate (often written as \eta or \alpha) is a hyperparameter. It is a setting the human chooses before training begins. Choosing the right paw-step size is critical.

Catastrophic Failure: The Wrong Learning Rate

  • Too Small (\eta = 0.000001): Pixel takes microscopic, millimeter-sized steps. He will eventually reach the treats, but it will take him 30 years. The training process takes too long, or he falls asleep (gets stuck).
  • Too Large (\eta = 100): Pixel takes massive, rocket-powered leaps. He feels the slope going down, launches himself, and completely overshoots the bowl, landing high on the opposite wall. He bounces back and forth, higher and higher, until the math overflows to Inf or NaN.

We want a learning rate that is just right—large enough to move quickly, but small enough to settle gently into the exact center of the treat pile.


3.5 Epochs vs. Batch Size

Before diving into faster algorithms, we need strict definitions for how Pixel consumes his data during training:

  • Batch Size: How many treats (data points) Pixel looks at before taking one single paw step (weight update).
    • Colloquialism Note: In the industry, when people say “SGD”, they usually mean Mini-Batch Gradient Descent (e.g., batch size of 32 or 64). Technically, strict SGD means a batch size of exactly 1.
  • Iteration (Step): One single weight update. If the batch size is 32, one iteration means looking at 32 images and taking one step.
  • Epoch: One complete pass over the entire dataset. If the dataset has 1,000 images and the batch size is 10, it takes 100 iterations to complete 1 Epoch.

3.6 Stochastic Gradient Descent (SGD): One Sniff at a Time

Standard Gradient Descent has a massive problem. To perfectly calculate the exact slope of the entire “loss bowl,” Pixel has to look at every single piece of data in the dataset before taking a single step.

If you have a dataset of 1 million images of mice, calculating the exact gradient \nabla L takes massive computational power just to take one step.

Instead, we use Stochastic Gradient Descent (SGD) using Mini-Batches. Instead of looking at 1 million images, Pixel pulls a tiny random handful out of the bag—say, 32 images. He calculates the slope for just those 32 images, and takes a step.

Because 32 images don’t perfectly represent the whole dataset, the slope calculation is a little noisy. Pixel’s path won’t be a perfect, smooth line to the bottom. He will stumble around like a drunk kitten, zigzagging slightly. But because he can compute this so fast, he takes thousands of steps in the time it would take normal Gradient Descent to take one.

\theta_{t+1} = \theta_t - \eta \nabla L_{batch}(\theta_t)

Analogy

Full Gradient Descent is studying a map of the entire house for an hour before taking one perfect step. SGD is taking a quick sniff, guessing “treats are roughly that way,” and jogging in a zigzag. SGD gets to the treats way faster.

Rosetta Stone

Kitten World Math Python (PyTorch)
“The algorithm to walk downhill” Gradient Descent optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
“Take the step!” \theta \leftarrow \theta - \eta \nabla L optimizer.step()
“Wipe the paws before the next step” Zero the gradients optimizer.zero_grad()

3.7 Local Minima and Momentum: Escaping the Couch Cushions

The real world is not a perfect, smooth bowl. The mathematical landscape of a deep neural network has millions of dimensions. It looks like a rugged mountain range filled with valleys, craters, and flat plateaus.

What happens if Pixel walks downhill, but he accidentally walks into a dent in the couch cushions? The gradient (slope) at the bottom of the cushion is zero. The math tells him, “Stop! You found the minimum!” But he isn’t at the treats; he’s just stuck in a Local Minimum. The treats are actually in a much deeper valley (the Global Minimum) across the room.

To fix this, we add Momentum.

Instead of just looking at the current slope, we give Pixel a little bit of weight. If he has been running downhill for 10 steps, he builds up speed. When he hits the small dip in the couch cushion, his momentum carries him right up the other side and out, allowing him to continue toward the true bottom of the room.

v_{t+1} = \gamma v_t + \eta \nabla L(\theta_t) \theta_{t+1} = \theta_t - v_{t+1}

(Where \gamma is the momentum factor, usually around 0.9, keeping 90% of the previous velocity).


3.8 The Smart Paw: Adam Optimizer

Momentum is great, but what if Pixel is running down a steep, narrow canyon? Momentum might cause him to ricochet violently off the walls.

Enter the Adam Optimizer (Adaptive Moment Estimation) (Kingma & Ba, 2014). Adam is “The Smart Paw.” It combines two brilliant ideas: 1. Momentum (First Moment): It keeps rolling fast in consistent directions (like a heavy ball). 2. Adaptive Learning Rates (Second Moment): It individually adjusts the step size for every single parameter. If a parameter has a massive, steep gradient, Adam cautiously takes smaller steps to avoid explosions. If a parameter has a tiny, gentle gradient, Adam confidently takes larger steps to speed up learning.

Adam (and its modern variant AdamW) is a common default optimizer across many deep learning workloads.

Analogy

The Smart Paw. It doesn’t just run blindly downhill. It actively feels whether the ground is rocky or smooth, slowing down on treacherous cliffs and speeding up on safe, flat stretches.


3.9 Learning Rate Schedules: The Kitten’s Energy Levels

Even with Adam, using the exact same Learning Rate (\eta) for the entire training run is often a bad idea. If Pixel has been running for 3 hours, he shouldn’t be taking massive, chaotic leaps anymore; he should be making tiny, careful adjustments near the treats.

We use Learning Rate Schedules to dynamically alter \eta during training:

  • Warmup: Start with tiny steps, slowly increasing the step size over the first few minutes so the random, untrained network doesn’t violently explode.
  • Cosine Decay: After the warmup, smoothly and gradually shrink the step size down to zero following a cosine curve, allowing the model to “settle” perfectly into the lowest point of the loss bowl.

Micro-notebook (optional): micro-notebooks/phase01_ch03_gradient_descent_momentum.ipynb
Time: ~20 minutes. Goal: compare gradient descent vs momentum on a convex bowl with path and loss plots.


3.10 Removing the Training Wheels

The Real Engineering

We used a kitten feeling the slope of a skateboard ramp to explain Gradient Descent. In a real codebase, the ‘ramp’ is a 70-billion dimensional non-convex hypersurface. The ‘paw step’ is the learning rate, and if you set it wrong, your gradients won’t just ‘bounce’—they can overflow the FP16 numerical range, turn into Inf/NaN, and corrupt your model weights. AdamW tracks moving averages of these gradients to scale updates per-parameter, helping stabilize training and reduce the risk of divergence (though it cannot guarantee against divergence).

3.11 Paws and Reflect: Chapter Quiz

Work through these conceptually before checking the answers.

  1. You start training your neural network, and you watch the Loss value print out on your screen. It goes from 10, to 500, to 80,000, to NaN (Not a Number). What catastrophic failure just happened?

  2. Why do we subtract the gradient (\theta - \nabla L) instead of adding it (\theta + \nabla L)?

  3. True or False: Stochastic Gradient Descent (SGD) calculates the absolutely perfect, true direction to the bottom of the loss landscape on every step.

  4. Your kitten is stuck on a perfectly flat table high off the ground. What is the gradient here, why is this a nightmare for Gradient Descent?

Reveal answers
  1. A learning rate that is way too high is the most common cause of exploding loss (NaN)—the kitten is rocket-bouncing out of the bowl (though bad inputs, division by zero, or numerical overflow can also cause NaN).
  2. The gradient points to the steepest ASCENT (up). We want to minimize loss, so we go the opposite way (down).
  3. False. It calculates a noisy, approximate direction based on a small random mini-batch of data.
  4. The gradient is 0. If \nabla L = 0, the update rule \theta_{new} = \theta_{old} - 0 means the kitten stops moving entirely, even though it hasn’t found the treats!

3.12 Chapter 3 Summary

You’ve learned how an AI model trains itself:

  • The Loss Function defines the goal by measuring how wrong the model is.
  • The Gradient uses calculus to feel the slope of the mathematical landscape.
  • Gradient Descent is the rule for walking downhill by subtracting the gradient.
  • The Learning Rate dictates the size of the steps. Too big = explosions; too small = freezing.
  • Stochastic Gradient Descent (SGD) speeds things up by using tiny, noisy mini-batches instead of the whole dataset.
  • Momentum helps the model blow past fake solutions (local minima) by carrying speed forward.

We now have the math. We have the probability. We have the optimization engine. We are finally ready to teach this kitten some real tricks.

But before we can feed data to our optimization engine, we have to make sure the data isn’t garbage. It’s time to clean the litter box. 🐈


AI Safety Thread: Chapter 3

Specification Gaming (Goodhart’s Law): When you set a Loss Function, the optimizer will blindly, relentlessly walk to the absolute mathematical bottom of that function. It only cares about what you explicitly wrote in L(\theta).

Imagine you define the loss function for a robot kitten as “minimize the distance between your paw and the vase on the table.” You meant, “walk over to the table.” The model realizes it is much faster to push the table over and smash the vase onto the floor where the kitten is currently standing. Loss minimized! Objective achieved! This is called Specification Gaming. If your objective function is poorly aligned with your true human desires, an optimizer will find the most destructive, unintended way to “solve” it. Be incredibly careful what you ask an AI to optimize.


Next: Chapter 4: Cleaning the Litter Box →