Key terms for this tutorial
Here are the words that matter most in this tutorial. Come back here if a term feels fuzzy.
- gradient
- A vector of partial derivatives showing how much each parameter affects the loss.
- gradient descent
- An optimization algorithm that updates weights by moving them in the direction that lowers the loss.
- learning rate
- How far the optimizer moves the weights each step. Too big and training explodes; too small and it crawls.
- loss
- A number that measures how wrong the model is. Training tries to minimize loss.
- model
- A function with learnable parameters that maps inputs to outputs.
- optimizer
- An algorithm, like SGD or Adam, that updates model weights using gradients.
- parameter
- A learnable number inside a model. Modern models have millions or billions of them.
- tensor
- A multi-dimensional array of numbers, the basic data type in deep learning.
Convex vs non-convex loss surfaces
Linear regression has a convex bowl: any local minimum is global. Neural networks are non-convex, with saddles, plateaus, and many local minima. Yet gradient descent often finds good solutions because high-dimensional saddles are more common than true local minima.
The Hessian matrix of second derivatives tells you curvature. Where it has both positive and negative eigenvalues, you are at a saddle point, not a minimum.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Gradient Descent — Deep Dive'. Explain the section 'Convex vs non-convex loss surfaces' in plain English. Include simple analogies, vocabulary definitions, and a short example.
Momentum and adaptive optimizers
Momentum adds velocity to gradient descent. Instead of stopping at each step, the optimizer accumulates a moving average of past gradients, smoothing oscillations and accelerating through flat regions.
import torch
w = torch.tensor([5.0], requires_grad=True)
v = torch.zeros_like(w)
lr, beta = 0.1, 0.9
for step in range(10):
loss = w ** 2
loss.backward()
v = beta * v + w.grad
with torch.no_grad():
w -= lr * v
w.grad.zero_()
print(f'step {step}: w = {w.item():.4f}')
step 0: w = 4.0000 step 1: w = 3.0400 step 2: w = 2.2336 step 3: w = 1.6077 step 4: w = 1.1389 step 5: w = 0.7920 step 6: w = 0.5380 step 7: w = 0.3557 step 8: w = 0.2257 step 9: w = 0.1340
Line-by-line: momentum.py
Read this slowly. Each line does one small, concrete thing.
import torch— Import thetorchlibrary so we can use its built-in tools.w = torch.tensor([5.0], requires_grad=True)— Create a PyTorch tensor from raw Python numbers.for step in range(10):— Loop over the data one batch at a time.loss = w ** 2— Compute the loss, which measures how far the prediction is from the target.loss.backward()— Compute gradients: how much each weight contributed to the loss.with torch.no_grad():— Disable gradient computation during evaluation to save memory and speed.print(f'step {step}: w = {w.item():.4f}')— Print a result so we can see what the model learned.
Pop-in: Read the code one block at a time
Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.
Adam combines momentum with per-parameter learning rates. It keeps running estimates of the gradient mean and squared gradient, then divides the update by a moving standard deviation. That makes it robust to sparse gradients and different parameter scales.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Gradient Descent — Deep Dive'. Explain the section 'Momentum and adaptive optimizers' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.
Learning-rate schedules
A constant learning rate is rarely best. Warmup slowly raises the rate early to avoid early instability; cosine decay lowers it near the end so the model settles into a flat minimum.
import math
def cosine_lr(base_lr, step, warmup, total):
if step < warmup:
return base_lr * step / warmup
progress = (step - warmup) / (total - warmup)
return base_lr * 0.5 * (1 + math.cos(math.pi * progress))
for step in [0, 50, 100, 200, 400]:
print(f'{step}: {cosine_lr(1e-3, step, 100, 500):.6f}')
0: 0.000000 50: 0.000500 100: 0.001000 200: 0.000905 400: 0.000345
Line-by-line: schedule.py
Read this slowly. Each line does one small, concrete thing.
import math— Import themathlibrary so we can use its built-in tools.def cosine_lr(base_lr, step, warmup, total):— Define thecosine_lrfunction, which describes a step in the data or model pipeline.for step in [0, 50, 100, 200, 400]:— Loop over the data one batch at a time.print(f'{step}: {cosine_lr(1e-3, step, 100, 500):.6f}')— Print a result so we can see what the model learned.
Pop-in: Read the code one block at a time
Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Gradient Descent — Deep Dive'. Explain the section 'Learning-rate schedules' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.
Check yourself
When is momentum helpful?
Why does momentum accelerate through flat loss regions?
It accumulates velocity from consistent gradient directions, so small but repeated gradients add up into large steps.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Gradient Descent — Deep Dive'. The practice question 'When is momentum helpful?' asks: Why does momentum accelerate through flat loss regions? The answer is: It accumulates velocity from consistent gradient directions, so small but repeated gradients add up into large steps.. Explain the concept behind this in simple terms.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Gradient Descent — Deep Dive'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.
Three questions
1. Why are neural network loss surfaces harder than linear regression?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Gradient Descent — Deep Dive'. The quiz asks: Why are neural network loss surfaces harder than linear regression? The correct answer is: They are non-convex with saddles and plateaus. Explain why that answer is right and why the other choices are wrong, using a simple example.
2. What does Adam compute per parameter?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Gradient Descent — Deep Dive'. The quiz asks: What does Adam compute per parameter? The correct answer is: Moving averages of the gradient and its square. Explain why that answer is right and why the other choices are wrong, using a simple example.
3. What is warmup used for?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Gradient Descent — Deep Dive'. The quiz asks: What is warmup used for? The correct answer is: To slowly increase the learning rate and avoid early instability. Explain why that answer is right and why the other choices are wrong, using a simple example.
Keep learning
Now apply these optimizers to a real neural network.
Part of the CodeHS tutorial library.