Phase 03 / State, randomness & control flow
Branches with lax.cond
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
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.
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/04-branches-with-lax-cond/code/main.py.\.venv\Scripts\python.exe phases/03-state/04-branches-with-lax-cond/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-04.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:
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
- 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 , , and : 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.
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 and , both returning , 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 floatTrace 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 . On negative inputs its slope is ; on positive inputs its slope is . 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 to 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.
Both branches form one magnitude function
Predict before looking: What happens on each side of zero?
Read the figure
The horizontal axis is input ; the vertical axis is the returned magnitude. The V-shaped line gives at both and , and 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 . Their slopes are to the left and 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
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: 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 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.
# 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.
# 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.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: 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:
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.
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.
Reproduce the Python truth-test failure
# 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 static or remove the negative case.
Check a batched numerical selection
# 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 and slopes .
Correct values under batching do not imply a conditional branch remains lazy after every transformation.
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 when is positive and 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.
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 NotImplementedError1. 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
# 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 for and otherwise. Derive outputs at ,, and derivatives away from .
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.
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 NotImplementedErrorShow a hint
At the false branch is selected.
Reveal reference solution and reasoning
# 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.
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 NotImplementedErrorShow a hint
Decide what each output component means before padding.
Reveal reference solution and reasoning
# 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].
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].
Carry forward
- The repair changes where the decision is represented. It does not make static or remove the negative case.
- Correct values under batching do not imply a conditional branch remains lazy after every transformation.
Keep your evidence
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.
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.