๐Ÿงญ AI Roadmap โ€บ 00 ยท Math & Foundations โ€บ 02 ยท Calculus & Optimization
โ† 00 ยท Math Foundations Hub

Calculus & Optimization for AI

How neural networks learn: Loss functions, partial derivatives, the calculus chain rule (Backpropagation), and gradient descent optimization (AdamW).

๐Ÿ”ด CORE PILLAR 02
๐Ÿ“‰ Loss Functions ($\mathcal{L}$) ๐Ÿ”„ Gradients ($\nabla \mathcal{L}$) โ›“๏ธ Chain Rule โšก AdamW Optimizer
๐Ÿ’ก The Optimization Principle
Every AI model begins with random weight matrices. Calculus is the mathematical steering wheel: it computes the exact partial derivative $\frac{\partial \mathcal{L}}{\partial w}$ for every single parameter, telling the optimizer whether to nudge that weight up or down to reduce prediction error.
01

Loss Functions: Measuring Prediction Error

Cross-Entropy Loss in Language Models

In language modeling, the training objective is Next-Token Prediction. When the target token is $y$ and the model predicts probability $P(y)$, the error is calculated using Cross-Entropy Loss:

$$\mathcal{L} = -\log P(y_{\text{target}})$$

If the model predicts $P(\text{target}) = 0.99$, $\mathcal{L} = -\log(0.99) \approx 0.01$ (nearly zero penalty). If it predicts $P(\text{target}) = 0.01$, $\mathcal{L} = -\log(0.01) \approx 4.60$ (massive penalty).

๐ŸŽฏ Where This Directly Applies:
Module 04: Pretraining Evaluating loss curves across trillions of tokens to monitor convergence.
Module 08: DPO & RLHF Calculating log-odds ratio loss between chosen vs. rejected answers.
02

Gradients & Backpropagation (The Chain Rule)

How Error Flows Backward Through 96 Transformer Layers

Because Transformer networks are deep composite functions $y = f(g(h(x)))$, finding the gradient for early layers requires the Calculus Chain Rule:

$$\frac{\partial \mathcal{L}}{\partial w} = \frac{\partial \mathcal{L}}{\partial y} \cdot \frac{\partial y}{\partial h} \cdot \frac{\partial h}{\partial w}$$

PyTorch automates this through its Autograd computational graph engine, generating backward gradient tensors for all active parameters.

03

Gradient Descent & Learning Rate Dynamics

Nudging Parameters Down the Loss Valley

Once the gradient $\nabla \mathcal{L}$ is computed, parameters are updated via:

$$W_{t+1} = W_t - \eta \cdot \nabla \mathcal{L}$$

Where $\eta$ is the Learning Rate. If $\eta$ is too high, the model explodes into `NaN`; if too low, training takes decades.

โšก Interactive Gradient Descent Simulator Loss $\mathcal{L}(w) = (w - 2.5)^2 + 0.5$
This page 0:00
This session 0:00
Total (all pages) 0:00
Today 0:00
โ–ถ Running
๐Ÿ“Š View all study stats โ†’
0:00 studying