Phase 02 / JAX transformations
Tracing, static arguments, and recompilation
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 60 minutes · CPU practice
Explain the staging boundary and repair configuration versus runtime-control-flow mistakes.
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Compile a function with jit
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/05-tracing-static-arguments-and-recompilation/code/main.py.\.venv\Scripts\python.exe phases/02-transforms/05-tracing-static-arguments-and-recompilation/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-05.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: Sum: ; Mean: . These mode choices can use separate compiled specializations.
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
- Distinguish runtime array values from shape/dtype metadata and static configuration.
- Inspect a staged computation with make_jaxpr.
- Explain a Python value-dependent branch failure under jit.
- Use static configuration or JAX control flow according to the kind of decision.
The problem
A function works until you put a Python if statement inside jit. Why does that change things? We’ll separate what Python knows while tracing from what the program learns at runtime. Then you’ll choose between a small static configuration and an array-based decision, rather than making every difficult argument static.
The idea
Tracing observes how Python builds an array computation from abstract inputs. Static arguments are part of that program-building decision; dynamic array values are data for the resulting computation. Keep a small call ledger to separate these roles.
Build a call ledger before diagnosing recompilation
A trace count is easier to interpret when each call changes only one thing. Start with two arrays of the same shape, dtype and static mode but different values; then change shape; then change mode. This separates new runtime data from requests to construct a different staged computation.
In the retained ledger, calls one and two both use shape , float32 and sum, while outputs change from to . The next call uses shape ; the last changes mode to mean. Read the table as this lesson’s observed signature changes, not as a universal count of JAX cache entries.
The specialization key separates changing data from program choices
Predict: If only the array entries change, which ledger fields remain fixed?
The table nodes are four calls. The first two carry different arrays through the same shape, dtype and static-mode signature, so their sums change from to while the requested staged computation stays the same. The third changes shape and the fourth changes static mode. Read each arrow as the next call in this controlled sequence; the table is not a global cache counter.
Separate metadata, configuration, and data
A staged function needs a clear boundary between array values that flow at runtime and choices that determine which program is built. The values are data; shape describes their array; sum or mean selects a reduction rule.
Here the finite mode string is treated as static configuration. With sum, returns ; with mean, it returns . Marking a changing batch as static would make each value part of specialization and is not the right way to express ordinary runtime data. Choose the boundary from what the function computes, not merely to silence an error.
Read a tiny staged program
make_jaxpr lets us inspect the staged array computation when we need to understand what tracing represented. For the square-and-sum function, the retained output shows multiplication followed by reduce_sum, producing a scalar. That connects the source operations to the traced program without needing to infer behavior from timing.
A Python print may run during tracing, but it is not itself an array operation in the jaxpr. The exact formatting and primitive names can vary, so focus on the dataflow and reduction. Use a tiny example and compare the traced operations with the source rather than treating a jaxpr dump as a stable user-facing format.
Why a Python if can fail
Python if asks Python to choose a branch immediately. During tracing, a dynamic scalar argument is represented by a tracer whose runtime Boolean value is not yet available to Python. Thus if x > 0 can fail even though the same function works eagerly for a concrete number.
The failure identifies a staging mismatch: the decision depends on runtime array data. Keep that distinction clear from static configuration, which is intentionally known while specializing. For runtime branching, use a JAX control-flow form such as lax.cond; for an elementwise choice over arrays, use selection with compatible shapes.
Make configuration choices explicit
The reduce_values example uses a small finite mode to select either sum or mean. Its result depends on both inputs: the array supplies values, and the static mode chooses the reduction. Unknown mode strings should be rejected, because silently mapping a typo to a valid reduction can produce plausible but incorrect results.
In the observed calls, sum of is , while mean is . Keep the function identity stable and make the static choice explicit. Changing array values with the same shape and mode changes the answer without changing the intended computation; changing mode requests a different specialization choice.
Inspect tracing without confusing it with runtime logging
A Python print inside a jitted function reports tracing activity, not every execution of the numerical program. If a compatible second call produces no print, that is consistent with reuse of the trace; it does not show that the function did not run.
Use trace observations to diagnose a small controlled call sequence, and use JAX runtime debugging facilities when the question concerns runtime values. The execution output here separately confirms the computed sum and the jaxpr. Avoid turning one print count into a claim about all compilations or device executions.
Carry this boundary into the next phase
The next lessons make random keys, parameter trees, repeated state and branches explicit. The same classification helps each one: values needed to choose or update the next numerical result must be represented as runtime data or state; program choices known during specialization can define a static configuration.
When a traced program fails, first identify whether the problematic value is an array tracer or a true configuration choice. Then choose the operation that matches the question. This is more reliable than marking arbitrary inputs static, especially when their values change from call to call.
Call signatures separate runtime values from specialization choices
Predict before looking: Which call changes only data values, and which calls request a different staged program?
Read the figure
Read each row as a call to the compiled reduction. The value column shows runtime array data; the signature columns show shape, dtype and static mode. Calls one and two both use but return and from different values. Call three changes the shape to ; call four changes the mode to mean and returns . The table’s exact signatures belong to this call sequence.
Connect it to the computation
Changing values while shape, dtype and mode remain fixed changes the result without changing the requested computation. A shape or static-mode change requests another specialization. Use the ledger to predict which property changed before inspecting traces; do not interpret it as a universal cache or compilation counter.
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 tracing and array operations
Import jax and jax.numpy for the reduction and JIT wrapper.
import jax
import jax.numpy as jnpThe data values will remain ordinary JAX array inputs; the mode selects Python control flow.
2 Make the reduction mode static during tracing
Define sum and mean branches, reject unknown modes, and mark mode as a static JIT argument.
def reduce_values(x, mode):
if mode == "sum":
return x.sum()
if mode == "mean":
return x.mean()
raise ValueError("mode must be sum or mean")
# Wrap with `jax.jit` (`compiled`) so XLA traces and compiles the function.
compiled = jax.jit(reduce_values, static_argnames=("mode",))Python must know mode while tracing because it chooses a branch. Each distinct static value can lead to a separate compiled specialization.
Explain the APIs in this step
array.sum(axis=...): Adds values along the selected axis; that axis is removed unlesskeepdims=True.array.mean(axis=..., keepdims=...): Averages values along the selected axis; that axis is removed unlesskeepdims=True.jax.jit(fn) / @jax.jit: Traces a function for its input signatures and compiles it; changed shapes, dtypes, or static arguments can trigger another compilation.
3 Run and check both compiled specializations
Apply sum and mean to [1,2,3] and compare them with their known results.
x = jnp.array([1., 2., 3.])
assert jnp.allclose(compiled(x, mode="sum"), 6.)
assert jnp.allclose(compiled(x, mode="mean"), 2.)The outputs 6 and 2 distinguish the two reduction rules while using the same data array.
Explain the APIs in this step
jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.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 reduce_values(x, mode):
if mode == "sum":
return x.sum()
if mode == "mean":
return x.mean()
raise ValueError("mode must be sum or mean")
# Wrap with `jax.jit` (`compiled`) so XLA traces and compiles the function.
compiled = jax.jit(reduce_values, static_argnames=("mode",))
x = jnp.array([1., 2., 3.])
assert jnp.allclose(compiled(x, mode="sum"), 6.)
assert jnp.allclose(compiled(x, mode="mean"), 2.)Run the example
python3 phases/02-transforms/05-tracing-static-arguments-and-recompilation/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
# Tracing, static arguments, and recompilation
import jax
import jax.numpy as jnp
def reduce_values(x, mode):
if mode == "sum":
return x.sum()
if mode == "mean":
return x.mean()
raise ValueError("mode must be sum or mean")
# Wrap with `jax.jit` (`compiled`) so XLA traces and compiles the function.
compiled = jax.jit(reduce_values, static_argnames=("mode",))
x = jnp.array([1., 2., 3.])
print("Sum:", float(compiled(x, mode="sum")))
print("Mean:", float(compiled(x, mode="mean")))
assert jnp.allclose(compiled(x, mode="sum"), 6.)
assert jnp.allclose(compiled(x, mode="mean"), 2.)Expected result: Sum: ; Mean: . These mode choices can use separate compiled specializations.
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.
Sum: 6.0
Mean: 2.0
Tracing sum_squares; shape: (3,)
{ lambda ; a:f32[3]. let
b:f32[3] = mul a a
c:f32[] = reduce_sum[axes=(0,) out_sharding=None] b
in (c,) }
Expected dynamic Boolean conversion error
PASS: transforms-05
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Look at the staged numerical work
# Experiment — Look at the staged numerical work: The second call supplies new values with the same shape/dtype.
def sum_squares(values):
print("Tracing sum_squares; shape:", values.shape)
return jnp.sum(values * values)
print(jax.make_jaxpr(sum_squares)(x))
# Wrap with `jax.jit` (`staged_squares`) so XLA traces and compiles the function.
staged_squares = jax.jit(sum_squares)
assert jnp.allclose(staged_squares(x), 14.)
assert jnp.allclose(staged_squares(x + 1.), 29.)Expected: The representation contains numerical multiplication and reduction. Trace prints can appear during staging, not as one guaranteed print per call.
The second call supplies new values with the same shape/dtype. The numerical result changes while the computation structure can be reused.
Reproduce and repair a dynamic branch
# Experiment — Reproduce and repair a dynamic branch
def python_branch(value):
if value > 0.:
return value ** 2
return -value
assert python_branch(-2.) == 2.
try:
jax.jit(python_branch)(jnp.array(-2.))
except jax.errors.TracerBoolConversionError:
print("Expected dynamic Boolean conversion error")
else:
raise AssertionError("Expected a traced Python branch to fail")
def runtime_branch(value):
return jax.lax.cond(value > 0., lambda z: z ** 2, lambda z: -z, value)
# Wrap with `jax.jit` (`compiled_branch`) so XLA traces and compiles the function.
compiled_branch = jax.jit(runtime_branch)
assert jnp.allclose(compiled_branch(jnp.array(-2.)), 2.)
assert jnp.allclose(compiled_branch(jnp.array(3.)), 9.)Expected: The Python branch fails under jit with a tracer Boolean conversion error. The staged conditional returns and .
The test expects a particular category of error and confirms the repair for both branches. A broad catch-all would hide unrelated failures.
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 · Extend reduce_values with a static max mode while preserving sum and mean. Reject unknown modes. Verify all three modes on and on .
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- A reducer supporting sum, mean, and max.
- Two arrays containing positive and negative values.
Outputs
- Jitted results for all supported modes and an error for an unknown mode.
Invariants to check
- The mode is static configuration.
- Unknown modes are rejected.
- Both signs of input are checked.
Hints
- Keep array values dynamic and specialize the mode.
- Reuse the function for changed array values.
import jax
import jax.numpy as jnp
def reduce_values(values, mode):
# TODO: implement the declared reductions and reject unknown modes
raise NotImplementedError
def verify_reductions():
# TODO: compile with mode static and check both input sets
raise NotImplementedErrorReveal the reference solution
# Exercise solution
def choose_reduction(values, mode):
if mode == "sum":
return values.sum()
if mode == "mean":
return values.mean()
if mode == "max":
return values.max()
raise ValueError("unknown mode")
# Wrap with `jax.jit` (`choose`) so XLA traces and compiles the function.
choose = jax.jit(choose_reduction, static_argnames=("mode",))
for values in (x, jnp.array([-4., -1., -2.])):
for mode, reference in (("sum", jnp.sum), ("mean", jnp.mean), ("max", jnp.max)):
assert jnp.allclose(choose(values, mode=mode), reference(values))
try:
choose(x, mode="typo")
except ValueError:
pass
else:
raise AssertionError("Unknown mode should fail")Keep runtime values dynamic
Practice
Implement an elementwise absolute value with a numerical selection, jit it, and test mixed-sign vectors. Explain why making the whole vector static is inappropriate.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Mixed-sign numeric vectors.
- An elementwise absolute-value function.
Outputs
- Jitted results for each vector.
Invariants to check
- Numerical values remain runtime data.
- Output shape matches its input.
Hints
- Use elementwise numerical selection.
- Do not make the entire vector static.
import jax
import jax.numpy as jnp
def elementwise_absolute(values):
# TODO: select the nonnegative magnitude elementwise
raise NotImplementedError
def verify_absolute(compiled_absolute, vectors):
# TODO: test the compiled function on each mixed-sign input
raise NotImplementedErrorShow a hint
jnp.where selects elementwise; both candidate arrays are computed expressions. It is not a Python branch per element.
Reveal reference solution and reasoning
# Keep runtime values dynamic (Practice): The vector values are runtime data.
def elementwise_absolute(values):
return jnp.where(values >= 0., values, -values)
# Wrap with `jax.jit` (`compiled_absolute`) so XLA traces and compiles the function.
compiled_absolute = jax.jit(elementwise_absolute)
for values in (jnp.array([-2., 0., 3.]), jnp.array([5., -4., -1.])):
assert jnp.allclose(compiled_absolute(values), jnp.abs(values))The vector values are runtime data. Elementwise selection preserves a fixed output shape and does not need a static array.
Audit a shape-dependent specialization
Challenge
Run a jitted sum-of-squares function for lengths and , each with two different value sets. Compare to a loop calculation. Explain which changes can affect specialization and which are ordinary runtime data.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- A jitted sum-of-squares function.
- Inputs of lengths three and five with two value sets each.
Outputs
- Compiled results and an independent Python-loop reference.
- A note distinguishing shape from data-value changes.
Invariants to check
- Each element contributes once.
- Separate changed shape from changed values.
- Do not use elapsed time alone to claim a trace count.
Hints
- Inspect shape metadata directly.
- Build the reference with a plain Python loop.
import jax
import jax.numpy as jnp
def sum_squares(values):
# TODO: define the numerical reduction
raise NotImplementedError
def audit_shapes(compiled, value_sets):
# TODO: compare compiled results with an independent loop reference
raise NotImplementedErrorShow a hint
Do not use elapsed time alone to infer whether tracing occurred. Values and shape are different inputs to your reasoning.
Reveal reference solution and reasoning
# Audit a shape-dependent specialization (Challenge)
def plain_sum_squares(values):
return jnp.sum(values ** 2)
# Wrap with `jax.jit` (`compiled_squares`) so XLA traces and compiles the function.
compiled_squares = jax.jit(plain_sum_squares)
for length in (3, 5):
for shift in (0., 1.):
values = jnp.arange(length, dtype=jnp.float32) + shift
expected = sum(float(v) ** 2 for v in values)
assert jnp.allclose(compiled_squares(values), expected)Changing the length changes shape metadata and can need a new specialization. Changing shift changes element values at the same shape/dtype. The test verifies correctness across both kinds of changes without inventing a guaranteed compilation count.
Diagnose the result
For a tracer Boolean conversion error, inspect the Python truth test. For an unhashable static argument, reconsider whether the object is really configuration. For repeated setup, inspect function recreation, shapes/dtypes, and static values. For missing Python logs, distinguish tracing from runtime execution. Always verify both branches and preserve unknown-mode errors rather than returning a plausible fallback.
Carry forward
- Python executes while staging; numerical array operations form the runtime computation.
- Static configuration and dynamic numerical data have different roles.
- Use runtime control flow for runtime decisions and compatible branch returns.
- Inspect evidence of tracing separately from numerical correctness and timing.
Keep your evidence
Keep the small jaxpr observation, the expected tracer Boolean error, checks of both repaired branches, all static reduction modes including invalid-mode rejection, and shape/value-change cases. Do not infer compilation counts from timing alone.
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.
Primary references
Phase 02 Integration Project
Bring this phase together: Compare scalar, vmap, autodiff, and changed-shape JIT behavior
Checkpoint to prove: Compose grad, vmap, and jit; explain what each transformation changes.
Work in projects/transforms-audit/starter/model.py. Complete stages 1 and 2 for independent calculations and changed-condition diagnosis, then retain the stage 3 evidence with --evidence-dir runs/transforms-audit. Stage 4 integrates the checks. Learner commands explicitly select the starter; --implementation solution is instructor reference execution. This bounded practice does not certify the entire phase or target hardware.