Phase 01 / Arrays & pure functions
Immutable updates and indexing
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 45 minutes · CPU practice
Implement functional indexed updates and distinguish accumulated contributions from shape-preserving masks.
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Pure functions and explicit inputs
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/01-arrays/04-immutable-updates-and-indexing/code/main.py.\.venv\Scripts\python.exe phases/01-arrays/04-immutable-updates-and-indexing/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 arrays-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: Original: ; Set: ; Add: .
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
- Predict the values returned by functional indexed set and add.
- Distinguish array-value semantics from Python name rebinding and compiler storage choices.
- Accumulate repeated-index contributions with an explicit integer reference.
- Choose a fixed-shape mask when output shape must remain stable.
The problem
You want to replace a few array entries, but JAX rejects the NumPy-style assignment. The key idea is small: describe the new array value, then keep the result. We’ll try replacement and addition, check that the original value is still available, and see what happens when an index appears more than once.
The idea
An indexed update in JAX returns an array value. This makes the relationship between old and new state explicit: the caller chooses which result to keep. The programming model describes values; compiler decisions about physical memory reuse are a separate issue.
Separate a new value from a new physical buffer
Start from the displayed original array . The set operation replaces index with , producing . The add operation contributes at indices and , producing . Both outputs branch from the same original, so the add result still has at index ; it did not inherit the set result.
Draw two arrows from the original, labeled set and add. If you want both effects in sequence, pass the first returned array into the second operation; the final values would then be . These are value semantics. The drawing does not establish whether the compiler allocated a distinct physical buffer.
A Python name and an array value are different
After y = x.at[1].set(20), the name x still refers to and y refers to . If instead you write x = x.at[1].set(20), Python rebinds the name x; it does not alter an earlier value held through original = x.
The execution receipt prints the original, set result, and add result side by side, and the heatmap uses those as three rows. Keeping a second name for the original makes the distinction observable. Before running a changed index, predict which positions should differ and check the untouched positions too.
Set replaces; add accumulates
Replacing an entry means its old value no longer contributes at that position in the result. Adding a contribution means the old value remains and the contribution is combined with it. Use set for a known replacement and add for a scatter-like accumulation.
Repeated indices need particular care. With add, contributions to the same index are accumulated; their floating-point order may not be guaranteed. With conflicting set values for the same index, do not assume a portable last-write-wins order. Choose unique indices when you need deterministic replacement semantics and test duplicate accumulation with exact small integers before studying floating-point ordering.
Choose a mask when you want to keep the shape
Selecting [ > threshold] extracts a variable number of elements: its output length depends on values. A masked replacement, jnp.where(x > threshold, x, 0), keeps the original shape. They are different calculations even if both are described casually as filtering.
A fixed-shape representation is useful for staged computation. Later lessons will explain why value-dependent output lengths can fail under jit. Decide whether downstream code expects compacted selected data or an array with masked entries before choosing the operation.
Make the index domain part of the contract
Our examples use explicit in-bounds integer indices and ordinary slices. Indexing behavior at out-of-bounds positions is not a substitute for validating bad input. Negative indexing, duplicate indices, masks, and scatter modes all need deliberate interpretation in a real data pipeline.
A small update test should verify unchanged positions as well as changed positions. Testing only the new value at one index could miss an unintended broadcast across a slice or a mistaken axis in a matrix.
Carry functional updates into training state
A model update is a larger version of the same idea: parameters and gradients produce new parameters. The caller retains or checkpoints state. Functional indexed operations let you describe a selective change without mutating an old array value.
This lesson prepares you to reason about optimizer and simulation state. It is separate from memory efficiency or a training algorithm; those require broader computations and measurements.
An update returns a new array
Predict before looking: Which cells change after set, and which after add?
Read the figure
Columns are array indices. The top row is the original array, and each lower row is a separate result created from that original. The cell colors encode stored values; the dark cell containing makes the replacement easy to locate.
The middle row replaces only index : becomes . The bottom row instead adds at indices and , giving .
Connect it to the computation
The bottom row still contains at index . This is the visual clue that the two updates branch from the original; the second operation did not continue from the middle row. In both cases, the top row remains unchanged.
An immutable update returns a new value. To make changes accumulate, pass the returned array into the next update. If these operations were chained, the final array would be , which is deliberately not the bottom row shown here.
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 Create the original four-element array
Import jax.numpy and define the values that the indexed updates will use.
import jax.numpy as jnp
x = jnp.array([1., 2., 3., 4.])Keep this original value available so the later checks can show that JAX updates return new arrays.
Explain the APIs in this step
jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.
2 Set one index and add to two others
Use .at[1].set to replace the second element, then .at[[0, 2]].add to add five at two indices.
y = x.at[1].set(20.)
z = x.at[jnp.array([0, 2])].add(5.)Each indexed operation returns a new array. The set and add operations leave all unselected positions unchanged.
Explain the APIs in this step
jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.
3 Check both updated values and the unchanged input
Compare the original, replacement result, and addition result with their expected vectors.
assert jnp.allclose(x, jnp.array([1.,2.,3.,4.]))
assert jnp.allclose(y, jnp.array([1.,20.,3.,4.]))
assert jnp.allclose(z, jnp.array([6.,2.,8.,4.]))Checking x itself makes the immutability behavior observable; the other checks verify the selected indices and values.
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.jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.
View the cumulative build in main.py
These blocks append in order to your separate practice file.
import jax.numpy as jnp
x = jnp.array([1., 2., 3., 4.])
y = x.at[1].set(20.)
z = x.at[jnp.array([0, 2])].add(5.)
assert jnp.allclose(x, jnp.array([1.,2.,3.,4.]))
assert jnp.allclose(y, jnp.array([1.,20.,3.,4.]))
assert jnp.allclose(z, jnp.array([6.,2.,8.,4.]))Run the example
python3 phases/01-arrays/04-immutable-updates-and-indexing/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
# Immutable updates and indexing: An indexed update in JAX returns an array value.
import jax.numpy as jnp
x = jnp.array([1., 2., 3., 4.])
y = x.at[1].set(20.)
z = x.at[jnp.array([0, 2])].add(5.)
print("Original:", x)
print("Set:", y)
print("Add:", z)
assert jnp.allclose(x, jnp.array([1.,2.,3.,4.]))
assert jnp.allclose(y, jnp.array([1.,20.,3.,4.]))
assert jnp.allclose(z, jnp.array([6.,2.,8.,4.]))Expected result: Original: ; Set: ; Add: .
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.
Original: [1. 2. 3. 4.]
Set: [ 1. 20. 3. 4.]
Add: [6. 2. 8. 4.]
PASS: arrays-04
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
See name rebinding without old-value mutation
# Experiment — See name rebinding without old-value mutation
original = x
rebound = x
rebound = rebound.at[1].set(20.)
assert jnp.allclose(original, jnp.array([1., 2., 3., 4.]))
assert jnp.allclose(rebound, jnp.array([1., 20., 3., 4.]))
ignored = x.at[0].set(99.)
assert jnp.allclose(x, original)
assert float(ignored[0]) == 99.Expected: The original remains ; rebound and ignored hold separate returned values.
Assigning a result changes the binding, while ignoring a result leaves the caller using the old value.
Accumulate repeated integer contributions
# Experiment — Accumulate repeated integer contributions: The integer loop reference makes accumulation explicit.
import numpy as np
indices = jnp.array([1, 1, 3])
contributions = jnp.array([2, 3, 7], dtype=jnp.int32)
base_counts = jnp.zeros(4, dtype=jnp.int32)
counts = base_counts.at[indices].add(contributions)
reference_counts = np.zeros(4, dtype=np.int32)
for index, contribution in zip([1, 1, 3], [2, 3, 7]):
# Accumulate the next contribution into `reference_counts[index]`.
reference_counts[index] += contribution
assert jnp.array_equal(counts, reference_counts)
assert jnp.array_equal(counts, jnp.array([0, 5, 0, 7]))
assert jnp.array_equal(base_counts, jnp.zeros(4, dtype=jnp.int32))Expected: The counts are ; repeated index receives both contributions.
The integer loop reference makes accumulation explicit. It avoids asserting a floating-point reduction order or conflicting-set behavior.
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.
Replace the last two elements with zero in a new array. Keep unchanged.
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- A one-dimensional four-value array
x. - A request to replace its final two positions in a new value.
Outputs
- A changed array and the unchanged original input.
Invariants to check
- The source array remains unchanged.
- Output shape matches input shape.
- Only requested positions change.
Hints
- Use a functional indexed update and keep its returned array.
- Compare the input after the update.
import jax.numpy as jnp
def replace_suffix(x):
# TODO: make the requested functional indexed update
raise NotImplementedErrorReveal the reference solution
# Exercise solution: Replace the last two elements with zero in a new array.
masked = x.at[2:].set(0.)
assert jnp.allclose(masked, jnp.array([1.,2.,0.,0.]))
assert jnp.allclose(x, jnp.array([1.,2.,3.,4.]))Replace a region of a matrix
Practice
Create a matrix containing through . Set its final column to in a returned value. Verify the whole result and original matrix.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- A three-by-three matrix of consecutive values.
Outputs
- A new matrix with its final column replaced.
Invariants to check
- Nonselected entries match the input.
- The original matrix is unchanged.
- The returned shape remains
(3, 3).
Hints
- Select the last column in every row.
- Check the entire result and original.
import jax.numpy as jnp
def replace_final_column(matrix):
# TODO: update the selected region in a returned array
raise NotImplementedErrorShow a hint
The slice [:, ] selects every row and the last column. A scalar replacement broadcasts across that slice.
Reveal reference solution and reasoning
# Replace a region of a matrix (Practice)
matrix = jnp.arange(9, dtype=jnp.float32).reshape(3, 3)
updated_matrix = matrix.at[:, -1].set(-1.)
assert jnp.allclose(updated_matrix, jnp.array([[0., 1., -1.], [3., 4., -1.], [6., 7., -1.]]))
assert jnp.allclose(matrix, jnp.arange(9).reshape(3, 3))Checking the entire matrix verifies both changed and unchanged positions; preserving the original checks the update contract.
Keep shape while masking values
Challenge
Keep only values greater than from , replacing other positions with zero. Compare with compact selection and explain the shape difference.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- A one-dimensional input
xand threshold two.
Outputs
- A fixed-shape masked value and a compact selected value.
Invariants to check
- The masked result keeps input shape.
- The compact result contains only selected entries.
Hints
- Use elementwise selection for fixed shape.
- Inspect both output shapes.
import jax.numpy as jnp
def compare_mask_and_selection(x, threshold=2.):
# TODO: construct both fixed-shape mask and compact selection
raise NotImplementedErrorShow a hint
Use where for the fixed-shape result. Boolean indexing produces selected values, not a shape-preserving mask.
Reveal reference solution and reasoning
# Keep shape while masking values (Challenge)
fixed_shape = jnp.where(x > 2., x, 0.)
selected = x[x > 2.]
# Check tensor shape invariant: `fixed_shape.shape == (4,)`
assert fixed_shape.shape == (4,)
# Check tensor shape invariant: `selected.shape == (2,)`
assert selected.shape == (2,)
assert jnp.allclose(fixed_shape, jnp.array([0., 0., 3., 4.]))
assert jnp.allclose(selected, jnp.array([3., 4.]))Both are useful representations, but they are not interchangeable. The expected downstream shape determines which is appropriate.
Diagnose the result
If nothing changes, check whether the returned update was discarded. If old values seem changed, distinguish name rebinding from mutation and inspect mutable containers around the array. If duplicate replacements are surprising, do not assume last-write-wins order; use an explicit unique-index policy. If a mask later fails under jit, inspect whether its output length depends on runtime values.
Carry forward
- Indexed updates return values; retaining them is the caller’s responsibility.
- Name rebinding and mutation are different operations.
- Repeated-index add accumulates contributions, while conflicting set needs a deliberate policy.
- A shape-preserving mask and compact selection express different computations.
Keep your evidence
Keep original and updated arrays, a repeated-index integer reference, the whole-matrix replacement check, and compact-versus-fixed-shape outputs. Explain replacement, accumulation, and name rebinding.
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 01 Integration Project
Bring this phase together: Audit masked batch moments and padding-sensitive denominators
Checkpoint to prove: Predict output shapes and explain why a pure function is easier to transform.
Work in projects/arrays-audit/starter/model.py. Complete stages 1 and 2 for independent calculations and changed-condition diagnosis, then retain the stage 3 evidence with --evidence-dir runs/arrays-audit. Stage 4 integrates the checks. Learner commands explicitly select the starter; --implementation solution is instructor reference execution. This bounded practice does not certify the entire phase or target hardware.