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

Phase 03 / State, randomness & control flow

Branches with lax.cond

Revision v0.18.1 ·

Lesson · about 60 minutes · CPU practice

Implement a data-dependent branch that works inside a compiled function.

Phase study guide: preparation, milestones and project evidence

Before you start

Before this: Compiled loops with lax.scan
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/04-branches-with-lax-cond/code/main.py

PowerShell command · repository folder
.\.venv\Scripts\python.exe phases/03-state/04-branches-with-lax-cond/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: 3.03.0

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

  • Locate the decision boundary
  • Trace both branches and check their result types
  • Choose cond or where by the shape of the question
  • Inspect boundary behavior and derivatives

The problem

A Python branch can choose a path when it knows a value. Inside jit, that value may not be available yet. We’ll use lax.cond to make the choice at runtime, check what both branches must return, and compare a single decision with elementwise selection.

The idea

A data-dependent branch needs a control-flow operation that can represent both alternatives in a transformed program. With a scalar predicate, lax.cond selects the result of one branch while requiring compatible result structures from both.

Trace both possibilities, execute the selected rule

A data-dependent choice must be represented inside a staged function because Python cannot choose from a value that will only exist at runtime. lax.cond expresses one scalar decision with two possible branch functions, each following the same input and output contract.

The plot uses input on the horizontal axis and returned magnitude on the vertical axis. It passes through (−3,3)(-3,3), (0,0)(0,0), and (3,3)(3,3): the negative side is negated and the nonnegative side is returned unchanged. The continuous join has a sharp corner, so matching outputs at zero do not imply a unique mathematical derivative there.

magnitude⁡(x)={xx≥0−xx<0\operatorname{magnitude}(x)=\begin{cases}x&x\ge0\\-x&x<0\end{cases}

Locate the decision boundary

For a scalar predicate, cond selects one branch result, but both branch functions are traced to build the staged computation. This is why a Python print or side effect inside a branch is not evidence about which numerical branch ran. The plotted magnitude values show only the returned function.

The execution receipt checks inputs −3-3 and 33, both returning 33, and confirms the expected failure for a traced Python Boolean. Keep tracing behavior separate from runtime selection, and keep both branch computations pure so the program remains meaningful under transformations.

predicate: x>=0
true:  operand x → x
false: operand x → −x
joined result: scalar float

Trace both branches and check their result types

The conditional result must have one stable contract regardless of which predicate value is supplied. Both branches need compatible pytree structure, corresponding leaf shapes and dtypes. If one returns a scalar and the other a vector, the result cannot be represented as one conditional output.

This requirement is independent of whether a test input selects a branch that seems valid. Both branches participate in tracing, so an invalid operation or incompatible output may fail before that specific runtime case is executed. Check branch contracts first, then test the selected numerical results.

Choose cond or where by the shape of the question

Choose control flow to match the shape of the decision. cond expresses one scalar predicate selecting one result for the computation; where selects elementwise from compatible arrays. A vector of independent predicates is an elementwise question or a deliberately batched conditional, not one scalar decision.

Transformations can alter how conditionals are implemented; for example, batching a conditional may turn it into selection. Therefore branch-local side effects or assumptions that an unselected expression is never evaluated are fragile. Keep branch functions pure and expressions valid for their transformed use.

Inspect boundary behavior and derivatives

The magnitude example equals ∣x∣|x|. On negative inputs its slope is −1-1; on positive inputs its slope is 11. At zero the two one-sided slopes differ, so the classical derivative is undefined even though both branches return zero there.

Test a negative value, a positive value and the exact boundary. Changing x≥0x\ge0 to x>0x>0 does not change this magnitude’s value at zero, but it can matter for other branch formulas. Keep numerical branch correctness and differentiability as separate checks.

Read the figure

The horizontal axis is input xx; the vertical axis is the returned magnitude. The V-shaped line gives 33 at both −3-3 and 33, and 00 at the join. On the left arm the rule negates negative inputs; on the right it returns nonnegative inputs. Compare equal distances from zero to see the symmetry and continuity.

Connect it to the computation

The two branch formulas combine to implement ∣x∣|x|. Their slopes are −1-1 to the left and 11 to the right, so the corner at zero marks a change in derivative even though the output has no jump. Read the plot for output behavior; the tracing and branch-selection behavior comes from the control-flow contract, not from this curve.

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: Both branches return the same scalar type.
# Define and JIT-compile `magnitude(x)` so XLA traces and fuses the operations:
@jax.jit
def magnitude(x):
    return jax.lax.cond(x >= 0., lambda v: v, lambda v: -v, x)

Both branches return the same scalar type. cond takes the runtime predicate and passes xx to the selected numerical branch.

Explain the APIs in this step
  • 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 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
print(float(magnitude(-3.)))
assert jnp.allclose(magnitude(-3.), 3.)
assert jnp.allclose(magnitude(2.), 2.)

Compare the output to the expected result below before making the exercise change.

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.

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

# Step 2 — Build the computation: Both branches return the same scalar type.
# Define and JIT-compile `magnitude(x)` so XLA traces and fuses the operations:
@jax.jit
def magnitude(x):
    return jax.lax.cond(x >= 0., lambda v: v, lambda v: -v, x)

# Step 3 — Run and check the result
print(float(magnitude(-3.)))
assert jnp.allclose(magnitude(-3.), 3.)
assert jnp.allclose(magnitude(2.), 2.)

Run the example

python3 phases/03-state/04-branches-with-lax-cond/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: Both branches return the same scalar type.
# Define and JIT-compile `magnitude(x)` so XLA traces and fuses the operations:
@jax.jit
def magnitude(x):
    return jax.lax.cond(x >= 0., lambda v: v, lambda v: -v, x)
# Step 3 — Run and check the result
print(float(magnitude(-3.)))
assert jnp.allclose(magnitude(-3.), 3.)
assert jnp.allclose(magnitude(2.), 2.)

Expected result: 3.03.0

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

3.0
3.0
Expected traced Python Boolean failure
Expected branch shape mismatch
PASS: state-04

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

Reproduce the Python truth-test failure

Reproduce the Python truth-test failure · Python experiment
# Experiment — Reproduce the Python truth-test failure: The repair changes where the decision is represented.
def eager_branch(v):
    if v>=0.:
        return v
    return -v
assert eager_branch(-3.)==3.
try:
    jax.jit(eager_branch)(jnp.array(-3.))
except jax.errors.TracerBoolConversionError:
    print("Expected traced Python Boolean failure")
else:
    raise AssertionError("Expected branch error")
for v in [-3.,0.,2.]:
    assert jnp.allclose(magnitude(v),abs(v))

Expected: The traced Python branch fails; cond gives the correct values for all three cases.

The repair changes where the decision is represented. It does not make xx static or remove the negative case.

Check a batched numerical selection

Check a batched numerical selection · Python experiment
# Experiment — Check a batched numerical selection
values=jnp.array([-3.,-1.,2.,4.])
assert jnp.allclose(jax.vmap(magnitude)(values),jnp.abs(values))
assert jnp.allclose(jax.vmap(jax.grad(magnitude))(values),jnp.array([-1.,-1.,1.,1.]))

Expected: Magnitudes [3,1,2,4][3,1,2,4] and slopes [−1,−1,1,1][-1,-1,1,1].

Correct values under batching do not imply a conditional branch remains lazy after every transformation.

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.

Write a compiled function that applies 2x2x when xx is positive and x−2x-2 otherwise. Check positive, negative, and zero inputs.

Show a writing guide and starter scaffold

How to write this exercise code

Learner-only inputs, outputs, checks and hints

Inputs

  • A scalar or array of values evaluated as scalar calls.

Outputs

  • A JIT-compatible piecewise function: twice x when positive, otherwise x minus two.

Invariants to check

  • Both lax.cond branches return identical shape and dtype.
  • The zero boundary follows the non-positive branch.

Hints

  • Use x > 0 as the predicate.
  • Pass x as the operand and use one scalar result from each branch.
Your attempt · complete the TODOs
import jax
import jax.numpy as jnp

@jax.jit
def piecewise_rule(x: jax.Array) -> jax.Array:
    """Return 2*x for positive x and x-2 otherwise."""
    # TODO: express the runtime branch with jax.lax.cond.
    raise NotImplementedError

1. Key functions & syntax to use:

  • 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.
Reveal the reference solution
Reference solution
# Exercise solution
# Define and JIT-compile `choose_update(x)` so XLA traces and fuses the operations:
@jax.jit
def choose_update(x):
    return jax.lax.cond(x > 0., lambda v: v * 2., lambda v: v - 2., x)
assert jnp.allclose(choose_update(3.), 6.)
assert jnp.allclose(choose_update(-3.), -5.)
assert jnp.allclose(choose_update(0.), -2.)

Match a changed piecewise rule

Practice

Implement x2x^2 for x>1x>1 and 2x2x otherwise. Derive outputs at −1-1,11,22 and derivatives away from 11.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • A scalar input v.

Outputs

  • The value of v squared for v>1, and 2v otherwise.

Invariants to check

  • At v=1 the false branch is chosen.
  • Both branches return a scalar of compatible dtype.

Hints

  • Set the predicate to v > 1.
  • Check derivatives only away from the branch boundary.
Your attempt · complete the TODOs
import jax
import jax.numpy as jnp

def changed_rule(v: jax.Array) -> jax.Array:
    """Implement the two-branch scalar rule."""
    # TODO: use lax.cond with the exact boundary specified in the task.
    raise NotImplementedError
Show a hint

At x=1x=1 the false branch is selected.

Reveal reference solution and reasoning
Match a changed piecewise rule · Python solution
# Match a changed piecewise rule (Practice)
def piecewise(v):
    return jax.lax.cond(v>1.,lambda z:z*z,lambda z:2*z,v)
assert jnp.allclose(jax.vmap(piecewise)(jnp.array([-1.,1.,2.])),jnp.array([-2.,2.,4.]))
assert jnp.allclose(jax.grad(piecewise)(-1.),2.)
assert jnp.allclose(jax.grad(piecewise)(2.),4.)

The values check the exact boundary and both formulas; the derivatives are checked only at smooth points.

Repair incompatible branch shapes

Challenge

Return a scalar in one branch and a length-two vector in the other, reproduce the error, then define a consistent two-value result.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • A scalar input v used by two branch functions.

Outputs

  • A pair of scalar values with the same shape and dtype regardless of the predicate.

Invariants to check

  • lax.cond requires compatible results from both branches.
  • The pair gives the same semantic meaning on both paths.

Hints

  • Choose what the two returned components represent first.
  • Construct a length-two array in each branch.
Your attempt · complete the TODOs
import jax
import jax.numpy as jnp

def consistent_pair(v: jax.Array) -> jax.Array:
    """Return a consistent length-two result from both runtime branches."""
    # TODO: make both cond branches return matching shape and dtype.
    raise NotImplementedError
Show a hint

Decide what each output component means before padding.

Reveal reference solution and reasoning
Repair incompatible branch shapes · Python solution
# Repair incompatible branch shapes (Challenge)
try:
    jax.lax.cond(True,lambda x:x,lambda x:jnp.stack([x,x]),jnp.array(2.))
except TypeError:
    print("Expected branch shape mismatch")
else:
    raise AssertionError("Expected result type error")
def pair(v):
    return jax.lax.cond(v>=0.,lambda x:jnp.stack([x,x*x]),lambda x:jnp.stack([-x,x*x]),v)
assert jnp.allclose(pair(jnp.array(-2.)),jnp.array([2.,4.]))

A branch mismatch is a result-contract error even when the current predicate is known. Here the repaired output explicitly means [magnitude,square].

Check your understanding

Can one cond branch return a scalar and the other a length-three array?

Choose one answer

Diagnose the result

A branch mismatch is a result-contract error even when the current predicate is known. Here the repaired output explicitly means [magnitude,square].

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

Carry forward

  • The repair changes where the decision is represented. It does not make xx static or remove the negative case.
  • Correct values under batching do not imply a conditional branch remains lazy after every transformation.

Keep your evidence

Download evidence template

Keep the branch-contract diagram, eager/jit failure and repair, boundary cases, batched values and off-boundary derivatives, and the shape-mismatch diagnosis.

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

Phase 03 Integration Project

Bring this phase together: A deterministic batched simulation

Checkpoint to prove: Replay the same experiment with saved state and keys; explain the update order.

Copy projects/foundation-toolkit/starter/toolkit.py to projects/foundation-toolkit/my_toolkit.py and write your code in projects/foundation-toolkit/my_toolkit.py. Run python3 projects/foundation-toolkit/tests/check.py --implementation projects/foundation-toolkit/my_toolkit.py --stage 4 from the top-level folder to verify stage 4.