Phase 03 / State, randomness & control flow
Compiled loops with lax.scan
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 65 minutes · CPU practice
Replace a fixed-length Python loop with scan and compare final states.
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Pytrees and structured parameters
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/03-state/03-compiled-loops-with-lax-scan/code/main.py.\.venv\Scripts\python.exe phases/03-state/03-compiled-loops-with-lax-scan/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 state-03.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: History: ; Final: .
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
- Separate carry from recorded outputs
- Keep the carry contract invariant
- Differentiate the recurrence by hand
- Compile the repeated transition without a timing promise
The problem
Suppose a simulator keeps part of its current value and adds a new input at each step. Let’s write out four steps so we know what should happen. Then we’ll express the same loop with scan, compare it with Python, and see how changing the retained fraction affects the final value.
The idea
A scan separates the state carried between steps from the outputs collected at each step. This is useful whenever the same rule repeats over time while the state keeps a fixed structure, shape and dtype.
- Initial state
carry₀, inputs[0]Start with an explicit state tree.
- Body
carry₁, output₀ = body(carry₀, input₀)Return the next state and this step’s output.
- Repeat
carryₜ → body → carryₜ₊₁scan collects outputs and returns the final carry.
Every carry leaf keeps the same shape and dtype through the loop. Outputs are stacked along the scan axis; the carry is the state that connects steps.
Conceptual illustration. Verify the computation in the lesson’s Python experiments.
Unroll three steps before compiling the loop
A repeated update is easier to translate when we first make its state flow concrete. Start with carry , add inputs , and emit each new carry: the successive values are . The final carry is the last state ; the output history is the three emitted values .
The diagram’s input nodes feed the step nodes, horizontal arrows pass carry from one step to the next, and downward arrows collect outputs. The edge labels and are the carry values passed onward; the emitted values are . Trace these arrows when deciding which Python variables belong in scan’s carry and which belong in its stacked output.
Carry moves through time; outputs are collected
Predict: What changes if the step emits the old carry instead of the new carry?
Follow each input node into its step node, then follow the horizontal arrows for carry: initial , then , then , and final . Each downward arrow collects the updated carry as an output, producing . Thus final carry and stacked outputs are separate results. Arrow lengths and node spacing show dataflow only, not runtime.
Separate carry from recorded outputs
A scan step has the contract . The carry is the small state needed by the next transition; the output is a record collected for inspection or later computation. They may contain related values without being the same conceptual object.
For the plotted decay recurrence from initial carry zero, the horizontal axis is completed step and the vertical axis is carry value. The four outputs are , approaching the dashed fixed point . The initial zero is not plotted. Use the index to avoid labeling the first update as step zero.
(state_t, input_t) → transition → (state_(t+1), recorded_t)
state: 0 → 1 → 1.5 → 1.75 → 1.875Keep the carry contract invariant
A compiled scan needs a stable carry contract: same pytree structure, shapes and dtypes at every transition. The numerical contents may change, as the carry goes from to , but the container and dimensions stay fixed. A growing Python list or a concatenated history changes the carry shape and violates this contract.
Keep history in the separately stacked outputs, as the example does, while the carry remains one scalar. For a bounded variable-size problem, represent capacity explicitly and use masks as needed; do not make the repeated state grow implicitly each step.
Differentiate the recurrence by hand
Differentiating a recurrence is clearer when the final answer is written as a function of the parameter. With four unit inputs and initial zero, the final carry is , whose derivative at is . The recurrence for the sensitivity is , starting at zero.
Autodiff through scan follows the represented transition and this same dependency through time. It cannot validate whether the model itself is stable or whether the recurrence was encoded correctly. Compare the short polynomial and one changed input sequence before trusting a long run.
Compile the repeated transition without a timing promise
scan describes a fixed repeated transition compactly, while a Python loop inside jit may be unrolled during tracing. This distinction can matter for compilation of long loops, but it does not guarantee that scan is faster for every workload.
The retained receipt checks that Python and scan produce history and final value , and that a changing carry shape is rejected. Those are correctness and contract checks, not a timing result. If measuring later, compare the same steps, inputs and precision and wait for completion.
The carry approaches a fixed point
Predict before looking: Why does the increment between successive states shrink?
Read the figure
The horizontal axis counts completed scan steps, and the vertical axis is carry value. The solid history is at steps one through four; the dashed line is the fixed point . The initial carry is not included, so the first plotted point already follows one update. Notice that the gap to shrinks from to .
Connect it to the computation
The recurrence halves the remaining gap to each step. In scan terms, each updated scalar is carried to the next transition, while each plotted value is also collected in the output history. Use the horizontal step labels to distinguish final carry from the sequence of emitted values.
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 Prepare the inputs
Create main.py in your lesson workspace. Add this first block; use the environment from setup.
# Step 1 — Prepare the inputs
import jax
import jax.numpy as jnpThese explicit inputs define the case that the later checks will verify.
2 Build the computation
Append this block below the inputs in the same file.
# Step 2 — Build the computation: step returns the next scalar carry and one recorded scalar.
def step(carry, increment):
next_value = 0.5 * carry + increment
return next_value, next_value
increments = jnp.array([1., 1., 1., 1.])step returns the next scalar carry and one recorded scalar. scan feeds that carry back into step and stacks the four recorded outputs.
Explain the APIs in this step
jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.
3 Run and check the result
Append the checks, save main.py, and run python main.py from this folder using your course environment.
# Step 3 — Run and check the result
final, history = jax.lax.scan(step, jnp.array(0.), increments)
print("History:", history)
print("Final:", float(final))
assert jnp.allclose(history, jnp.array([1.,1.5,1.75,1.875]))
assert jnp.allclose(final, history[-1])Compare the output to the expected result below before making the exercise change.
Explain the APIs in this step
jax.lax.scan(step_fn, init_carry, xs, length=...): Compiles a sequential loop whose step returns(next_carry, y), yielding(final_carry, stacked_ys).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.
# Step 1 — Prepare the inputs
import jax
import jax.numpy as jnp
# Step 2 — Build the computation: step returns the next scalar carry and one recorded scalar.
def step(carry, increment):
next_value = 0.5 * carry + increment
return next_value, next_value
increments = jnp.array([1., 1., 1., 1.])
# Step 3 — Run and check the result
final, history = jax.lax.scan(step, jnp.array(0.), increments)
print("History:", history)
print("Final:", float(final))
assert jnp.allclose(history, jnp.array([1.,1.5,1.75,1.875]))
assert jnp.allclose(final, history[-1])Run the example
python3 phases/03-state/03-compiled-loops-with-lax-scan/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
# Step 1 — Prepare the inputs
import jax
import jax.numpy as jnp
# Step 2 — Build the computation: step returns the next scalar carry and one recorded scalar.
def step(carry, increment):
next_value = 0.5 * carry + increment
return next_value, next_value
increments = jnp.array([1., 1., 1., 1.])
# Step 3 — Run and check the result
final, history = jax.lax.scan(step, jnp.array(0.), increments)
print("History:", history)
print("Final:", float(final))
assert jnp.allclose(history, jnp.array([1.,1.5,1.75,1.875]))
assert jnp.allclose(final, history[-1])Expected result: History: ; Final: .
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.
History: [1. 1.5 1.75 1.875]
Final: 1.875
History: [1. 1.5 1.75 1.875]
Final: 1.875
Expected carry-shape mismatch
PASS: state-03
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Compare scan to the Python recurrence
# Experiment — Compare scan to the Python recurrence
inputs=jnp.array([1.,-1.,2.,0.])
state=0.
reference=[]
for inc in [1.,-1.,2.,0.]:
state=0.5*state+inc
reference.append(state)
last,observed=jax.lax.scan(step,jnp.array(0.),inputs)
assert jnp.allclose(observed,jnp.array([1.,-0.5,1.75,0.875]))
assert jnp.allclose(observed,jnp.array(reference))
assert jnp.allclose(last,state)Expected: History ; final .
The loop is an independent control-flow reference and the fixed numbers verify time indexing.
Verify state and sensitivity together
# Experiment — Verify state and sensitivity together: The scalar objective is the final state.
# Define `terminal(d)` to carry state across steps with `jax.lax.scan`:
def terminal(d):
return jax.lax.scan(lambda c,u:(d*c+u,d*c+u),jnp.array(0.),increments)[0]
value,sensitivity=jax.value_and_grad(terminal)(0.5)
assert jnp.allclose(value,1.875)
assert jnp.allclose(sensitivity,2.75)
assert jnp.allclose(jax.jit(terminal)(0.5),value)Expected: Final state and sensitivity .
The scalar objective is the final state. Returning the whole history to ordinary grad would need a deliberate scalar reduction.
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.
Make the decay an explicit scalar argument. Differentiate the final value with respect to decay and compare at with the analytic derivative .
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- The initial scalar state, increments, and explicit decay scalar from the exercise.
Outputs
- The final scan value, per-step history, autodiff derivative with respect to decay, and comparison with the analytic value at 0.5.
Invariants to check
- The final value is differentiated through the scan; the derivative check uses decay 0.5 and the stated analytic reference.
Hints
- Pass decay as an explicit scan-transition input.
- Differentiate the function returning only the final carry, then compare at the requested decay.
import jax
import jax.numpy as jnp
def check_scan_decay_derivative(initial, increments, decay):
# TODO: Return the scan history and final carry, then differentiate the final carry with respect to decay.
raise NotImplementedErrorReveal the reference solution
# Exercise solution: Make the decay an explicit scalar argument.
# Define `simulate(decay)` to carry state across steps with `jax.lax.scan`:
def simulate(decay):
def transition(carry, increment):
value = decay * carry + increment
return value, value
return jax.lax.scan(transition, jnp.array(0.), increments)[0]
assert jnp.allclose(jax.grad(simulate)(0.5), 2.75)Record a different output
Practice
Carry the state, but record its squared value. Confirm that final carry still means state.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- An initial scalar carry and a sequence of increments.
Outputs
- The final state and the squared state recorded at every step.
Invariants to check
- The carry remains unsquared between transitions.
- Recorded output has the same leading length as increments.
Hints
- Compute the next state once in the transition.
- Return that state as carry and its square as the scan output.
import jax
import jax.numpy as jnp
def state_and_energy(initial: jax.Array, increments: jax.Array, decay: float = 0.5) -> tuple[jax.Array, jax.Array]:
"""Scan a scalar state while recording its squared energy."""
# TODO: define the transition and return lax.scan outputs.
raise NotImplementedErrorShow a hint
The second returned value is only the recorded output.
Reveal reference solution and reasoning
# Record a different output (Practice): Carry and history need not have the same interpretation.
last,energy=jax.lax.scan(lambda c,u:(0.5*c+u,(0.5*c+u)**2),jnp.array(0.),increments)
assert jnp.allclose(last,1.875)
assert jnp.allclose(energy,jnp.array([1.,2.25,3.0625,3.515625]))Carry and history need not have the same interpretation. The state remains unsquared for the next transition.
Diagnose a growing carry
Challenge
Try appending each input to the carry with concatenate. Explain why scan rejects it and replace it with stacked output.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- A fixed-shape scan carry and a sequence whose values are to be recorded.
Outputs
- A scan result whose carry shape stays fixed while all per-step values are stacked in output.
Invariants to check
- Carry shape and dtype agree on every iteration.
- History length equals the sequence length, including empty sequences.
Hints
- A growing array belongs in the scan output, not in carry.
- Keep the carry fixed and return each new value as the output.
import jax
import jax.numpy as jnp
def collect_scan(initial: jax.Array, values: jax.Array) -> tuple[jax.Array, jax.Array]:
"""Keep a fixed carry and collect each input in the scan history."""
# TODO: implement a fixed-type carry transition with per-step output.
raise NotImplementedErrorShow a hint
The carry shape is part of the loop type.
Reveal reference solution and reasoning
# Diagnose a growing carry (Challenge): The error identifies incompatible carry input/output types.
def growing(c,u):
return jnp.concatenate([c,u[None]]),u
try:
jax.lax.scan(growing,jnp.zeros((0,)),increments)
except TypeError:
print("Expected carry-shape mismatch")
else:
raise AssertionError("Expected scan type failure")
_,saved=jax.lax.scan(lambda c,u:(c,u),jnp.array(0.),increments)
assert jnp.array_equal(saved,increments)The error identifies incompatible carry input/output types. Store per-step values in scan outputs instead of growing the carry.
Diagnose the result
The error identifies incompatible carry input/output types. Store per-step values in scan outputs instead of growing the carry.
Carry forward
- The loop is an independent control-flow reference and the fixed numbers verify time indexing.
- The scalar objective is the final state. Returning the whole history to ordinary grad would need a deliberate scalar reduction.
Keep your evidence
Keep the labeled carry/output transition, Python-reference trajectory, polynomial derivative, compiled value check and growing-carry failure with a fixed-shape repair.
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.