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

Phase 01 / Arrays & pure functions

Pure functions and explicit inputs

Revision v0.18.1 ·

Lesson · about 45 minutes · CPU practice

Design an explicit parameter/data interface and return new state without mutating old containers.

Phase study guide: preparation, milestones and project evidence

Before you start

Before this: Shapes, broadcasting, and dtypes
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/01-arrays/03-pure-functions-and-explicit-inputs/code/main.py

PowerShell command · repository folder
.\.venv\Scripts\python.exe phases/01-arrays/03-pure-functions-and-explicit-inputs/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: [11. 33. 55.]

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

  • Identify hidden inputs and side effects in a numerical function.
  • Pass model parameters explicitly and return new state without mutating input containers.
  • Test replay and independence between two parameter configurations.
  • Explain why host orchestration and transformed numerical computation need different boundaries.

The problem

Have you ever rerun a notebook cell and got a different result because another cell changed a variable? Let’s make that dependency visible. We’ll pass a model’s weights into its prediction function, return new values explicitly, and check that the same inputs reproduce the same calculation.

The idea

A pure function makes its changing inputs visible and returns its result without secretly changing shared state. That gives transformations such as differentiation and compilation a clear computation to work with. When a prediction changes, we should be able to identify the input that changed.

Make a repeated call explainable

Imagine a predictor whose source accepts features and weights but reads its bias from a Python global. You compile it, edit the global, and call the compiled function again. The source now displays a different bias, but the traced computation may still contain the earlier value. The real dependency is hidden from the function signature.

Make the bias an explicit input so each call states which value it uses. The recorded prediction series make this dependence visible: with weight 22, inputs 0,1,20,1,2, and biases 11 and 33, the outputs are [1,3,5][1,3,5] and [3,5,7][3,5,7]. Increasing only the bias by 22 raises every prediction by 22, while preserving the slope.

Purity does not mean an application has no state. It means the numerical function receives the state it needs and returns values; orchestration and reporting can remain outside that boundary.

f(X,w,b)=Xw+b1,f(X,w,b+1)−f(X,w,b)=1f(X,w,b)=Xw+b\mathbf{1},\qquad f(X,w,b+1)-f(X,w,b)=\mathbf{1}

Hidden state makes the signature incomplete

A function that takes xx but reads a global weight has two effective inputs while advertising only one. Re-running it after changing the global can change its result with no visible argument change. Tests may depend on the order in which prior code ran.

Passing the weight explicitly makes the dependency visible. It also allows two model configurations to coexist without rewriting global variables. That matters for evaluation, comparisons, checkpoint recovery, and eventually multiple workers.

Array immutability does not make a dictionary immutable

An array stored in a Python dictionary is immutable as an array value, but the dictionary binding is mutable. After params["weight"] = new_weight, any alias to that same dictionary sees the new entry. The recorded example therefore reports aliased container weight 9.09.0, even though no JAX array was edited in place.

Constructing {**params, "weight": new_weight} instead returns a new dictionary and leaves the old mapping available for comparison. This is a shallow copy, which is enough for this example because the leaves are arrays. If you change the example, keep both mappings and predict their weight entries before printing; that separates container mutation from array-value semantics.

Treat a step as an input/output contract

A training step will eventually consume parameters, optimizer state, and a batch, then return updated state and metrics. The current predictor is the simpler first piece: parameters and data in, predictions out. The caller owns the history and can save both original and updated values.

This structure makes replay a meaningful test. With the same inputs, predictions should agree; changing the weight should affect predictions in the expected way. Do not make a test depend on a global that may already have been edited elsewhere in a notebook.

predict(parameters, observations) → predictions
future step(state, batch) → new_state, metrics

Choose a clear transformation boundary

A print, file write, or list append is a Python side effect. Inside a transformed function, such effects can happen during tracing rather than every device execution. We will investigate that mechanism in the tracing lesson. For now, separate producing metrics from reporting them.

Return the values you need to inspect, then let the caller print or save them. This design also makes unit-sized numerical checks simpler: you can compare actual outputs with known arrays without parsing console messages or relying on side-effect timing.

A deterministic check has limits

Calling a function twice with fixed inputs checks a useful property, but it does not prove the absence of every hidden dependency. A hidden global might happen not to change. Inspect the implementation and deliberately exercise multiple configurations. Randomness will need an explicit input as well; that is why the next phase introduces keys rather than treating random draws as invisible global state.

Keep the evidence proportional to the claim: these tests establish the behavior of this predictor and update pattern, not the replay of an entire distributed training job.

Read the figure

The horizontal axis is the input and the vertical axis is the prediction. The solid line uses bias 11; the dashed line uses bias 33. Both use the same weight 22.

At input 00, the predictions are 11 and 33. At input 22, they are 55 and 77. The gap stays 22 everywhere, and the parallel lines rise by 22 for each unit increase in the input.

Connect it to the computation

In y=wx+by=wx+b, changing the explicit bias changes the vertical offset, while the unchanged weight preserves the slope. You can read the bias directly where the line meets the vertical axis because the product wxwx is zero there.

This makes the function’s inputs inspectable: the change in the output follows the change in the passed parameter. As a check, setting the bias to 00 would move the solid line down by 11 and make it pass through the origin. It would not flatten the line.

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 Import JAX array operations

Import jax.numpy for the prediction function and its inputs.

main.py · append build step 1
import jax.numpy as jnp

The import supplies array arithmetic; model parameters and observations will be passed explicitly.

2 Define a prediction from explicit parameters

Write the affine predictor and store its weight and bias in a parameter dictionary.

main.py · append build step 2
def predict(params, x):
    return params["weight"] * x + params["bias"]
params = {"weight": jnp.array(2.), "bias": jnp.array(1.)}

The function has no hidden mutable state: the same parameters and input produce the same output.

Explain the APIs in this step
  • jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.

3 Evaluate the predictor on three inputs

Use inputs [0, 1, 2] and compare predictions against the hand-calculated values.

main.py · append build step 3
x = jnp.array([0., 1., 2.])
assert jnp.allclose(predict(params, x), jnp.array([1., 3., 5.]))

With weight 2 and bias 1, the predictions are [1, 3, 5]. This check verifies both parameter lookup and broadcasting.

Explain the APIs in this step
  • 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
import jax.numpy as jnp

def predict(params, x):
    return params["weight"] * x + params["bias"]
params = {"weight": jnp.array(2.), "bias": jnp.array(1.)}

x = jnp.array([0., 1., 2.])
assert jnp.allclose(predict(params, x), jnp.array([1., 3., 5.]))

Run the example

python3 phases/01-arrays/03-pure-functions-and-explicit-inputs/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
# Pure functions and explicit inputs
import jax.numpy as jnp
def predict(params, x):
    return params["weight"] * x + params["bias"]
params = {"weight": jnp.array(2.), "bias": jnp.array(1.)}
x = jnp.array([0., 1., 2.])
print(predict(params, x))
assert jnp.allclose(predict(params, x), jnp.array([1., 3., 5.]))

Expected result: [11. 33. 55.]

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

[1. 3. 5.]
aliased container weight: 9.0
evaluation losses: 0.0 6.0
PASS: arrays-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

Expose a mutable container alias

Expose a mutable container alias · Python experiment
# Experiment — Expose a mutable container alias: The mutation concerns Python container bindings.
container = {"weight": jnp.array(2.), "bias": jnp.array(1.)}
alias = container
alias["weight"] = jnp.array(9.)
assert float(container["weight"]) == 9.
assert float(params["weight"]) == 2.
print("aliased container weight:", float(container["weight"]))

Expected: The aliased container changes to weight 99; the separate original lesson parameters remain 22.

The mutation concerns Python container bindings. It does not contradict JAX array immutability.

Replay two independent model configurations

Replay two independent model configurations · Python experiment
# Experiment — Replay two independent model configurations
first_params = {"weight": jnp.array(2.), "bias": jnp.array(1.)}
second_params = {"weight": jnp.array(-1.), "bias": jnp.array(4.)}
first_output = predict(first_params, x)
second_output = predict(second_params, x)
assert jnp.allclose(first_output, jnp.array([1., 3., 5.]))
assert jnp.allclose(second_output, jnp.array([4., 3., 2.]))
assert jnp.allclose(predict(first_params, x), first_output)
assert jnp.allclose(predict(second_params, x), second_output)

Expected: The two configurations produce [1,3,5][1, 3, 5] and [4,3,2][4, 3, 2], and both can be replayed.

Independent configurations reveal the benefit of explicit inputs more clearly than one call on one global parameter set.

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.

Create new parameters with weight 33 while retaining the original bias. Show that the original parameters still produce the original predictions.

Show a writing guide and starter scaffold

How to write this exercise code

Learner-only inputs, outputs, checks and hints

Inputs

  • A parameter mapping with weight and bias.
  • A requested new weight and the prediction inputs.

Outputs

  • A new parameter mapping and predictions under both versions.

Invariants to check

  • The original mapping remains unchanged.
  • The retained field keeps its original value.
  • Original predictions can be replayed.

Hints

  • Return a new mapping instead of assigning into the input.
  • Pass the changed mapping explicitly to prediction.
Your attempt · complete the TODOs
import jax.numpy as jnp

def update_weight(params, new_weight):
    # TODO: return a new mapping with only the requested field changed
    raise NotImplementedError
Reveal the reference solution
Reference solution
# Exercise solution: Create new parameters with weight 3 while retaining the original bias.
updated = {**params, "weight": jnp.array(3.)}
assert jnp.allclose(predict(updated, x), jnp.array([1.,4.,7.]))
assert float(params["weight"]) == 2.0

Update the bias without changing either parameter input

Practice

Implement with_bias(params, new_bias), returning a new dictionary. Verify outputs for new bias −2-2 and replay the original prediction.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • The original parameters, a new bias value, and the lesson prediction function.

Outputs

  • A new mapping and predictions for both parameter versions.

Invariants to check

  • The returned mapping is a distinct container.
  • Changing bias does not alter the original prediction.

Hints

  • Create a copy with one updated field.
  • Check identity and numerical replay separately.
Your attempt · complete the TODOs
import jax.numpy as jnp

def with_bias(params, new_bias, predict, inputs):
    # TODO: return a new mapping and compare both prediction paths
    raise NotImplementedError
Show a hint

A new dictionary is required; changing a binding in the original dictionary breaks the promised contract.

Reveal reference solution and reasoning
Update the bias without changing either parameter input · Python solution
# Update the bias without changing either parameter input (Practice)
def with_bias(parameters, new_bias):
    return {**parameters, "bias": jnp.asarray(new_bias)}
changed_bias = with_bias(params, -2.)
assert changed_bias is not params
assert jnp.allclose(predict(changed_bias, x), jnp.array([-2., 0., 2.]))
assert jnp.allclose(predict(params, x), jnp.array([1., 3., 5.]))

The caller can evaluate both the old and new model without restoring a global value or depending on call order.

Return predictions and metrics together

Challenge

Write evaluate(params, inputs, targets) that returns predictions and a scalar MSE. Test two model configurations on targets [1,3,5][1, 3, 5]. Keep printing outside the function.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • Two parameter configurations, inputs, and targets.

Outputs

  • Predictions and scalar loss for both configurations.

Invariants to check

  • Evaluation returns numerical data without printing.
  • The loss reduces example errors to one scalar.
  • Parameter inputs are not mutated.

Hints

  • Keep reporting outside the function.
  • Use the supplied prediction function.
Your attempt · complete the TODOs
import jax.numpy as jnp

def evaluate(params, inputs, targets, predict):
    # TODO: return predictions and scalar mean squared error
    raise NotImplementedError
Show a hint

Compute data inside the numerical core and report it outside. A tuple return does not itself imply mutation.

Reveal reference solution and reasoning
Return predictions and metrics together · Python solution
# Return predictions and metrics together (Challenge)
def evaluate(parameters, inputs, targets):
    predictions = predict(parameters, inputs)
    return predictions, jnp.mean((predictions - targets) ** 2)
labels = jnp.array([1., 3., 5.])
outputs, error = evaluate(first_params, x, labels)
other_outputs, other_error = evaluate(second_params, x, labels)
# Check tensor shape invariant: `error.shape == ()`
assert error.shape == ()
assert jnp.allclose(error, 0.)
assert jnp.allclose(other_error, 6.)
assert jnp.allclose(outputs, first_output)
print("evaluation losses:", float(error), float(other_error))

The second model has residuals [3,0,−3][3, 0, -3], giving mean squared error 66. Known output arithmetic makes the check independent of the implementation.

Check your understanding

What makes predict easier to transform and test?

Choose one answer

Diagnose the result

If a replay differs, inspect hidden globals, mutable aliases, and random state before assuming nondeterministic hardware. If an update affects an old model, check whether the caller reused the same dictionary. If logs disappear under a transform, inspect whether they are Python side effects. Preserve numerical results as return values so you can investigate without relying on side-effect behavior.

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

Carry forward

  • Explicit inputs make model dependencies visible and configurations independent.
  • Immutable arrays can still be stored in mutable Python containers.
  • Return new state deliberately and let the caller own it.
  • Keep numerical computation separate from host logging, I/O, and orchestration.

Keep your evidence

Download evidence template

Keep both parameter configurations, their known predictions, a container-alias experiment, a non-mutating update, and an evaluation loss checked by hand. Explain which state the caller owns.

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