Domain Specialization · Local CPULaptop CPULesson 2 of 4 in Phase 10

Phase 10 / Scientific computing

Vectorize trajectories and scan time

Revision v0.18.1 ·

Lesson · about 100 minutes · CPU practice

Construct and verify a fourth-order fixed-step transition. Distinguish batch-major from time-major trajectory layouts.

Phase study guide: preparation, milestones and project evidence

Before you start

Before this: A functional physical simulation
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/10-science/02-vectorize-trajectories-and-scan-time/code/main.py

PowerShell command · repository folder
.\.venv\Scripts\python.exe phases/10-science/02-vectorize-trajectories-and-scan-time/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: Shape (3, 41); endpoints approximately [0.12329849, 0.24659697, 0.49319394]. Both compositions agree.

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

  • Construct and verify a fourth-order fixed-step transition.
  • Distinguish batch-major from time-major trajectory layouts.
  • Compare two valid scan/vectorization compositions numerically.
  • Separate independent ensembles from interacting states.

The problem

You need to simulate a collection of experimental starts, not just one. Which dimension represents independent experiments, and which represents sequential time? We will build both compositions explicitly and verify that their axes and physical predictions agree.

The idea

A simulation ensemble repeats one rule across independent systems and across time. Vectorization handles the independent systems; recurrence handles each system's evolving state. Name those axes before composing transforms.

There are two different axes of repetition

Think of the output as a table: each row is one independent experiment and each column is a saved time. In this fixture the rows start at 0.5,1,20.5,1,2, and the columns run from time zero through two seconds. A state update connects neighboring columns in one row; no update uses another row's value.

The plot follows the three rows of this batch-major table. At two seconds the endpoints are about 0.1233,0.2466,0.49320.1233,0.2466,0.4932, so the top-starting trajectory remains four times the lowest. If the physical systems exchanged heat, this independence assumption would fail and a coupled state update would be needed rather than simply adding more vmap lanes.

Each row is one independent system; the horizontal arrows link that system's successive states over time. There are no arrows between rows, matching the uncoupled equations in the code. Vectorization represents the row axis and scan the within-row recurrence. If the physical model introduced heat exchange between systems, cross-row dependencies would be required; the current diagram would no longer describe it.

Open full-size diagram

Improve one step before multiplying trajectories

Forward Euler samples the slope only at the start of the interval. Classical RK4 samples a start slope, two midpoint slopes and an endpoint slope, then combines them with weights 1,2,2,11,2,2,1. The intermediate states are trial values, not four extra saved observations. For our linear equation the full step is multiplication by a fourth-degree approximation to e−khe^{-kh}. This makes an independent algebraic oracle possible.

R(z)=1+z+z22+z36+z424,un+1=R(−kh)unR(z)=1+z+\frac{z^2}{2}+\frac{z^3}{6}+\frac{z^4}{24},\qquad u_{n+1}=R(-kh)u_n

Read shapes as physical statements

Three initial states and forty updates produce shape (3,41)(3,41): row bb is one trajectory, and column nn stores that trajectory at time nhnh. Column zero stores the initial state at t=0t=0; the next forty columns store the forty updates, giving 41 saved times in total. Since the dimensions differ, transposing by mistake is visible: it would plot 41 systems with three time samples rather than three systems with 41 samples.

A mean over rows would summarize the ensemble at each time; a mean over columns would average each trajectory over time. Neither operation is a shape-only convenience: each asks a different physical question.

One transformation handles independence; another handles dependency

vmap transforms a scalar simulation into an ensemble operation. scan still enforces the sequential state dependence inside each trajectory. Reversing the composition is possible here: the carry can hold all three independent states, giving a time-major result of shape (41,3)(41,3). Its transpose matches the first construction. If one trajectory exchanges heat with another, the batch members no longer obey independent scalar equations; write a coupled vector state instead.

Use physical structure as a second check

The equation is linear in its initial value: doubling u0u_0 doubles every later state. Thus the trajectory from 2 should be four times the trajectory from 0.5 at each of the 41 saved times, including the endpoint 0.49320.4932 versus 0.12330.1233. This relationship independently checks that batching did not mix or normalize the rows.

If the rate varies by experiment, that same proportionality still applies when each compared pair shares a rate, but their endpoints no longer have one common decay fraction. If the equation becomes nonlinear in state, do not assume proportional trajectories; check against the model's actual structure instead.

Choose saved outputs deliberately

Saving every state costs storage proportional to batch size times number of saved times. Some objectives need only the final state. In that case return no saved observation from scan and keep its final carry. This reduces the explicit output size; it does not by itself establish the memory cost of reverse-mode differentiation, which may retain or recompute intermediates.

Read the figure

The horizontal axis is time from 0 to 2 seconds; the vertical axis is excess temperature. Each curve is one row of the executed 3×413\times41 batch-major output, including its time-zero value: starts 0.5, 1 and 2. At two seconds the curves end near 0.1233, 0.2466 and 0.4932. The highest endpoint is four times the lowest because the equation is linear in the initial state and shares one rate across the batch.

Connect it to the computation

The analytic exponential and the proportional-endpoint check both pass for these three independent starts. vmap evaluates the same rule across rows; scan carries each row's state through columns. The figure has no speed or memory axis, so vectorization here establishes a correct ensemble calculation, not a performance gain. If one trajectory's state affected another, the no-cross-row assumption would need to change before batching.

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 Use a higher-order scalar transition

Append this block to main.py in your CPU course environment; for the first block create the file. Run blocks in order.

main.py · append build step 1
# Step 1 — Use a higher-order scalar transition: Runge–Kutta uses four slopes inside one step.
import jax
# Enable 64-bit arithmetic before importing jax.numpy or creating arrays.
jax.config.update("jax_enable_x64", True)
import jax.numpy as jnp
import numpy as np

def rk4_step(rate, value, dt):
    a = -rate*value
    b = -rate*(value + dt*a/2)
    c = -rate*(value + dt*b/2)
    d = -rate*(value + dt*c)
    return value + dt*(a + 2*b + 2*c + d)/6

# Define `solve(rate, initial, steps, dt)` to carry state across steps with `jax.lax.scan`:
def solve(rate, initial, steps=40, dt=0.05):
    def advance(value, unused):
        next_value = rk4_step(rate, value, dt)
        return next_value, next_value
    _, tail = jax.lax.scan(advance, initial, None, length=steps)
    return jnp.concatenate((jnp.atleast_1d(initial), tail))

Runge–Kutta uses four slopes inside one step. It remains a pure transition, so the same scan interface can save its trajectory.

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

2 Batch initial conditions while sharing the model

Append this block to main.py in your CPU course environment; for the first block create the file. Run blocks in order.

main.py · append build step 2
# Step 2 — Batch initial conditions while sharing the model: The batch axis is independent initial conditions, not time.
initials = jnp.array([0.5, 1.0, 2.0])
rate, dt, steps = 0.7, 0.05, 40
# Vectorize across the batch dimension with `jax.vmap` (`simulate_batch`).
simulate_batch = jax.jit(jax.vmap(lambda initial: solve(rate, initial, steps, dt)))
trajectories = simulate_batch(initials)
times = np.arange(steps+1)*dt
# Transfer the device result to the host for an independent NumPy comparison.
oracle = np.asarray(initials)[:,None]*np.exp(-rate*times[None,:])
# Check tensor shape invariant: `trajectories.shape == (3, 41)`
assert trajectories.shape == (3, 41)
np.testing.assert_allclose(trajectories, oracle, rtol=3e-8, atol=1e-10)
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_allclose(np.asarray(trajectories)[2], 4*np.asarray(trajectories)[0], rtol=1e-12)
print("Shape:", trajectories.shape, "endpoints:", np.asarray(trajectories)[:,-1])

The batch axis is independent initial conditions, not time. The shared rate and grid are closed over here; vmap adds one leading axis to the scalar solve.

Explain the APIs in this step
  • jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.
  • 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.
  • jax.vmap(fn, in_axes=..., out_axes=...): Vectorizes a single-example function across mapped array axes without a Python loop.
  • np.testing.assert_allclose(actual, desired, rtol=..., atol=...): Checks a host-side numerical expectation and raises AssertionError when values differ beyond tolerance.

3 Change composition and verify axis meaning

Append this block to main.py in your CPU course environment; for the first block create the file. Run blocks in order.

main.py · append build step 3
# Step 3 — Change composition and verify axis meaning
# Define `scan_batch(rate, values, steps, dt)` to carry state across steps with `jax.lax.scan`:
def scan_batch(rate, values, steps=40, dt=0.05):
    def advance(state, unused):
        updated = rk4_step(rate, state, dt)
        return updated, updated
    _, tail = jax.lax.scan(advance, values, None, length=steps)
    return jnp.concatenate((values[None,:], tail), axis=0)
time_major = scan_batch(rate, initials)
# Check tensor shape invariant: `time_major.shape == (41, 3)`
assert time_major.shape == (41, 3)
np.testing.assert_allclose(time_major.T, trajectories, rtol=1e-12, atol=1e-12)
print("scan(vectors) transposed equals vmap(scan)")

Array arithmetic applies the independent scalar dynamics to all initial conditions. This equivalence would fail if the model coupled different batch members.

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).
  • np.testing.assert_allclose(actual, desired, rtol=..., atol=...): Checks a host-side numerical expectation and raises AssertionError when values differ beyond 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 — Use a higher-order scalar transition: Runge–Kutta uses four slopes inside one step.
import jax
# Enable 64-bit arithmetic before importing jax.numpy or creating arrays.
jax.config.update("jax_enable_x64", True)
import jax.numpy as jnp
import numpy as np

def rk4_step(rate, value, dt):
    a = -rate*value
    b = -rate*(value + dt*a/2)
    c = -rate*(value + dt*b/2)
    d = -rate*(value + dt*c)
    return value + dt*(a + 2*b + 2*c + d)/6

# Define `solve(rate, initial, steps, dt)` to carry state across steps with `jax.lax.scan`:
def solve(rate, initial, steps=40, dt=0.05):
    def advance(value, unused):
        next_value = rk4_step(rate, value, dt)
        return next_value, next_value
    _, tail = jax.lax.scan(advance, initial, None, length=steps)
    return jnp.concatenate((jnp.atleast_1d(initial), tail))

# Step 2 — Batch initial conditions while sharing the model: The batch axis is independent initial conditions, not time.
initials = jnp.array([0.5, 1.0, 2.0])
rate, dt, steps = 0.7, 0.05, 40
# Vectorize across the batch dimension with `jax.vmap` (`simulate_batch`).
simulate_batch = jax.jit(jax.vmap(lambda initial: solve(rate, initial, steps, dt)))
trajectories = simulate_batch(initials)
times = np.arange(steps+1)*dt
# Transfer the device result to the host for an independent NumPy comparison.
oracle = np.asarray(initials)[:,None]*np.exp(-rate*times[None,:])
# Check tensor shape invariant: `trajectories.shape == (3, 41)`
assert trajectories.shape == (3, 41)
np.testing.assert_allclose(trajectories, oracle, rtol=3e-8, atol=1e-10)
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_allclose(np.asarray(trajectories)[2], 4*np.asarray(trajectories)[0], rtol=1e-12)
print("Shape:", trajectories.shape, "endpoints:", np.asarray(trajectories)[:,-1])

# Step 3 — Change composition and verify axis meaning
# Define `scan_batch(rate, values, steps, dt)` to carry state across steps with `jax.lax.scan`:
def scan_batch(rate, values, steps=40, dt=0.05):
    def advance(state, unused):
        updated = rk4_step(rate, state, dt)
        return updated, updated
    _, tail = jax.lax.scan(advance, values, None, length=steps)
    return jnp.concatenate((values[None,:], tail), axis=0)
time_major = scan_batch(rate, initials)
# Check tensor shape invariant: `time_major.shape == (41, 3)`
assert time_major.shape == (41, 3)
np.testing.assert_allclose(time_major.T, trajectories, rtol=1e-12, atol=1e-12)
print("scan(vectors) transposed equals vmap(scan)")

Run the example

python3 phases/10-science/02-vectorize-trajectories-and-scan-time/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 — Use a higher-order scalar transition: Runge–Kutta uses four slopes inside one step.
import jax
# Enable 64-bit arithmetic before importing jax.numpy or creating arrays.
jax.config.update("jax_enable_x64", True)
import jax.numpy as jnp
import numpy as np

def rk4_step(rate, value, dt):
    a = -rate*value
    b = -rate*(value + dt*a/2)
    c = -rate*(value + dt*b/2)
    d = -rate*(value + dt*c)
    return value + dt*(a + 2*b + 2*c + d)/6

# Define `solve(rate, initial, steps, dt)` to carry state across steps with `jax.lax.scan`:
def solve(rate, initial, steps=40, dt=0.05):
    def advance(value, unused):
        next_value = rk4_step(rate, value, dt)
        return next_value, next_value
    _, tail = jax.lax.scan(advance, initial, None, length=steps)
    return jnp.concatenate((jnp.atleast_1d(initial), tail))

# Step 2 — Batch initial conditions while sharing the model: The batch axis is independent initial conditions, not time.
initials = jnp.array([0.5, 1.0, 2.0])
rate, dt, steps = 0.7, 0.05, 40
# Vectorize across the batch dimension with `jax.vmap` (`simulate_batch`).
simulate_batch = jax.jit(jax.vmap(lambda initial: solve(rate, initial, steps, dt)))
trajectories = simulate_batch(initials)
times = np.arange(steps+1)*dt
# Transfer the device result to the host for an independent NumPy comparison.
oracle = np.asarray(initials)[:,None]*np.exp(-rate*times[None,:])
# Check tensor shape invariant: `trajectories.shape == (3, 41)`
assert trajectories.shape == (3, 41)
np.testing.assert_allclose(trajectories, oracle, rtol=3e-8, atol=1e-10)
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_allclose(np.asarray(trajectories)[2], 4*np.asarray(trajectories)[0], rtol=1e-12)
print("Shape:", trajectories.shape, "endpoints:", np.asarray(trajectories)[:,-1])

# Step 3 — Change composition and verify axis meaning
# Define `scan_batch(rate, values, steps, dt)` to carry state across steps with `jax.lax.scan`:
def scan_batch(rate, values, steps=40, dt=0.05):
    def advance(state, unused):
        updated = rk4_step(rate, state, dt)
        return updated, updated
    _, tail = jax.lax.scan(advance, values, None, length=steps)
    return jnp.concatenate((values[None,:], tail), axis=0)
time_major = scan_batch(rate, initials)
# Check tensor shape invariant: `time_major.shape == (41, 3)`
assert time_major.shape == (41, 3)
np.testing.assert_allclose(time_major.T, trajectories, rtol=1e-12, atol=1e-12)
print("scan(vectors) transposed equals vmap(scan)")

Expected result: Shape (3, 41); endpoints approximately [0.12329849, 0.24659697, 0.49319394]. Both compositions agree.

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

Shape: (3, 41) endpoints: [0.12329848 0.24659697 0.49319394]
scan(vectors) transposed equals vmap(scan)
Shape: (3, 41) endpoints: [0.12329848 0.24659697 0.49319394]
scan(vectors) transposed equals vmap(scan)
RK4 polynomial maximum difference: 1.4432899320127035e-15
Paired-rate endpoints: [0.33516002 0.24659697 0.22160636]
Permutation preserves trajectory identity
Only final states returned: [0.12329848 0.24659697 0.49319394]
Grid axes: rate, initial condition, time (3, 3, 41)
PASS: science-02

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 RK4 with an independent polynomial

Compare RK4 with an independent polynomial · Python experiment
# Experiment — Compare RK4 with an independent polynomial
z = -rate*dt
multiplier = 1 + z + z*z/2 + z**3/6 + z**4/24
polynomial = np.asarray(initials)[:,None]*multiplier**np.arange(steps+1)[None,:]
np.testing.assert_allclose(trajectories, polynomial, rtol=1e-12, atol=1e-12)
print("RK4 polynomial maximum difference:", np.max(np.abs(np.asarray(trajectories)-polynomial)))

Expected: Differences are near float64 roundoff.

This checks the discrete algorithm independently of the continuous exponential. RK4 has much smaller error here but is not exact.

Let each trajectory have its own rate

Let each trajectory have its own rate · Python experiment
# Experiment — Let each trajectory have its own rate: Mapping both axes pairs corresponding entries.
rates = jnp.array([0.2, 0.7, 1.1])
# Vectorize across the batch dimension with `jax.vmap` (`paired`).
paired = jax.vmap(lambda k, u: solve(k,u), in_axes=(0,0))(rates,initials)
# Transfer the device result to the host for an independent NumPy comparison.
paired_reference = np.asarray(initials)[:,None]*np.exp(-np.asarray(rates)[:,None]*times)
np.testing.assert_allclose(paired,paired_reference,rtol=2e-7,atol=1e-10)
print("Paired-rate endpoints:", np.asarray(paired)[:,-1])

Expected: Three trajectories now have different relative decay rates.

Mapping both axes pairs corresponding entries. A grid of every rate with every initial value would require nested mapping and a different output contract.

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.

Add a fourth initial condition, verify the changed output shape and exponential values, then verify that reordering initial conditions reorders rows only.

Show a writing guide and starter scaffold

How to write this exercise code

Learner-only inputs, outputs, checks and hints

Inputs

  • Rate 0.7, a four-element initial-condition vector, and the lesson time grid with 41 points.
  • A permutation of the four initial conditions.

Outputs

  • Batched trajectory with shape (4, 41), checked against initial * exp(-rate*time).
  • Reordered trajectories whose rows follow the changed initial-condition order.

Invariants to check

  • Each initial condition scales the same scalar decay trajectory.
  • Reordering inputs changes rows only; time columns remain unchanged.
  • The batch/time axes have shape (4, 41).

Hints

  • Vectorize over initial values while preserving the time axis.
  • Compare all values with the analytic exponential and apply the same row permutation.
Your attempt · complete the TODOs
import numpy as np
import jax
import jax.numpy as jnp

def verify_batched_trajectories(solve, initial_values, rate, times, permutation):
    # TODO: evaluate four starts, check shape and exponential values, then row reordering.
    raise NotImplementedError("Check analytic trajectories and preserve batch/time axes")
Reveal the reference solution
Reference solution
# Exercise solution
changed_initials = jnp.array([0.5, 1.0, 2.0, 3.0])
# Vectorize across the batch dimension with `jax.vmap` (`changed`).
changed = jax.vmap(lambda u: solve(0.7,u))(changed_initials)
# Check tensor shape invariant: `changed.shape == (4,41)`
assert changed.shape == (4,41)
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_allclose(changed,np.asarray(changed_initials)[:,None]*np.exp(-0.7*times),rtol=3e-8)
order = jnp.array([3,0,2,1])
# Vectorize across the batch dimension with `jax.vmap` (`reordered`).
reordered = jax.vmap(lambda u: solve(0.7,u))(changed_initials[order])
np.testing.assert_allclose(reordered,changed[order],rtol=1e-12)
print("Permutation preserves trajectory identity")

Save only what the objective needs

Practice

Implement a final-state-only solve and compare it with the final column of the saved batch. Explain which allocation was removed.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • A vector of four initial conditions, fixed scalar rate, and saved time grid.

Outputs

  • Final-state-only values and the final column from the trajectory solve.
  • A short explanation naming the intermediate-trajectory allocation no longer retained.

Invariants to check

  • Both methods agree at the final time.
  • The final-only solve avoids retaining intermediate states.
  • Final-only evaluation carries the state without storing every time point.

Hints

  • Use the same integrator, step count, and initial values in both paths.
  • Compare arrays by shape and values, not a single selected element.
Your attempt · complete the TODOs
import numpy as np
import jax
import jax.numpy as jnp

def compare_final_only(initial_values, rate, dt, steps):
    # TODO: implement a scan that returns only its carry, then compare with saved states.
    raise NotImplementedError("Compare final-only integration with the saved trajectory")
Show a hint

scan may emit None while its carry still advances.

Reveal reference solution and reasoning
Save only what the objective needs · Python solution
# Save only what the objective needs (Practice): The explicit trajectory output is removed.
# Define `final_only(rate, initial, steps, dt)` to carry state across steps with `jax.lax.scan`:
def final_only(rate, initial, steps=40, dt=0.05):
    def advance(value, unused):
        return rk4_step(rate,value,dt), None
    return jax.lax.scan(advance,initial,None,length=steps)[0]
# Vectorize across the batch dimension with `jax.vmap` (`finals`).
finals = jax.vmap(lambda u: final_only(0.7,u))(initials)
np.testing.assert_allclose(finals,trajectories[:,-1],rtol=1e-12)
print("Only final states returned:", np.asarray(finals))

The explicit trajectory output is removed. Differentiation memory requires separate analysis and measurement.

Pairing versus Cartesian products

Challenge

Build the full grid of three rates and three initial values. Show that its diagonal agrees with the paired-rate experiment.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • Three rates and three initial values for the scalar decay model.

Outputs

  • Paired outputs and a full rate-by-initial-value grid.

Invariants to check

  • Paired evaluation returns one output per matching input pair.
  • Cartesian evaluation returns a (3, 3) grid; its diagonal matches paired results.

Hints

  • Use vmap over both arguments for pairing.
  • Nest vectorization over rates and initial values for the Cartesian grid.
Your attempt · complete the TODOs
import numpy as np
import jax
import jax.numpy as jnp

def compare_pairing_and_grid(solve, rates, initials):
    # TODO: construct paired and Cartesian evaluations.
    # Return both arrays and an explicit diagonal consistency check.
    raise NotImplementedError("Distinguish paired mapping from a Cartesian product")
Show a hint

Use nested vmap; identify the rate, initial-condition and time axes explicitly.

Reveal reference solution and reasoning
Pairing versus Cartesian products · Python solution
# Pairing versus Cartesian products (Challenge): Paired batches and Cartesian products are different experiments.
# Vectorize across the batch dimension with `jax.vmap` (`grid`).
grid = jax.vmap(lambda k: jax.vmap(lambda u: solve(k,u))(initials))(rates)
# Check tensor shape invariant: `grid.shape == (3,3,41)`
assert grid.shape == (3,3,41)
np.testing.assert_allclose(grid[jnp.arange(3),jnp.arange(3)],paired,rtol=1e-12)
print("Grid axes: rate, initial condition, time", grid.shape)

Paired batches and Cartesian products are different experiments. The diagonal correspondence verifies the axis interpretation.

Check your understanding

What does a shape of (3, 41) mean in the batch-major solver?

Choose one answer

Diagnose the result

If the reference comparison broadcasts unexpectedly, print both shapes before reducing anything. Compare a named row and a named time column. If changing one initial condition changes other rows, inspect reductions or coupling across the batch. A reduction can hide an axis error while still producing a plausible scalar.

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

Carry forward

  • Improve one step before multiplying trajectories
  • Read shapes as physical statements
  • One transformation handles independence; another handles dependency
  • Use physical structure as a second check
  • Choose saved outputs deliberately

Keep your evidence

Download evidence template

Polynomial/exponential references, batch/time shape diagram, permutation and final-only checks. Keep the environment, observed outputs and your explanation of the figure.

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