Skip to main content
Derivatives & Rates of Change

Derivatives & Rates of Change

Your Challenge: The Pricing Problem

You just launched your online store selling wireless headphones. Exciting! But now you face a critical decision: What price should you charge? You experiment with different prices over several weeks:
  • **Week 1 (30/pair):1,000customersbought!But...yourprofitwasonly30/pair)**: 1,000 customers bought! But... your profit was only 10,000
    • “Great sales, but I’m barely making money after costs ($20/pair)”
  • **Week 2 (100/pair):Only200customersbought.Profit:100/pair)**: Only 200 customers bought. Profit: 16,000
    • “Better profit per sale, but I’m losing too many customers!”
  • **Week 3 (50/pair):800customers.Profit:50/pair)**: 800 customers. Profit: 24,000
    • “Getting better… but is this the best I can do?”
Your Question: “There must be a sweet spot - a price that maximizes my profit. But how do I find it without testing every single price?”

The Slow Way (What You’re Doing Now)

You could test 100 different prices, one per week. That would take 2 years and cost you thousands in lost revenue!

The Fast Way (What You’ll Learn)

There’s a better approach: Derivatives Instead of blindly testing prices, derivatives tell you:
  • At $30: “Increase price → profit will go UP”
  • At $75: “Perfect! Any change makes profit go DOWN”
  • At $100: “Decrease price → profit will go UP”
Result: You find the optimal price (75)inminutes,notyears.Yourprofitjumpsto75) in minutes, not years. Your profit jumps to 30,250/month!

What You’ll Be Able To Do

By the end of this module, you’ll answer questions like: Your Business: What price maximizes YOUR profit?
Your Learning: How many hours should YOU study for maximum score?
Your ML Models: How should YOU adjust weights to reduce errors?
Your Life: What’s YOUR optimal speed to minimize fuel consumption?
Your tool: Derivatives - the mathematical way to find optimal solutions.
Estimated Time: 3-4 hours
Difficulty: Beginner
Prerequisites: Basic algebra
You’ll Build: Your own pricing optimizer, learning rate finder, and simple neural network

Your Problem: Finding the Pattern

Let’s model your business mathematically and visualize your pricing landscape: Your Pricing Landscape What this shows:
  • The green curve is your profit at different prices
  • Red dots are the prices you tested
  • The gold star is the optimal price ($75)
  • Arrows show which direction the derivative tells you to move
Your Insight: “The graph shows a hill! I need to find the peak. But how?”

Enter: The Derivative (Your Solution)

What You Need to Know

At any price, you need to answer: “If I increase my price by $1, does my profit go up or down?” This is EXACTLY what a derivative tells you! Derivative = Rate of Change
Output:
Your Reaction: “Wow! At 50,Ishouldincreasemyprice.Eachdollarincreaseadds50, I should increase my price. Each dollar increase adds 490 to my profit!”

What Is a Derivative? (The Intuitive Explanation)

Everyday Analogy: Your Car’s Speedometer

Think about driving a car: Position = where you are (e.g., mile marker 50)
Speed = how fast your position is changing (e.g., 60 mph)
Acceleration = how fast your speed is changing (e.g., +5 mph/second)
The speedometer shows your derivative! It tells you: “Right now, at this exact moment, you’re going 60 mph.”

The Thermostat Analogy

Here is another way to think about it that connects directly to ML. A thermostat measures the rate at which the room temperature is changing. If the temperature is rising fast (large positive derivative), the thermostat backs off. If it is falling (negative derivative), the thermostat cranks up the heat. The thermostat does not care about the absolute temperature as much as the direction and speed of change. A neural network’s training loop works identically. The derivative of the loss function is the “thermostat reading” for each weight. It tells the optimizer: “This weight is making the error grow fast — pull it back.” That feedback signal is what transforms a pile of random numbers into a model that recognizes faces, translates languages, or drives cars. Mathematically:
  • Position = f(t)f(t) (function of time)
  • Speed = f(t)f'(t) (derivative of position)
  • Acceleration = f(t)f''(t) (derivative of derivative)

Mathematical Definition (Now It Makes Sense!)

Derivative = Rate of change
“If I increase x by a tiny amount, how much does f(x) change?”
Formula: f(x)=limh0f(x+h)f(x)hf'(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h} In plain English:
  1. Move a tiny bit to the right (x → x+h)
  2. See how much f(x) changed
  3. Divide change in f by change in x
  4. Make h smaller and smaller (approaching zero)

Geometric View: The Tangent Line

Derivative as Slope The derivative at a point = slope of the tangent line Why tangent line?
  • Secant line: connects two points (average rate of change)
  • Tangent line: touches at ONE point (instantaneous rate of change)
  • As points get closer, secant → tangent

Computing a Derivative Numerically

Let’s compute the derivative of f(x)=x2f(x) = x^2 at x=3x = 3:
Output:
Key Insights:
  • As h gets smaller, our approximation gets better
  • The derivative is the instantaneous rate of change
  • At x=3, the function x2x^2 is rising steeply (slope = 6)
  • This tells us: small changes in x cause BIG changes in f(x)
Numerical Stability: The Goldilocks Zone for hYou might think “smaller h is always better.” Not so. Try h = 1e-15:
You will get something wildly wrong (like 6.66 or 0.0). Why? Computers store numbers in floating point with limited precision (about 15-16 significant digits for 64-bit floats). When h is extremely tiny, f(x+h) - f(x) subtracts two nearly identical numbers, and all the meaningful digits cancel out — a phenomenon called catastrophic cancellation.The practical sweet spot is h around 1e-5 to 1e-7. Even better, use the centered difference formula:f(x)f(x+h)f(xh)2hf'(x) \approx \frac{f(x+h) - f(x-h)}{2h}This is more accurate because the errors on both sides partially cancel. It converges as O(h2)O(h^2) rather than O(h)O(h) for the forward difference.
In ML frameworks like PyTorch, torch.autograd.gradcheck uses centered differences with h = 1e-6 by default to verify that analytical gradients are correct. Understanding why that value was chosen is the kind of detail that separates practitioners who debug training runs from those who stare at NaN losses in confusion.

Why This Matters for Machine Learning

In ML, we have a loss function L(w)L(w) where ww = model weights:
This is gradient descent - the algorithm that powers ALL of machine learning!

Example 1: Minimizing Business Costs

The Problem

You’re optimizing ad spending. Your cost function is: C(x)=x210x+100C(x) = x^2 - 10x + 100 Where xx is ad spend in thousands of dollars. Goal: Find the spending level that minimizes cost.

Step 1: Understand the Function

Step 2: Compute the Derivative

Derivative of C(x)=x210x+100C(x) = x^2 - 10x + 100: C(x)=2x10C'(x) = 2x - 10

Step 3: Find the Minimum

At the minimum, the derivative = 0 (flat tangent line) C(x)=02x10=0x=5C'(x) = 0 \\ 2x - 10 = 0 \\ x = 5
Key Insight:
  • Derivative < 0 → function decreasing → move right
  • Derivative = 0 → potential minimum/maximum
  • Derivative > 0 → function increasing → move left
Real Application: Google Ads uses derivatives to optimize bidding strategies for millions of advertisers!

Example 2: Optimizing Student Learning

The Problem

A student’s test score depends on study hours: S(h)=h2+12h+20S(h) = -h^2 + 12h + 20 Where hh is hours studied per day. Question: How many hours should they study to maximize their score?

Understanding the Relationship

Observation: Too few hours → low score. Too many hours → burnout, score decreases!

Finding the Optimal Study Time

Derivative: S(h)=2h+12S'(h) = -2h + 12
Interpretation:
  • Before 6 hours: More study → higher score (positive derivative)
  • At 6 hours: Perfect balance (zero derivative)
  • After 6 hours: More study → lower score due to burnout (negative derivative)
Real Application: Khan Academy uses similar models to recommend optimal practice time for students!

Example 3: Tuning Recommendation Systems

The Problem

Netflix wants to tune a recommendation parameter α\alpha to minimize prediction error: E(α)=(α0.8)2+0.1E(\alpha) = (\alpha - 0.8)^2 + 0.1 Goal: Find the α\alpha that minimizes error.

Visualizing the Error

Finding Optimal Parameter

Derivative: E(α)=2(α0.8)E'(\alpha) = 2(\alpha - 0.8)
Key Insight: This is exactly how machine learning works!
  1. Start with random parameters
  2. Compute derivative (gradient)
  3. Move in opposite direction of gradient
  4. Repeat until convergence
Real Application: Netflix uses gradient descent to tune thousands of parameters in their recommendation system!

Derivative Rules

Now that you understand WHY derivatives matter, here are the rules:

Power Rule

ddxxn=nxn1\frac{d}{dx}x^n = nx^{n-1}

Complete Derivative Rules Reference

Here’s your cheat sheet. Bookmark this page!

Basic Rules

Product & Quotient Rules

Chain Rule

ddxf(g(x))=f(g(x))g(x)\frac{d}{dx}f(g(x)) = f'(g(x)) \cdot g'(x) Memory trick: “Derivative of outside times derivative of inside”

Common Functions

Worked Examples: Applying the Rules

Example 1: Polynomial f(x)=3x42x3+5x7f(x) = 3x^4 - 2x^3 + 5x - 7 Using power rule and sum rule: f(x)=3(4x3)2(3x2)+5(1)0=12x36x2+5f'(x) = 3(4x^3) - 2(3x^2) + 5(1) - 0 = 12x^3 - 6x^2 + 5 Example 2: Product Rule h(x)=x2exh(x) = x^2 \cdot e^x Let f=x2f = x^2 and g=exg = e^x: h(x)=(2x)(ex)+(x2)(ex)=ex(2x+x2)=exx(x+2)h'(x) = (2x)(e^x) + (x^2)(e^x) = e^x(2x + x^2) = e^x \cdot x(x + 2) Example 3: Quotient Rule q(x)=x2x+1q(x) = \frac{x^2}{x + 1} Let f=x2f = x^2 and g=x+1g = x + 1: q(x)=(2x)(x+1)(x2)(1)(x+1)2=2x2+2xx2(x+1)2=x2+2x(x+1)2q'(x) = \frac{(2x)(x+1) - (x^2)(1)}{(x+1)^2} = \frac{2x^2 + 2x - x^2}{(x+1)^2} = \frac{x^2 + 2x}{(x+1)^2} Example 4: Chain Rule y=(3x+1)5y = (3x + 1)^5 Let outer f(u)=u5f(u) = u^5 and inner g(x)=3x+1g(x) = 3x + 1: y=5(3x+1)43=15(3x+1)4y' = 5(3x + 1)^4 \cdot 3 = 15(3x + 1)^4

ML-Specific Derivatives You’ll Use Often

Sigmoid Function: σ(x)=11+ex,σ(x)=σ(x)(1σ(x))\sigma(x) = \frac{1}{1 + e^{-x}}, \quad \sigma'(x) = \sigma(x)(1 - \sigma(x))
Numerical Stability of SigmoidThe naive 1 / (1 + np.exp(-x)) overflows when x is a large negative number because np.exp(700) exceeds float64 range. Production implementations use a clipped version:
Notice the key idea: for negative x, we rewrite the expression so the exponent is also negative, which can only produce values between 0 and 1 instead of exploding toward infinity. PyTorch does exactly this inside torch.sigmoid. When you see “RuntimeWarning: overflow encountered in exp” during training, this is almost always the culprit.The derivative sigma(x) * (1 - sigma(x)) has its own issue: it maxes out at 0.25 (when x=0) and approaches 0 as |x| grows. In a deep network, multiplying many of these small values together during backpropagation causes vanishing gradients — the reason ReLU largely replaced sigmoid in hidden layers.
Mean Squared Error Loss: L=1n(ypredytrue)2,Lypred=2n(ypredytrue)L = \frac{1}{n}\sum(y_{pred} - y_{true})^2, \quad \frac{\partial L}{\partial y_{pred}} = \frac{2}{n}(y_{pred} - y_{true}) Cross-Entropy Loss: L=ytruelog(ypred),Lypred=ytrueypredL = -\sum y_{true} \log(y_{pred}), \quad \frac{\partial L}{\partial y_{pred}} = -\frac{y_{true}}{y_{pred}}

Constant Rule

ddxc=0\frac{d}{dx}c = 0 Why? Constants don’t change!

Sum Rule

ddx[f(x)+g(x)]=f(x)+g(x)\frac{d}{dx}[f(x) + g(x)] = f'(x) + g'(x)

Product Rule

ddx[f(x)g(x)]=f(x)g(x)+f(x)g(x)\frac{d}{dx}[f(x)g(x)] = f'(x)g(x) + f(x)g'(x)

Chain Rule (Preview)

ddxf(g(x))=f(g(x))g(x)\frac{d}{dx}f(g(x)) = f'(g(x)) \cdot g'(x) We’ll cover this in depth in Module 3!

Higher-Order Derivatives

Second Derivative

The derivative of the derivative! f(x)=d2dx2f(x)f''(x) = \frac{d^2}{dx^2}f(x) Interpretation: How fast is the rate of change changing?
Physical Interpretation:
  • f(x)f(x) = position
  • f(x)f'(x) = velocity (rate of change of position)
  • f(x)f''(x) = acceleration (rate of change of velocity)

Concavity

Second derivative tells you about curvature:
  • f(x)>0f''(x) > 0 — Concave up (think of a bowl you can put soup in) — Local minimum
  • f(x)<0f''(x) < 0 — Concave down (think of an upside-down bowl, a hill) — Local maximum
  • f(x)=0f''(x) = 0 — Inflection point (the curve changes from bowl to hill or vice versa)
ML Connection: Curvature and Learning SpeedThe second derivative is not just an academic concept — it directly affects how fast your model can learn. Think of it this way: the first derivative tells you which direction to step, but the second derivative tells you how confident you should be in that step.In a region with high curvature (large f(x)|f''(x)|), the gradient changes rapidly, so you need small steps or you will overshoot. In a region with low curvature (small f(x)|f''(x)|), the gradient is stable, so you can afford larger steps. This insight is the entire motivation behind second-order optimization methods like Newton’s method, L-BFGS, and the curvature-aware components of Adam.When an interviewer asks “why might training oscillate near a minimum?”, the answer involves curvature: the loss surface has different second derivatives along different directions, so a single learning rate is either too big for the steep direction or too small for the flat one.

Numerical Derivatives

When you can’t compute derivatives analytically:

Forward Difference

f(x)f(x+h)f(x)hf'(x) \approx \frac{f(x+h) - f(x)}{h}

Central Difference (More Accurate)

f(x)f(x+h)f(xh)2hf'(x) \approx \frac{f(x+h) - f(x-h)}{2h}
When to use:
  • Complex functions without closed-form derivatives
  • Debugging analytical derivatives
  • Quick prototyping

Practice Exercises

Exercise 1: Profit Maximization


🎯 Practice Exercises & Real-World Applications

Challenge yourself! These exercises connect derivatives to decisions you make every day - from pricing to fitness to driving.

Exercise 1: Uber Surge Pricing 🚕

Uber uses dynamic pricing. When demand is high, prices surge. Model this:
Real-World Insight: This is exactly how Uber’s pricing algorithm works! They continuously estimate demand curves and adjust prices to maximize profit while balancing rider satisfaction.

Exercise 2: Optimal Study Time 📚

You’re studying for an exam. More study time = higher score, but with diminishing returns:
Real-World Insight: This “diminishing returns + cost” model applies everywhere: exercise (muscle gains vs. injury risk), marketing (ad spend vs. saturation), even eating (enjoyment vs. fullness)!

Exercise 3: Fuel Efficiency Sweet Spot 🚗

Your car’s fuel consumption depends on speed:
Real-World Insight: This is why highway speed limits and eco-driving recommendations hover around 55-65 mph. Car manufacturers optimize engines for this range. Tesla’s efficiency curves show the same pattern!

Exercise 4: Investment Growth Rate 💹

You’re analyzing compound growth with continuous compounding:
Real-World Insight: This is the “magic” of compound interest that Einstein allegedly called the 8th wonder of the world. The derivative shows that growth rate is proportional to current value - the rich get richer mathematically!

Key Takeaways

Derivative = rate of change - How output changes with input
Geometric view - Slope of tangent line
Optimization - Set derivative = 0 to find min/max
Second derivative - Tells you if it’s min or max
ML connection - Gradient descent uses derivatives to learn

Common Pitfalls & How to Avoid Them

Mistakes that trip up beginners and even experienced practitioners:
Wrong thinking: “The derivative of x2x^2 at x=3x=3 is x2=9x^2 = 9Correct: The derivative of x2x^2 is 2x2x. At x=3x=3, the derivative is 2(3)=62(3) = 6.The derivative tells you the slope, not the height!
Wrong: ddx(x2+1)3=3(x2+1)2\frac{d}{dx}(x^2 + 1)^3 = 3(x^2 + 1)^2Correct: ddx(x2+1)3=3(x2+1)22x=6x(x2+1)2\frac{d}{dx}(x^2 + 1)^3 = 3(x^2 + 1)^2 \cdot 2x = 6x(x^2 + 1)^2Rule: When there’s a function inside another function, multiply by the derivative of the inner function!
Trap: Using extremely small hh values for numerical derivatives.
Why? Computers have limited precision (~15-16 decimal digits). Subtracting nearly equal numbers loses precision.
Wrong thinking: “f’(x) = 0 means I found the minimum!”Reality: f’(x) = 0 could be:
  • Minimum (f”(x) > 0)
  • Maximum (f”(x) < 0)
  • Saddle point (f”(x) = 0)
Always check the second derivative or evaluate the function around that point!

Interview Questions You Should Be Able to Answer

These come up in ML Engineer and Data Scientist interviews at top companies:

What’s Next?

You now understand derivatives for single-variable functions. But ML models have MANY variables (thousands or millions!). How do we handle that? Gradients - the multi-variable version of derivatives!

Next: Gradients & Multivariable Calculus

Learn how to optimize functions with many variables

Interview Deep-Dive

Strong Answer:
  • This is a great question because it exposes the gap between pure math and engineering pragmatism. Technically, ReLU is not differentiable at exactly x=0 — it has a “kink.” But in practice, the probability that any neuron’s pre-activation lands on exactly 0.0 in floating-point arithmetic is essentially zero. It is a set of measure zero.
  • In frameworks like PyTorch and TensorFlow, the convention is to define the derivative at x=0 as either 0 or 1 (PyTorch uses 0). This is called a subgradient, and subgradient methods have well-established convergence guarantees for convex problems. For non-convex neural networks, the empirical evidence is overwhelming that this works.
  • The deeper insight: what matters for optimization is not pointwise differentiability but that the gradient provides a useful descent direction almost everywhere. ReLU is differentiable everywhere except a single point, and the gradient signal is clean — either 0 or 1, no saturation. Compare this to sigmoid where the derivative is technically defined everywhere but practically useless in deep networks because it saturates to near-zero for large or small inputs.
  • There is actually a family of smooth approximations to ReLU if you want strict differentiability: SiLU/Swish (x * sigmoid(x)), GELU (used in GPT and BERT), and Softplus (log(1 + exp(x))). These are differentiable everywhere and often perform slightly better, partly because the smooth gradient near zero provides a richer learning signal.
Follow-up: If ReLU’s derivative is just 0 or 1, does that mean all surviving gradients have the same magnitude? How does the network learn nuanced weight updates?No — and this is a subtle point. The ReLU derivative is 0 or 1, but that is just the local derivative of the activation. The actual gradient flowing to each weight is the product of the upstream gradient (which carries magnitude information from the loss and later layers) multiplied by the ReLU derivative multiplied by the input activation. So the ReLU acts as a gate — it either passes the full upstream gradient through (when active) or blocks it entirely (when inactive). The magnitude nuance comes from the loss gradient and the chain of other operations, not from the activation derivative itself. This gating behavior is actually what makes ReLU so effective: it creates sparse gradient flow, where only a subset of neurons participate in each update, which acts as an implicit form of regularization.
Strong Answer:
  • The analytical derivative is the exact mathematical formula derived using differentiation rules. For f(x) = x^3, that is f’(x) = 3x^2. It is exact, fast to compute, and is what autograd systems (PyTorch, JAX) effectively compute through the chain rule applied to computational graphs.
  • The numerical derivative uses finite differences: f’(x) approximately equals (f(x+h) - f(x-h)) / (2h) for small h. It requires no knowledge of the function’s internal structure — just the ability to evaluate it.
  • In production ML, you almost always use analytical gradients (via autodiff) for training because they are exact and efficient. Numerical derivatives scale terribly: for N parameters, you need 2N function evaluations versus one backward pass.
  • But numerical derivatives are invaluable for gradient checking during development. When implementing a custom layer or loss function, you compute both the analytical gradient and the numerical approximation, then verify they match within a relative error of about 1e-5 to 1e-7. This catches bugs like sign errors, missing factors, or incorrect chain rule application.
  • The failure mode of numerical differentiation is subtle: choosing h. Too large and the approximation is inaccurate (truncation error). Too small and floating-point cancellation destroys the result — you are subtracting two nearly equal numbers, losing significant digits. The sweet spot for float64 is typically h around 1e-5 to 1e-7. For float32 (common in GPU training), the useful range is even narrower, around 1e-3 to 1e-4. I have seen gradient checks fail spuriously because someone used h=1e-7 with float32 tensors.
Follow-up: You mentioned gradient checking catches bugs during development. Can you describe a real scenario where a gradient check would catch a bug that unit tests on the forward pass would miss?Absolutely. A common case: you implement a custom loss that includes a log term, like cross-entropy. Your forward pass produces correct loss values for all test cases. But in the backward pass, you accidentally write the gradient as 1/p instead of -1/p (forgot the negative sign from the derivative of -log(p)). The forward pass unit tests all pass perfectly because the loss computation is correct. But the model trains in the wrong direction — it maximizes loss instead of minimizing it. A gradient check comparing your analytical -1/p against numerical (f(p+h) - f(p-h))/(2h) would immediately flag the sign discrepancy. Another real scenario: forgetting to apply the chain rule through a clamp or clip operation. The forward pass clips values correctly, but the backward pass propagates gradients through the clipped region where they should be zero. Your loss looks fine, but the training dynamics are subtly wrong.
Strong Answer:
  • The fundamental issue is the multiplicative nature of the chain rule in deep networks. When you backpropagate through L layers, the gradient for the first layer involves multiplying L activation derivatives together. If each derivative is at most 0.25 (sigmoid), after 10 layers you have at most 0.25^10 which is about 9.5e-7. The gradient has effectively vanished.
  • Tanh is better because its derivative peaks at 1.0 (when the input is near zero). But it still saturates — for large positive or negative inputs, the derivative approaches zero. So in practice, tanh also suffers from vanishing gradients, just less severely. After enough layers, if neurons are frequently in the saturated regime, you get the same multiplicative decay.
  • The fundamental issue is not the specific maximum value but the fact that these activations have derivatives bounded strictly below 1 across most of their domain. Any function whose derivative is consistently less than 1 will cause exponential gradient decay through the chain rule. Conversely, derivatives consistently greater than 1 cause exploding gradients.
  • ReLU sidesteps this entirely: its derivative is exactly 1 for positive inputs. No multiplication-induced shrinkage. Through a chain of ReLU layers, the gradient magnitude is preserved (modulo the weight matrices). This is why ReLU enabled the training of much deeper networks starting around 2011-2012.
  • The modern understanding goes deeper: even with ReLU, the weight matrices themselves can cause gradient explosion or vanishing. That is why careful initialization (He initialization for ReLU, Xavier/Glorot for tanh) and architectural innovations like residual connections (ResNets) and normalization layers (BatchNorm, LayerNorm) are essential for very deep networks.
Follow-up: If the chain rule’s multiplicative structure is the core problem, how do residual connections (skip connections) change the gradient flow mathematically?A residual block computes y = F(x) + x instead of y = F(x). When you differentiate, dy/dx = dF/dx + 1. That “+1” is the critical term — it creates an identity shortcut for gradient flow. Even if dF/dx vanishes (the learned transformation has tiny gradients), the gradient still flows through the identity path with magnitude 1. In a deep ResNet with L blocks, the gradient from the loss to the first block has a path that multiplies by 1 at every skip connection, completely bypassing the vanishing gradient problem. This is why ResNets can be trained with hundreds or even thousands of layers, while plain networks struggle beyond 20-30 layers. The mathematical elegance is that you are adding a constant (the identity) to the Jacobian at each layer, ensuring the product of Jacobians stays well-conditioned.
Strong Answer:
  • NaN in training almost always means a numerical overflow or an invalid math operation somewhere in the forward or backward pass. My systematic approach starts with the calculus.
  • First, I check the gradient norms over time. If gradients are growing exponentially before the NaN, that is exploding gradients — the chain rule multiplications are compounding rather than staying bounded. The fix is gradient clipping (cap the global gradient norm to a threshold like 1.0 or 5.0) and possibly reducing the learning rate.
  • Second, I look for operations that produce NaN or Inf: log(0), division by zero, exp(large number). In cross-entropy loss, if a predicted probability hits exactly 0 and you compute log(0), that is negative infinity, which propagates through everything. The fix is adding epsilon: log(p + 1e-8) or using numerically stable implementations like PyTorch’s F.cross_entropy which combines log-softmax for stability.
  • Third, I check for softmax overflow. If logits become very large, exp(logit) overflows to Inf before normalization. The standard fix is the log-sum-exp trick: subtract the maximum logit before exponentiating. All production frameworks do this internally, but custom implementations often miss it.
  • Fourth, I inspect whether the NaN is in the forward pass or backward pass. I add hooks to check activations and gradients layer by layer. If activations are fine but gradients are NaN, the issue is likely in a backward computation — perhaps a custom backward function that divides by a value that became zero.
  • Fifth and often overlooked: data issues. If a batch contains a corrupted sample with Inf or NaN values (happens with real-world data pipelines), that single sample poisons the entire batch’s loss and gradient. I add data validation checks and NaN detection in the data loader.
  • The fact that it worked for 10,000 steps then broke suggests a slow accumulation — probably weight magnitudes growing gradually until an activation or gradient overflows. Learning rate warmup and weight decay both help prevent this drift.
Follow-up: You mentioned gradient clipping. Does gradient clipping introduce bias into the optimization, and if so, why is it still considered safe to use?Yes, gradient clipping does technically bias the gradient direction when it activates. When you scale down a gradient vector to meet a norm threshold, you preserve the direction but reduce the magnitude. This means you take a smaller step than the true gradient suggests. The bias is conservative — you never overshoot, you just under-step. In practice, clipping only activates during transient spikes (a particularly noisy batch, a rare data point), so the long-term optimization trajectory is minimally affected. The alternative — letting an exploding gradient step destroy your model weights — is catastrophically worse. There is also theoretical work showing that gradient clipping is equivalent to adaptive learning rate reduction during unstable steps, which is a well-motivated thing to do.