Phase 02 / JAX transformations
Losses and value_and_grad
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 55 minutes · CPU practice
Derive and audit a scalar loss, its parameter gradient, and stable versus unstable updates.
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Your first gradient
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/02-losses-and-value-and-grad/code/main.py.\.venv\Scripts\python.exe phases/02-transforms/02-losses-and-value-and-grad/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 transforms-02.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: Loss ≈ ; gradient ≈ . Small floating-point differences are normal.
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
- Derive a batch mean-squared-error gradient for one weight.
- Use value_and_grad to return a loss and its parameter gradient together.
- Predict how sum versus mean and residual scaling change an update.
- Verify an update with independent arithmetic and diagnose an unstable step.
The problem
Let’s turn the slope idea into a learning problem. We have three measurements and a model with one weight. How should that weight change to make its predictions better? We’ll calculate the prediction errors, combine them into one loss, and check the gradient by hand before asking JAX for the same result.
The idea
A loss value tells us how the current prediction is scored. Its derivative tells us how a small parameter change affects that score locally. value_and_grad returns both so we can inspect progress and choose an update without confusing the two quantities.
Read the value and derivative at the same point
We need both the score and its direction because they answer different questions: the loss says how this parameter setting performs, while the derivative predicts how a small adjustment changes that score. For the separate objective , at the loss is and the slope is , so increasing slightly should lower the loss. At , the slope is zero but the loss is still .
The plot has weight on both horizontal axes, loss in the upper panel and loss-per-weight in the lower. For the lesson’s unshifted data, gives , and gives . A zero derivative is a stationary point; it does not generally mean zero loss. Adding a constant shifts loss values without moving the derivative’s zero.
From three residuals to one decision
A batch needs one scalar score before grad can return a single objective gradient. For each row, compute prediction, subtract its target, square the residual, then average the squared errors. This order makes the reduction and its scale visible.
With inputs , targets , and , predictions are , residuals are , and squared errors sum to . The mean loss is . At , predictions match all targets and the loss is zero. These hand values check both the model and the averaging before differentiating.
Derive the gradient independently
Differentiating the mean loss preserves one contribution from every example, then averages them. Each squared residual contributes twice the residual, and differentiating the prediction contributes the input .
For this dataset, each residual is , so the loss is . At , its slope is . The negative sign predicts that raising the weight lowers the loss. Since gradient descent subtracts the gradient, the update should move upward; this direction check can reveal a missing minus sign before running code.
Read value_and_grad as an interface
value_and_grad returns the objective value and its derivative together, which keeps evaluation and update tied to the same parameter value. In the scalar example both outputs have shape . With a vector parameter the gradient has the parameter’s shape, and with a parameter pytree it has matching structure; it does not acquire the batch shape just because the loss used a batch.
By default, the first positional argument is differentiated. Passing data as later arguments makes the boundary explicit: differentiate parameters while treating this batch as input. The returned pair is an interface contract, not a promise of speed. Inspect both value and gradient shapes when moving from this scalar example to a model.
Predict whether a step improves the objective
An update is useful only if its sign and size move the objective in the intended direction. Starting at , with gradient and step size , gradient descent gives , closer to the zero-loss weight ; the loss falls to about .
For this quadratic the error is multiplied by each step. At , that multiplier is : the update crosses the solution and leaves a larger error, so loss rises. Read this as a property of this quadratic and dataset, not a universal learning-rate rule. The plotted slope tells direction; this calculation tells whether the chosen step overshoots.
Separate objective value from useful metrics
A mean loss compresses a batch to one number, so it can hide which example is still wrong. Keep residuals or another diagnostic as auxiliary output when they help explain behavior. With has_aux=True, value_and_grad differentiates only the scalar loss and carries auxiliary data alongside its value.
For example, predictions can be useful to inspect while optimizing their mean squared error. They are not a second objective merely because the function returns them. Read the result nesting carefully: objective plus auxiliary data is paired with the gradient. This distinction prevents logging outputs from being mistaken for quantities that receive gradients.
Loss and derivative use separate vertical scales
Predict before looking: At which weight is the derivative zero, and what is the loss at that same weight?
Read the figure
Both panels use the same horizontal weight coordinate. The upper vertical axis is mean squared loss; the lower is derivative per weight unit. At , read loss and slope ; at , both are zero for this dataset. Follow the lower curve to its zero, then read the upper curve at that same weight. The panels have separate units and scales.
Connect it to the computation
The lower curve crosses zero at the minimum of this convex quadratic, while the upper curve gives the objective value there. A stationary point need not have zero loss: adding a constant would lift only the upper curve and leave the lower zero crossing fixed. Use the two panels together to distinguish objective height from local direction.
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 differentiation and array operations
Import jax and jax.numpy for the loss and its derivative.
import jax
import jax.numpy as jnpThe loss below is scalar-valued, which is the input contract for value_and_grad.
2 Define the three-example squared-error loss
Set , choose targets , and average squared prediction errors for a scalar weight.
x = jnp.array([1., 2., 3.])
y = 2. * x
def loss(weight):
return jnp.mean((weight * x - y) ** 2)At weight 1, the residuals are [-1,-2,-3]. The mean squared error is 14/3; averaging matters because it scales the gradient too.
Explain the APIs in this step
jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.jnp.mean(x, axis=..., keepdims=...): Averages JAX array values along the selected axis.
3 Compute loss and gradient in one evaluation
Call value_and_grad at weight 1 and compare both results with hand calculations.
value, gradient = jax.value_and_grad(loss)(1.0)
assert jnp.allclose(value, 14./3.)
assert jnp.allclose(gradient, -28./3.)The derivative is the mean of , giving at . Checking value and derivative catches errors in both the objective and its reduction.
Explain the APIs in this step
jax.value_and_grad(loss_fn)(params, ...): Transforms a pure function to return its value and gradient(value, grads)from the same evaluation.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
x = jnp.array([1., 2., 3.])
y = 2. * x
def loss(weight):
return jnp.mean((weight * x - y) ** 2)
value, gradient = jax.value_and_grad(loss)(1.0)
assert jnp.allclose(value, 14./3.)
assert jnp.allclose(gradient, -28./3.)Run the example
python3 phases/02-transforms/02-losses-and-value-and-grad/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
# Losses and value_and_grad: A loss value tells us how the current prediction is scored.
import jax
import jax.numpy as jnp
x = jnp.array([1., 2., 3.])
y = 2. * x
def loss(weight):
return jnp.mean((weight * x - y) ** 2)
value, gradient = jax.value_and_grad(loss)(1.0)
print("Loss:", float(value), "gradient:", float(gradient))
assert jnp.allclose(value, 14./3.)
assert jnp.allclose(gradient, -28./3.)Expected result: Loss ≈ ; gradient ≈ . Small floating-point differences are normal.
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.
Loss: 4.6666669845581055 gradient: -9.333333969116211
weight / loss / gradient: 0.0 18.666667938232422 -18.666667938232422
weight / loss / gradient: 1.0 4.6666669845581055 -9.333333969116211
weight / loss / gradient: 2.0 0.0 0.0
PASS: transforms-02
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Check JAX against the handwritten gradient
# Experiment — Check JAX against the handwritten gradient: A derivative describes the direction.
def analytic_loss_gradient(weight):
return 2. * jnp.mean((weight * x - y) * x)
for weight in (0., 1., 2.):
value_here, grad_here = jax.value_and_grad(loss)(weight)
print("weight / loss / gradient:", weight, float(value_here), float(grad_here))
assert jnp.allclose(grad_here, analytic_loss_gradient(weight))Expected: The gradients are , , and ; the losses are , , and .
A derivative describes the direction. A new objective value is obtained only after a chosen update and a new evaluation.
Return residuals without changing the objective
# Experiment — Return residuals without changing the objective
def loss_with_residuals(weight):
residuals = weight * x - y
return jnp.mean(residuals ** 2), residuals
(aux_value, residuals), aux_gradient = jax.value_and_grad(loss_with_residuals, has_aux=True)(1.)
# Check tensor shape invariant: `residuals.shape == (3,)`
assert residuals.shape == (3,)
assert jnp.allclose(residuals, jnp.array([-1., -2., -3.]))
assert jnp.allclose(aux_value, value)
assert jnp.allclose(aux_gradient, gradient)Expected: The objective and gradient match the original; residuals are a separate array of shape .
The return structure separates logging data from a scalar optimization target. Reducing or selecting the wrong return value is a common source of interface bugs.
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 · Starting from , calculate the next weight and loss for and . Verify both. Explain the overshoot using the error multiplier rather than concluding that autodiff is wrong.
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- The lesson model inputs and targets.
- Starting weight 1 and learning rates 0.1 and 0.3.
Outputs
- Each candidate weight and its post-update loss.
Invariants to check
- Both updates use a gradient evaluated at the same starting weight.
- Loss is recomputed at each candidate.
- Overshoot is explained through the objective, not an autodiff failure.
Hints
- Keep the initial gradient separate from the candidate evaluations.
- Compare each rate independently.
import jax
import jax.numpy as jnp
def compare_updates(loss, initial_weight, rates):
# TODO: compute the initial gradient and evaluate each candidate
raise NotImplementedErrorReveal the reference solution
# Exercise solution
small_step = 1. - 0.1 * gradient
large_step = 1. - 0.3 * gradient
assert jnp.allclose(small_step, 29. / 15.)
assert loss(small_step) < value
assert loss(large_step) > value
assert jnp.allclose(loss(2.), 0.)Make the data boundary explicit
Practice
Rewrite loss(weight, inputs, targets) with data as arguments. Use value_and_grad and verify the gradient at against the hand-derived result.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- A scalar weight and input/target arrays passed as arguments.
- Starting weight 1.
Outputs
- Loss and weight gradient from
value_and_grad.
Invariants to check
- Data are explicit function inputs.
- Differentiation is with respect to the weight.
- Compare with an independent hand result.
Hints
- Place the parameter as the first argument.
- Use the same fixed data in both checks.
import jax
import jax.numpy as jnp
def explicit_loss(weight, inputs, targets):
# TODO: return the scalar batch objective
raise NotImplementedError
def check_value_and_gradient(inputs, targets):
# TODO: evaluate value_and_grad at the requested weight
raise NotImplementedErrorShow a hint
Default differentiation is with respect to the first argument, not every floating-point input.
Reveal reference solution and reasoning
# Make the data boundary explicit (Practice)
def explicit_loss(weight, inputs, targets):
return jnp.mean((weight * inputs - targets) ** 2)
v_explicit, g_explicit = jax.value_and_grad(explicit_loss)(1., x, y)
assert jnp.allclose(v_explicit, 14. / 3.)
assert jnp.allclose(g_explicit, -28. / 3.)Keeping data explicit prepares the function for new batches and avoids accidentally closing over stale training data.
Audit reduction and batch replication
Challenge
Compare the mean and sum loss gradients. Repeat this batch twice and predict the gradient under both reductions. Explain which learning-rate adjustment makes a sum-based update match a mean-based update.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Inputs and targets for one batch.
- A repeated copy of that batch.
Outputs
- Mean-loss and sum-loss gradients before and after repetition.
Invariants to check
- Repeating the batch preserves a mean gradient.
- A sum gradient scales with repeated example count.
- State the learning-rate adjustment that matches the update.
Hints
- Keep mean and sum in separate functions.
- Track the batch duplication factor.
import jax
import jax.numpy as jnp
def compare_reductions_and_repeats(inputs, targets, weight):
# TODO: compute both reductions before and after repeating data
raise NotImplementedErrorShow a hint
Duplicate data are not new information. Track the factor in the mathematical objective.
Reveal reference solution and reasoning
# Audit reduction and batch replication (Challenge)
def summed_loss(weight, inputs, targets):
return jnp.sum((weight * inputs - targets) ** 2)
g_mean = jax.grad(explicit_loss)(1., x, y)
g_sum = jax.grad(summed_loss)(1., x, y)
x_twice, y_twice = jnp.tile(x, 2), jnp.tile(y, 2)
assert jnp.allclose(g_sum, len(x) * g_mean)
assert jnp.allclose(jax.grad(explicit_loss)(1., x_twice, y_twice), g_mean)
assert jnp.allclose(jax.grad(summed_loss)(1., x_twice, y_twice), 2. * g_sum)
assert jnp.allclose(1. - 0.1 * g_mean, 1. - (0.1 / len(x)) * g_sum)Mean gradients stay fixed under exact batch replication; sum gradients scale with the count. Compensating the rate by 1/N makes this particular SGD update match.
Diagnose the result
If an update increases loss, verify the subtraction sign, reduction scale, and learning rate before blaming the gradient transform. If the objective is nonscalar, inspect the residual and reduction shapes. If metrics look plausible but gradients are wrong, compare against the independently derived formula at more than one parameter setting. These checks separate implementation mistakes from an unstable optimization choice.
Carry forward
- A scalar reduction defines both the objective and the update scale.
- value_and_grad returns a value/gradient pair; the gradient follows the parameter shape.
- Independent arithmetic and multiple parameter settings provide a useful numerical check.
- Descent direction does not guarantee descent with an arbitrary step size.
Keep your evidence
Keep handwritten loss/gradient arithmetic, checks at three weights, small/large-rate update results, auxiliary residuals, and mean-versus-sum batch-replication results. Explain the update-scale change.
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.