arrow_back All articles

The AI Compass: Gradients & The Mountain of Loss

William Golovlev · 2 min read AI/ML
The AI Compass: Gradients & The Mountain of Loss

We have our radio knobs (weights) and our scorecard (loss). But with 1,000 knobs, you can’t just guess which way to turn each one. You need a compass. That’s the gradient: it tells the model which direction is downhill toward a better score.

The mountain in the fog

You’re standing on a foggy mountain peak, trying to reach a warm cabin in the valley.

You can’t see the cabin (the perfect answer), but you can feel the tilt of the ground under your boots. The gradient is a measurement of that tilt. It tells you which way is up, so you know to step the other way.

Step size (learning rate)

Even with a compass, you have to pick how big a stride to take. In AI that’s the learning rate (lr).

Too small and you take baby steps; you’ll be on that mountain forever. Too big and you leap blindly, maybe right over the valley and onto a different mountain.

Back to the code

Remember requires_grad from the tensors post? This is where it pays off. Because PyTorch tracked the history of our tensors, it can calculate the gradient for us automatically.

# The "Magic" button
loss.backward()

# Now our coeffs have a "compass" attached to them!
print(coeffs.grad)

Each knob gets its own gradient. If a knob’s gradient is positive, turning that knob up would make the loss worse, so we turn it down. That’s why the update step is coeffs.sub_(coeffs.grad * lr): subtract the gradient, scaled by the step size.

The “zero grad” mystery

You’ll see coeffs.grad.zero_() in my code. That’s because gradients accumulate: each backward() call adds to whatever is already there. If you don’t wipe the compass after every step, the model follows directions from your last position and your current one at the same time. It’s like trying to go north and south at once.

Why this matters

The gradient is the difference between guessing and optimizing. We’re not changing numbers at random. Every adjustment moves the loss downhill, step by step, until it’s as low as it’ll go.

Next, we put it all together in the complete training loop and follow this compass to the valley.


This is part 4 of my AI fundamentals series. If you missed the earlier posts on tensors, loss functions, and weights and biases, start there.

Let me know what you think on LinkedIn, and stay tuned for the final video in this series where we run the complete training loop!

#Machine Learning#Gradients#AI Tutorial#Neural Networks#Optimization