Core Foundation · Local CPULaptop CPULesson 3 of 4 in Phase 03

Phase 03 / State, randomness & control flow

Compiled loops with lax.scan

Revision v0.18.1 ·

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.

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/03-state/03-compiled-loops-with-lax-scan/code/main.py

PowerShell command · repository folder
.\.venv\Scripts\python.exe phases/03-state/03-compiled-loops-with-lax-scan/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: History: [1.,1.5,1.75,1.875][1., 1.5, 1.75, 1.875]; Final: 1.8751.875.

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

  • 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.

Carry state through a compiled loop
  1. Initial statecarry₀, inputs[0]

    Start with an explicit state tree.

  2. Bodycarry₁, output₀ = body(carry₀, input₀)

    Return the next state and this step’s output.

  3. Repeatcarryₜ → 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 00, add inputs [1,2,3][1,2,3], and emit each new carry: the successive values are 1,3,61,3,6. The final carry is the last state 66; the output history is the three emitted values [1,3,6][1,3,6].

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 11 and 33 are the carry values passed onward; the emitted values are 1,3,61,3,6. Trace these arrows when deciding which Python variables belong in scan’s carry and which belong in its stacked output.

Follow each input node into its step node, then follow the horizontal arrows for carry: initial 00, then 11, then 33, and final 66. Each downward arrow collects the updated carry as an output, producing [1,3,6][1,3,6]. Thus final carry and stacked outputs are separate results. Arrow lengths and node spacing show dataflow only, not runtime.

Open full-size diagram

Separate carry from recorded outputs

A scan step has the contract (carryt,inputt)↦(carryt+1,outputt)(carry_t,input_t)\mapsto(carry_{t+1},output_t). 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 ct+1=0.5ct+1c_{t+1}=0.5c_t+1 from initial carry zero, the horizontal axis is completed step and the vertical axis is carry value. The four outputs are 1,1.5,1.75,1.8751,1.5,1.75,1.875, approaching the dashed fixed point 22. 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.875

Keep 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 00 to 1.51.5, 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 1+d+d2+d31+d+d^2+d^3, whose derivative at d=0.5d=0.5 is 2.752.75. The recurrence for the sensitivity is st+1=statet+dsts_{t+1}=state_t+d s_t, 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.

sfinal(d)=1+d+d2+d3dsfinaldd=1+2d+3d2sfinal(0.5)=1.875,sfinal′(0.5)=2.75\begin{aligned}s_{\mathrm{final}}(d)&=1+d+d^2+d^3\\\frac{ds_{\mathrm{final}}}{dd}&=1+2d+3d^2\\s_{\mathrm{final}}(0.5)&=1.875,\qquad s_{\mathrm{final}}\prime(0.5)=2.75\end{aligned}

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 [1,1.5,1.75,1.875][1,1.5,1.75,1.875] and final value 1.8751.875, 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.

Read the figure

The horizontal axis counts completed scan steps, and the vertical axis is carry value. The solid history is 1,1.5,1.75,1.8751,1.5,1.75,1.875 at steps one through four; the dashed line is the fixed point 22. The initial carry 00 is not included, so the first plotted point already follows one update. Notice that the gap to 22 shrinks from 11 to 0.1250.125.

Connect it to the computation

The recurrence ct+1=0.5ct+1c_{t+1}=0.5c_t+1 halves the remaining gap to 22 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

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 Prepare the inputs

Create main.py in your lesson workspace. Add this first block; use the environment from setup.

main.py · append build step 1
# Step 1 — Prepare the inputs
import jax
import jax.numpy as jnp

These 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.

main.py · append build step 2
# 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.

main.py · append build step 3
# 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.

main.py · cumulative Python build
# 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.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
# 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: [1.,1.5,1.75,1.875][1., 1.5, 1.75, 1.875]; Final: 1.8751.875.

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:03:10.197100+00:00 · Python 3.14.3 · JAX 0.9.2 · 1 CPU device

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.

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

Compare scan to the Python recurrence

Compare scan to the Python recurrence · Python experiment
# 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 [1,−0.5,1.75,0.875][1,-0.5,1.75,0.875]; final 0.8750.875.

The loop is an independent control-flow reference and the fixed numbers verify time indexing.

Verify state and sensitivity together

Verify state and sensitivity together · Python experiment
# 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 1.8751.875 and sensitivity 2.752.75.

The scalar objective is the final state. Returning the whole history to ordinary grad would need a deliberate scalar reduction.

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.

Make the decay an explicit scalar argument. Differentiate the final value with respect to decay and compare at 0.50.5 with the analytic derivative 2.752.75.

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.
Your attempt · complete the TODOs
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 NotImplementedError
Reveal the reference solution
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.
Your attempt · complete the TODOs
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 NotImplementedError
Show a hint

The second returned value is only the recorded output.

Reveal reference solution and reasoning
Record a different output · Python solution
# 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.
Your attempt · complete the TODOs
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 NotImplementedError
Show a hint

The carry shape is part of the loop type.

Reveal reference solution and reasoning
Diagnose a growing carry · Python solution
# 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.

Check your understanding

What must remain consistent across scan steps?

Choose one answer

Diagnose the result

The error identifies incompatible carry input/output types. Store per-step values in scan outputs instead of growing the carry.

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

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

Download evidence template

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.

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