Phase 02 / JAX transformations
Your first gradient
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
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.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-cpu.txtpy -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-cpu.txtAfter activation, run the complete worked example from that same folder:
python phases/02-transforms/01-your-first-gradient/code/main.py.\.venv\Scripts\python.exe phases/02-transforms/01-your-first-gradient/code/main.pyFor 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.
Download this lesson’s notebook. Open it with a Python kernel using the course environment. Run cells from the top after restarting the kernel; experiments depend on earlier definitions.
For local Jupyter, first install the course requirements using the Local Python steps, then use your environment’s Python to start Jupyter:
python -m pip install jupyterlab
python -m jupyter lab.\.venv\Scripts\python.exe -m pip install jupyterlab
.\.venv\Scripts\python.exe -m jupyter labSelect the downloaded first-gradient.ipynb file in JupyterLab. The notebook contains reference solutions; make your prediction and attempt each practice task before opening them. Restart the kernel before changing logical device setup.
The worked reference for this lesson is CPU-validated. Some references explicitly configure logical CPU devices; setting JAX_PLATFORMS does not adapt them to a TPU. Follow the execution matrix and reviewed multi-host example before attempting a target run.
For accelerator preparation, study TPU setup, observed runtime receipts, checkpointed jobs and precision and retained traces. Current receipts cover bounded v5e1 launch, resume, and precision checks; four single-device Pallas cases; and a four-device v5e collective fixture. Each receipt is limited to its recorded source, environment, cases, and hardware. It does not qualify all lessons or TPU configurations. Cloud provisioning is optional for CPU learning.
Check:
Revisit the guided CPU setup · Open 19: TPU Setup. Package instructions are CPU instructions; Windows and accelerator environments need their own validation.
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 , 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.
Read left to right as input and upward as function value. The solid curve is ; the dashed straight line touches it at the selected point and has slope . 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 , the slope at is . Increasing the input by predicts an output increase of , from to ; the exact output is . The extra 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 , both curves pass through . At , the square is while the tangent predicts ; at , they are and . 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 , the derivative of the square is . A move right by therefore predicts a change of , from to . The exact value at is . 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 gives . 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.
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 , autodiff and the analytic result are both , while a finite difference with step is about . With a much smaller step, floating-point subtraction can lose useful digits; the recorded sweep for the composed function shows error growing again at and a zero estimate at . 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 , then . The first operation changes three times as fast as ; the square changes at rate .
At , the code’s intermediate is , so the total slope is . The execution receipt also checks and , giving and . These values make a concrete reference for grad: it follows the same operation sequence and chain rule rather than nudging the input repeatedly.
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 . 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 , zero is a minimum; for , 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.
A tangent describes local change
Predict before looking: At , is the slope equal to the height of the curve?
Read the figure
The horizontal axis is input , and both plotted vertical values are function or tangent predictions. The solid square curve and dashed tangent meet at the marked . At , compare with ; at , compare with . These coordinates show where a local slope prediction begins to separate from the curved function.
Connect it to the computation
The tangent slope at is , so for a small change , it predicts . The exact square adds . 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
Open full-size figureDownload data and provenance
The notebook contains the data experiment, plotting code, and recorded figure output. Rerun it to test your changes.
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.
import jax
import jax.numpy as jnpThe differentiation API will operate on the function defined in the next block.
2 Define the square and differentiate it
Write and create a callable derivative with jax.grad.
def f(x):
return x ** 2
derivative = jax.grad(f)The derivative is . jax.grad transforms the scalar-output function, so derivative(3) should return .
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 asparams.
3 Check the derivative at two points
Evaluate the derivative at 3 and at the minimum x=0.
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.
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: 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-8Approximately . 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.pyAbout 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
# 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:
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.
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.
Check the chain rule at three inputs
# 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 , , and .
The inner derivative contributes a factor of . Omitting that factor is a chain-rule error; matching only one point can hide a wrong expression.
Choose a finite-difference scale
# 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 , rounding can erase the input change.
A central difference has truncation error at larger and cancellation/rounding error at very small . 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.
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 . Derive , predict the values at , , and , then verify every prediction with JAX. Explain why the zero at 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
gradreceives 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.
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 NotImplementedErrorReveal the 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 , find the derivative with respect to and then with respect to . Evaluate them at and . 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.
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 NotImplementedErrorShow 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 (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 . Explain why ordinary grad rejects it. Build a scalar objective using their mean, derive its derivative, and check , , and . 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
gradreceives one scalar objective.- Mean and sum remain distinct objectives.
Hints
- Choose the reduction before differentiating.
- Compare the factors analytically.
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 NotImplementedErrorShow a hint
Write the reduction as a mathematical function first: its mean is .
Reveal reference solution and reasoning
# 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.
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 , sweep , and compare with an analytic test case. Each symptom calls for different evidence.
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
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.
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.