Core Foundation · Local CPULaptop CPULesson 1 of 5 in Phase 02

Phase 02 / JAX transformations

Your first gradient

Revision v0.18.1 ·

Lesson · about 55 minutes · CPU practice

Explain local sensitivity and the chain rule, then compare analytic, numerical, and automatic derivatives.

Phase study guide: preparation, milestones and project evidence

Before you start

Before this: Arrays & pure functions
Hardware: CPU

Setup help: Python, notebook, or Cloud TPU VM

Use the tested CPU packages (the recorded environment uses Python 3.14.3). Other Python versions require separate checks. Hardware receipts apply only to their recorded source, environment, hardware, and cases; they do not qualify every lesson or TPU configuration. See the TPU performance and hardware evidence guide. The optional Cloud TPU specialization explains target-specific execution boundaries. Logical CPU devices practice partitioning; they do not simulate TPU performance.

Download the repository ZIP or use your existing checkout. Extract it and open a terminal in the folder containing requirements-cpu.txt. The beginner ZIP is separate; these lessons use the full repository folder.

macOS / Linux terminal · repository folder
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-cpu.txt

PowerShell · repository folder
py -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-cpu.txt

After activation, run the complete worked example from that same folder:

macOS / Linux terminal · activated environment
python phases/02-transforms/01-your-first-gradient/code/main.py

PowerShell command · repository folder
.\.venv\Scripts\python.exe phases/02-transforms/01-your-first-gradient/code/main.py

For an incremental build, create main.py in your own practice folder, append each build block in order, and run python main.py with this environment active. Keep that file separate from the downloaded reference solution.

Check: 6.06.0

Revisit the guided CPU setup · Open 19: TPU Setup. Package instructions are CPU instructions; Windows and accelerator environments need their own validation.

Stage 1 of 5 · Understand the MechanismCore mental model, equations & visual walkthrough

What you will be able to do

  • Predict the sign and magnitude of a derivative from a local change.
  • Trace the chain rule through a composed numerical function.
  • Compare an analytic derivative, a finite-difference estimate, and JAX autodiff.
  • Distinguish a stationary point from a minimum and repair scalar-output/input-type errors.

The problem

Imagine that you can turn one dial, and a score tells you how far you are from the result you want. Which way should you turn it? We’ll begin with the curve f(x)=x2f(x)=x^2, where we can check the answer by hand. A derivative tells us how the score changes nearby; then JAX will calculate that derivative for us. You do not need to guess what the tool is doing.

The idea

A derivative tells us how an output changes near a particular input. We can understand it before using autodiff: move the input a small amount, estimate the output change from the local slope, then compare that prediction with the function.

Move the input. Watch the local slope.
−4041680

Read left to right as input and upward as function value. The solid curve is f(x)=x2f(x)=x^2; the dashed straight line touches it at the selected point and has slope 2x2x. Near that point, the line approximates the curve; farther away, they separate. Negative tangent values extend below this viewing window. Move the input across zero to see the slope change sign. This analytic illustration updates in the browser; the Python exercise computes the derivative with JAX.

Use a slope to predict a nearby change

A derivative is useful because it predicts the effect of a small adjustment before we make it. For f(x)=x2f(x)=x^2, the slope at x=3x=3 is 66. Increasing the input by 0.010.01 predicts an output increase of 6(0.01)=0.066(0.01)=0.06, from 99 to 9.069.06; the exact output is 9.06019.0601. The extra 0.00010.0001 is curvature, not an autodiff error.

The tangent plot uses input on the horizontal axis and function or predicted value on the vertical axis. At x=3x=3, both curves pass through (3,9)(3,9). At x=2x=2, the square is 44 while the tangent predicts 33; at x=0x=0, they are 00 and −9-9. Use the tangent only nearby: its negative value at zero is not a negative square.

Read a slope before you compute it

Use a negative input to check what the sign means. At x=−3x=-3, the derivative of the square is −6-6. A move right by 0.010.01 therefore predicts a change of −0.06-0.06, from 99 to 8.948.94. The exact value at −2.99-2.99 is 8.94018.9401. A negative slope means the output decreases when the input increases locally; it does not mean that the output itself is negative.

At zero, the derivative is zero, so the linear prediction is no change. Yet moving to 0.010.01 gives 0.00010.0001. This is consistent: the first-order change vanishes, leaving the smaller squared term. A zero derivative at one point does not mean the function is constant around it. Compare positive, negative and zero inputs before checking the derivative rule with JAX.

f(x+δ)−f(x)=2xδ+δ2f′(x)=2x\begin{aligned}f(x+\delta)-f(x)&=2x\delta+\delta^2\\f\prime(x)&=2x\end{aligned}

Three ways to obtain a derivative

There are three ways to answer the same local-change question, and comparing them catches mistakes. Algebra gives the exact derivative; finite differences estimate it from nearby function values; autodiff composes derivative rules for the operations in the program.

For the executed check at x=3x=3, autodiff and the analytic result are both 66, while a finite difference with step 10−310^{-3} is about 66. With a much smaller step, floating-point subtraction can lose useful digits; the recorded sweep for the composed function shows error growing again at 10−510^{-5} and a zero estimate at 10−710^{-7}. Autodiff does not have a hidden finite-difference step, but it still differentiates the numerical program you wrote, including any poorly conditioned or unintended calculation.

Follow the chain rule through the program

The chain rule matters when a program is built from multiple operations: a change to the input passes through each intermediate value. Let u=3x+1u=3x+1, then y=u2y=u^2. The first operation changes uu three times as fast as xx; the square changes yy at rate 2u2u.

At x=2x=2, the code’s intermediate is u=7u=7, so the total slope is 2(7)⋅3=422(7)\cdot3=42. The execution receipt also checks x=−1x=-1 and x=0x=0, giving −12-12 and 66. These values make a concrete reference for grad: it follows the same operation sequence and chain rule rather than nudging the input repeatedly.

u=3x+1,y=u2dydx=dydududx=2u⋅3\begin{aligned}u&=3x+1,\qquad y=u^2\\\frac{dy}{dx}&=\frac{dy}{du}\frac{du}{dx}=2u\cdot3\end{aligned}

Know the contract of grad

grad is designed for a scalar objective because it returns one derivative value per differentiated input value. Its default target is the first positional argument, and that argument needs an inexact type such as a floating-point scalar or array. A vector output such as residuals is not yet one objective; choose a sum or mean, or use a Jacobian when every output derivative is wanted.

A scalar array has shape ()(), while a one-element vector has shape (1,)(1,). Those are different contracts even if both display one number. Likewise, Python 3.0 is a floating-point input while 3 is an integer. Check argument position, dtype and output shape when a valid-looking function cannot be differentiated.

A zero gradient is a question, not a verdict

A zero gradient only says the first-order change is zero at that point; it does not classify the point. For x2x^2, zero is a minimum; for x3x^3, the derivative is also zero there although the function continues decreasing to the left; a constant function has zero slope everywhere.

When a model unexpectedly reports zero, first check whether the objective depends on the parameter and whether grad received the intended argument. Then compare the function at nearby points and hand-check a simple case. Changing an optimizer cannot repair a derivative of the wrong objective.

Read the figure

The horizontal axis is input xx, and both plotted vertical values are function or tangent predictions. The solid square curve and dashed tangent meet at the marked (3,9)(3,9). At x=2x=2, compare 44 with 33; at x=0x=0, compare 00 with −9-9. These coordinates show where a local slope prediction begins to separate from the curved function.

Connect it to the computation

The tangent slope at x=3x=3 is 66, so for a small change Δx\Delta x, it predicts 9+6Δx9+6\Delta x. The exact square adds (Δx)2(\Delta x)^2. Use the plotted gap as a reminder that a derivative predicts nearby change, not the entire function; then try a small move on either side of the marked input.

Figure data and execution details

Recorded environment: JAX 0.9.2 · 1 CPU device

The notebook contains the data experiment, plotting code, and recorded figure output. Rerun it to test your changes.

Stage 2 of 5 · Build & Run the ReferenceStep-by-step code construction & verified execution output

Your build: Create a separate main.py in your practice folder. Append each block in order and run python main.py in the lesson environment. The downloaded script is the complete reference, so keep it separate from your attempt.

1 Import JAX automatic differentiation

Import jax and jax.numpy for the scalar function and derivative.

main.py · append build step 1
import jax
import jax.numpy as jnp

The differentiation API will operate on the function defined in the next block.

2 Define the square and differentiate it

Write f(x)=x2f(x) = x^2 and create a callable derivative with jax.grad.

main.py · append build step 2
def f(x):
    return x ** 2
derivative = jax.grad(f)

The derivative is 2x2x. jax.grad transforms the scalar-output function, so derivative(3) should return 66.

Explain the APIs in this step
  • jax.grad(loss_fn)(params, ...): Transforms a scalar-output function into one returning the gradient PyTree with the same structure as params.

3 Check the derivative at two points

Evaluate the derivative at 3 and at the minimum x=0.

main.py · append build step 3
assert jnp.allclose(derivative(3.0), 6.)
assert jnp.allclose(derivative(0.0), 0.)

The values 6 and 0 test the rule at a nonzero point and at the stationary point.

Explain the APIs in this step
  • jnp.allclose(actual, expected, rtol=..., atol=...): Returns a JAX boolean scalar indicating whether corresponding values are within the requested tolerance.
View the cumulative build in main.py

These blocks append in order to your separate practice file.

main.py · cumulative Python build
import jax
import jax.numpy as jnp

def f(x):
    return x ** 2
derivative = jax.grad(f)

assert jnp.allclose(derivative(3.0), 6.)
assert jnp.allclose(derivative(0.0), 0.)

Build a numerical estimate

Numerical estimate
# Numerical estimate: Approximately 6.0.
def central_difference(function, x, h=1e-3):
    return (function(x + h) - function(x - h)) / (2 * h)

def square(x):
    return x * x

estimate = central_difference(square, 3.0)
print("Finite-difference estimate:", estimate)
assert abs(estimate - 6.0) < 1e-8

Approximately 6.06.0. This estimate evaluates the function at two nearby points; it is not automatic differentiation.

Run the example

python3 phases/02-transforms/01-your-first-gradient/code/main.py
About this command

This shortcut uses an activated macOS/Linux course environment in the repository folder. For Windows, use the explicit interpreter command in “Setup help” above. The script includes worked examples and reference solutions.

Inspect the complete assembled example
main.py · complete Python example
# Your first gradient: A derivative tells us how an output changes near a particular input.
import jax
import jax.numpy as jnp
def f(x):
    return x ** 2
derivative = jax.grad(f)
print(float(derivative(3.0)))
assert jnp.allclose(derivative(3.0), 6.)
assert jnp.allclose(derivative(0.0), 0.)

Expected result: 6.06.0

Recorded output and runtime details

Reference output captured from executing the complete lesson script (code/main.py) and its assertions in the course CPU environment.

2026-10-27T17:02:47.265557+00:00 · Python 3.14.3 · JAX 0.9.2 · 1 CPU device

Finite-difference estimate: 5.999999999999339
6.0
chain rule: -1.0 -12.0
chain rule: 0.0 6.0
chain rule: 2.0 42.0
h / estimate / error: 0.1 27.009973526000977 0.009973526000976562
h / estimate / error: 0.01 27.000045776367188 4.57763671875e-05
h / estimate / error: 0.001 26.9975643157959 0.0024356842041015625
h / estimate / error: 1e-05 27.0843505859375 0.0843505859375
h / estimate / error: 1e-07 0.0 27.0
PASS: first-gradient

Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.

Stage 3 of 5 · Controlled ExperimentsPredict before running & test boundary conditions

Check the chain rule at three inputs

Check the chain rule at three inputs · Python experiment
# Experiment — Check the chain rule at three inputs: The inner derivative contributes a factor of 3.
def composed(x):
    return (3. * x + 1.) ** 2
for point in (-1., 0., 2.):
    observed = jax.grad(composed)(point)
    expected = 6. * (3. * point + 1.)
    print("chain rule:", point, float(observed))
    assert jnp.allclose(observed, expected)

Expected: The three derivatives are −12-12, 66, and 4242.

The inner derivative contributes a factor of 33. Omitting that factor is a chain-rule error; matching only one point can hide a wrong expression.

Choose a finite-difference scale

Choose a finite-difference scale · Python experiment
# Experiment — Choose a finite-difference scale
def cubic32(x):
    return x ** 3
point = jnp.array(3., dtype=jnp.float32)
for step in (1e-1, 1e-2, 1e-3, 1e-5, 1e-7):
    estimate = (cubic32(point + step) - cubic32(point - step)) / (2. * step)
    print("h / estimate / error:", step, float(estimate), float(jnp.abs(estimate - 27.)))
assert jnp.allclose(jax.grad(cubic32)(point), 27.)

Expected: The errors need not decrease monotonically. At sufficiently small hh, rounding can erase the input change.

A central difference has truncation error at larger hh and cancellation/rounding error at very small hh. The original numerical-estimate example used Python floats; this sweep deliberately uses a JAX float32 array. Do not silently compare their precision as if it were identical.

Stage 4 of 5 · Hands-On Exercise & CheckpointModify the code yourself, solve transfer tasks & test your understanding
Hands-On Exercise · Modify & Verify Run in the declared lesson environment

Make it yours

Where to put your code: Modify your own main.py, or use the Make it yours cell in your downloaded notebook. Run your attempt in the declared environment and verify your prediction before opening the reference solution.

Foundation · Define f(x)=x3f(x)=x^3. Derive f′(x)f\prime(x), predict the values at −2-2, 00, and 33, then verify every prediction with JAX. Explain why the zero at x=0x=0 is separate from a minimum.

Show a writing guide and starter scaffold

How to write this exercise code

Learner-only inputs, outputs, checks and hints

Inputs

  • A scalar cubic function defined by the learner.
  • Evaluation points -2, 0, and 3.

Outputs

  • The function and its JAX derivatives at each point.
  • An explanation that separates a stationary point from a minimum.

Invariants to check

  • grad receives a scalar-output function.
  • Every requested point is checked.
  • A zero derivative alone does not classify a minimum.

Hints

  • Derive the polynomial rule before calling autodiff.
  • Check function behavior on either side of the stationary point.
Your attempt · complete the TODOs
import jax
import jax.numpy as jnp

def cubic(x):
    # TODO: define the scalar cubic
    raise NotImplementedError

def check_cubic(points):
    # TODO: evaluate and retain one JAX derivative per point
    raise NotImplementedError
Reveal the reference solution
Reference solution
# Exercise solution: Foundation · Define f(x)=x^3.
def cubic(x):
    return x ** 3
for point in (-2., 0., 3.):
    assert jnp.allclose(jax.grad(cubic)(point), 3. * point ** 2)
assert cubic(-0.1) < cubic(0.) < cubic(0.1)

Differentiate the parameter you intended

Practice

For the prediction y^=wx\hat y=wx, find the derivative with respect to ww and then with respect to xx. Evaluate them at w=2w=2 and x=3x=3. Predict both answers before choosing argnums.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • The scalar prediction weight * x.
  • Weight 2 and input 3.
  • Two requested differentiation arguments.

Outputs

  • A derivative with respect to each argument.

Invariants to check

  • The unselected argument remains an ordinary input.
  • Distinguish prediction from derivative.

Hints

  • Name the differentiation argument explicitly.
  • Check each derivative against its own input.
Your attempt · complete the TODOs
import jax

def scalar_prediction(weight, x):
    # TODO: define the scalar prediction
    raise NotImplementedError

def compare_argument_gradients():
    # TODO: transform the function for each requested argument
    raise NotImplementedError
Show a hint

grad defaults to argnums=0. The other input remains an input to the transformed callable.

Reveal reference solution and reasoning
Differentiate the parameter you intended · Python solution
# Differentiate the parameter you intended (Practice)
def scalar_prediction(weight, x):
    return weight * x
assert jnp.allclose(jax.grad(scalar_prediction, argnums=0)(2., 3.), 3.)
assert jnp.allclose(jax.grad(scalar_prediction, argnums=1)(2., 3.), 2.)

A parameter gradient and an input sensitivity answer different questions even when they originate from the same function.

Repair an objective without hiding its meaning

Challenge

A function returns [x2,(x−2)2][x^2,(x-2)^2]. Explain why ordinary grad rejects it. Build a scalar objective using their mean, derive its derivative, and check x=0x=0, 11, and 22. Would a sum have the same derivative magnitude?

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • A two-element output containing squared costs.
  • Inputs 0, 1, and 2.

Outputs

  • A scalar mean objective and its derivatives.
  • A comparison with the sum objective’s derivative scale.

Invariants to check

  • grad receives one scalar objective.
  • Mean and sum remain distinct objectives.

Hints

  • Choose the reduction before differentiating.
  • Compare the factors analytically.
Your attempt · complete the TODOs
import jax
import jax.numpy as jnp

def mean_objective(x):
    # TODO: construct the two costs and reduce to one scalar
    raise NotImplementedError

def compare_reductions(points):
    # TODO: evaluate derivatives for the mean and sum objectives
    raise NotImplementedError
Show a hint

Write the reduction as a mathematical function first: its mean is x2−2x+2x^2-2x+2.

Reveal reference solution and reasoning
Repair an objective without hiding its meaning · Python solution
# Repair an objective without hiding its meaning (Challenge)
def two_costs(x):
    return jnp.array([x ** 2, (x - 2.) ** 2])
def mean_cost(x):
    return jnp.mean(two_costs(x))
for point in (0., 1., 2.):
    assert jnp.allclose(jax.grad(mean_cost)(point), 2. * point - 2.)
    assert jnp.allclose(jax.grad(lambda z: jnp.sum(two_costs(z)))(point), 2. * jax.grad(mean_cost)(point))

Mean and sum agree on the minimizer here but differ by a factor of two in gradient magnitude. Reducing output is a modeling choice, not just a syntax repair.

Check your understanding

For f(x)=x3f(x)=x^3, JAX reports f′(0)=0f\prime(0)=0. What can you conclude?

Choose one answer

Diagnose the result

If grad reports a scalar-output error, inspect the output shape before adding an arbitrary reduction. If it reports an integer-input error, check the dtype of the differentiated argument. If a gradient is unexpectedly zero, evaluate the function at nearby inputs and verify argument selection. If finite differences disagree, record dtype and hh, sweep hh, and compare with an analytic test case. Each symptom calls for different evidence.

Stage 5 of 5 · Keep Your EvidenceRecord your verification receipt & carry takeaways forward

Carry forward

  • A derivative is a local sensitivity; a gradient transformation returns a callable.
  • Autodiff applies the chain rule to program operations, while finite differences approximate with input perturbations.
  • Scalar objective, input dtype, and differentiated argument are part of the contract.
  • A stationary point and a minimum are different claims.

Keep your evidence

Download evidence template

Keep predictions and analytic derivations at multiple inputs, the finite-difference step/error sweep with dtype, both argnums checks, and the scalar-objective repair. Explain why a zero gradient need not mark a minimum.

Save your modified code, its output, and an explanation of your prediction. Checkpoint answers and exercise evidence are tracked separately.

Saved in this browser. Export or back up your portfolio anytime in My learning.

Save work for this lesson

Reference execution: CPU validation only. This worked reference is validated on CPU. Accelerator compatibility requires a separate source review and target execution receipt. Use the execution matrix to review device selection and data ownership before adapting a separate target program. Execution matrix and target qualification.

Primary references