Onboarding · Local CPULaptop CPULesson 2 of 4 in Phase 00

Phase 00 / Setup & first steps

Meet your arrays and devices

Revision v0.18.1 ·

Lesson · about 45 minutes · CPU practice

Create an array, inspect its dtype and device, and explain the result.

Phase study guide: preparation, milestones and project evidence

Before you start

Before this: Set up your learning workspace
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/00-welcome/02-meet-your-arrays-and-devices/code/main.py

PowerShell command · repository folder
.\.venv\Scripts\python.exe phases/00-welcome/02-meet-your-arrays-and-devices/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: (2,3)(2, 3); Dtype: float32; Row sums: [ 33. 1212.]. Device names vary.

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

  • Read the table before using an API
  • Derive a reduction and its output shape
  • Distinguish dtype from mathematical value
  • Inspect placement without assuming an accelerator

The problem

Imagine a small table: two observations, with three measurements in each row. If we ask JAX to add the values, should it add across the rows or down the columns? Let’s work out both answers before running any code. You’ll learn to check an array’s shape, number format and device, so a plausible-looking result does not hide a mistake.

The idea

An array is a collection of values with a shape, a dtype and a device. Shape tells us how to index the values; dtype tells us how they are represented; device tells us where the computation lives. Start by predicting a small reduction before asking JAX to perform it.

Read one array two ways

Take the two rows [0,1,2][0,1,2] and [3,4,5][3,4,5] from the program below. Summing across each row gives [3,12][3,12]: one answer per observation. Summing down the rows gives [3,5,7][3,5,7]: one answer per feature. The values stay fixed; the question determines the axis.

The row sums use axis=1, because the feature axis is reduced. The feature sums use axis=0, because the observation axis is reduced. The axis you name is the one you consume, not the one you keep. Check this in the heatmap by pointing to the cells that contribute to one output.

Now predict a changed input. If every entry increases by 11, each three-feature row sum increases by 33, while each two-observation column sum increases by 22. The new outputs are [6,15][6,15] and [5,7,9][5,7,9]. Use the different increments to explain the reduction instead of memorizing axis numbers.

ri=∑j=02Xij,cj=∑i=01Xij,X=[012345]r_i=\sum_{j=0}^{2}X_{ij},\qquad c_j=\sum_{i=0}^{1}X_{ij},\qquad X=\begin{bmatrix}0&1&2\\3&4&5\end{bmatrix}

Read the table before using an API

Start with the six values 00 through 55. Reshape them into two rows: [0,1,2][0, 1, 2] and [3,4,5][3, 4, 5]. The first axis selects an observation; the second selects a measurement. Shape (2,3)(2, 3) describes that organization, not the numerical values. Reshape preserves element count and ordering here; it does not create new measurements.

A length-six array and a two-by-three array contain the same values but invite different operations. In your notebook, write an axis label beside each dimension. This becomes important when a later model expects one prediction per row.

flat [0,1,2,3,4,5] → rows [[0,1,2],[3,4,5]]
axis 0: observations (2)
axis 1: measurements (3)

Derive a reduction and its output shape

Summing along axis 11 consumes the feature axis and leaves one total per observation. From the displayed rows [0,1,2][0,1,2] and [3,4,5][3,4,5], calculate 0+1+2=30+1+2=3 and 3+4+5=123+4+5=12; the result [3,12][3,12] has shape (2,)(2,). Summing along axis 00 consumes the observation axis instead, leaving one total per feature: [3,5,7][3,5,7], shape (3,)(3,).

With keepdims=True, the column means retain a leading singleton dimension, shape (1,3)(1,3). That shape makes the intended reuse across both rows visible when centering. Before running your exercise, write the output shape next to the axis you plan to reduce; if you need one value per observation, the answer should have two entries.

(2,3) --sum(axis=1)--> (2,) : [3,12]
(2,3) --sum(axis=0)--> (3,) : [3,5,7]

Distinguish dtype from mathematical value

Dtype describes storage and arithmetic, not whether a value happens to be an integer. The value 33 can be represented as int32 or float32. This lesson asks for float32 explicitly so later differentiation uses an inexact input. Do not infer precision from the way Python prints a scalar.

Float32 cannot represent every real number, or even every large integer. An exact-looking printed value is not a guarantee of exact arithmetic. Keep dtype in an experiment record and compare with tolerances when arithmetic is approximate.

Inspect placement without assuming an accelerator

jax.devices() lists available devices; x.devices() describes the placement of this array. A CPU result is useful evidence of CPU execution. It is separate from that a TPU runtime is installed or that a model scales across devices.

Creating a NumPy copy brings values into host memory for inspection. Converting a scalar with float also requires a concrete value. Those are useful boundaries for tests and reports; repeated transfers inside a training loop can distort performance. Use device metadata to inspect placement and an explicit synchronization point for timing later.

Read the figure

The horizontal axis selects a feature column; the vertical axis selects an observation row. Each cell contains one array value. The color bar maps larger numbers to darker purple: the bottom-right cell is darkest because it contains 55.

Read across the top row to find (0,1,2)(0,1,2), then across the bottom row to find (3,4,5)(3,4,5). The picture therefore represents an array with shape (2,3)(2,3): two observations, each with three features.

Connect it to the computation

Now connect the picture to a reduction. Summing the feature columns within each row gives 0+1+2=30+1+2=3 and 3+4+5=123+4+5=12. That is why summing along axis 11 returns two values. Summing down rows instead would return (3,5,7)(3,5,7), one value per feature.

The row labels are positions, not times or class labels. The darker lower row tells us its stored values are larger; it does not imply that the observation is more important.

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: x has two observations and three features.
x = jnp.arange(6, dtype=jnp.float32).reshape(2, 3)

xx has two observations and three features. axis=0 removes the observation dimension, so the means describe features; the centered result retains both axes.

Explain the APIs in this step
  • jnp.arange(n, dtype=...): Creates a 1-D JAX array of evenly spaced values [0, 1, ..., n-1] on the target device.
  • array.reshape(new_shape): Reorganizes tensor axes without changing the total element count (array.size).

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("Shape:", x.shape)
print("Dtype:", x.dtype)
print("Devices:", x.devices())
print("Row sums:", x.sum(axis=1))
# Check tensor shape invariant: `x.shape == (2, 3)`
assert x.shape == (2, 3)
assert jnp.allclose(x.sum(axis=1), jnp.array([3., 12.]))

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

Explain the APIs in this step
  • array.sum(axis=...): Adds values along the selected axis; that axis is removed unless keepdims=True.
  • 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.

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

# Step 2 — Build the computation: x has two observations and three features.
x = jnp.arange(6, dtype=jnp.float32).reshape(2, 3)

# Step 3 — Run and check the result
print("Shape:", x.shape)
print("Dtype:", x.dtype)
print("Devices:", x.devices())
print("Row sums:", x.sum(axis=1))
# Check tensor shape invariant: `x.shape == (2, 3)`
assert x.shape == (2, 3)
assert jnp.allclose(x.sum(axis=1), jnp.array([3., 12.]))

Run the example

python3 phases/00-welcome/02-meet-your-arrays-and-devices/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: x has two observations and three features.
x = jnp.arange(6, dtype=jnp.float32).reshape(2, 3)
# Step 3 — Run and check the result
print("Shape:", x.shape)
print("Dtype:", x.dtype)
print("Devices:", x.devices())
print("Row sums:", x.sum(axis=1))
# Check tensor shape invariant: `x.shape == (2, 3)`
assert x.shape == (2, 3)
assert jnp.allclose(x.sum(axis=1), jnp.array([3., 12.]))

Expected result: Shape: (2,3)(2, 3); Dtype: float32; Row sums: [ 33. 1212.]. Device names vary.

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

Shape: (2, 3)
Dtype: float32
Devices: {CpuDevice(id=0)}
Row sums: [ 3. 12.]
Shape: (2, 3)
Dtype: float32
Devices: {CpuDevice(id=0)}
Row sums: [ 3. 12.]
Means: [[1.5 2.5 3.5]]
Centered: [[-1.5 -1.5 -1.5]
 [ 1.5  1.5  1.5]]
Host dtype: float32
Expected element-count mismatch
PASS: welcome-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

Center each measurement

Center each measurement · Python experiment
# Experiment — Center each measurement: The calculation reuses one mean per column.
# Reduce along axis=0 to compute `means`.
means=x.mean(axis=0,keepdims=True)
centered=x-means
print("Means:",means)
print("Centered:",centered)
# Check tensor shape invariant: `means.shape==(1,3)`
assert means.shape==(1,3)
assert jnp.allclose(centered,jnp.array([[-1.5,-1.5,-1.5],[1.5,1.5,1.5]]))

Expected: Means [[1.5,2.5,3.5]][[1.5,2.5,3.5]]; centered rows are −1.5-1.5 and +1.5+1.5.

The calculation reuses one mean per column. An explicit hand calculation verifies both the values and the meaning of the reduction.

Keep a host reference

Keep a host reference · Python experiment
# Experiment — Keep a host reference: The host reference is an inspection copy.
import numpy as np
# Transfer the device result to the host for an independent NumPy comparison.
host=np.asarray(x)
# Check tensor shape invariant: `host.shape==(2,3)`
assert host.shape==(2,3)
np.testing.assert_array_equal(host,np.arange(6).reshape(2,3))
print("Host dtype:",host.dtype)

Expected: A NumPy array with the same two-by-three values.

The host reference is an inspection copy. Its existence says nothing about accelerator throughput.

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.

Compute column sums instead. State the resulting shape before running the code.

Show a writing guide and starter scaffold

How to write this exercise code

Learner-only inputs, outputs, checks and hints

Inputs

  • A two-row, three-feature JAX array named x.
  • The lesson has checked its dtype and device.

Outputs

  • Column totals and an explicit output-shape check.

Invariants to check

  • Reduce the observation axis and preserve the feature axis.
  • Check shape separately from numeric values.

Hints

  • Read the dimensions before choosing a reduction axis.
  • The result retains the feature dimension.
Your attempt · complete the TODOs
import jax.numpy as jnp

def column_summary(x):
    # TODO: reduce observations and return feature-wise values and shape
    values = ...
    shape = ...
    return values, shape
Reveal the reference solution
Reference solution
# Exercise solution: Compute column sums instead.
# Reduce along axis=0 to compute `column_sums`.
column_sums = x.sum(axis=0)
# Check tensor shape invariant: `column_sums.shape == (3,)`
assert column_sums.shape == (3,)
assert jnp.allclose(column_sums, jnp.array([3., 5., 7.]))

Add a new observation

Practice

Append [6,7,8][6,7,8]. Predict row sums and column means, then check both.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • The original two-row table and the new observation [6, 7, 8].

Outputs

  • The extended table, row totals, and feature means.

Invariants to check

  • Appending adds an observation without changing feature count.
  • Row and feature reductions preserve opposite axes.

Hints

  • Concatenate along the observation axis.
  • Write down the table shape before reducing.
Your attempt · complete the TODOs
import jax.numpy as jnp

def extend_and_summarize(table, new_row):
    # TODO: append one observation and compute both summaries
    extended = ...
    row_totals = ...
    feature_means = ...
    return extended, row_totals, feature_means
Show a hint

Keep observation rows and measurement columns.

Reveal reference solution and reasoning
Add a new observation · Python solution
# Add a new observation (Practice)
table=jnp.arange(9,dtype=jnp.float32).reshape(3,3)
assert jnp.allclose(table.sum(axis=1),jnp.array([3.,12.,21.]))
assert jnp.allclose(table.mean(axis=0),jnp.array([3.,4.,5.]))

Changing the observation count changes axis 00, while the measurement count stays three.

Diagnose an impossible reshape

Challenge

Try reshaping six values to (2,4)(2,4). Explain the failure and repair the intended three-measurement table.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • A six-value array and target shape (2, 4).
  • The intended table has three measurements per row.

Outputs

  • A captured incompatible reshape and a repaired three-feature layout.

Invariants to check

  • Reshape preserves the number of elements.
  • The repaired table retains every value.

Hints

  • Count required elements before reshaping.
  • Catch the shape error without discarding data.
Your attempt · complete the TODOs
import jax.numpy as jnp

def diagnose_reshape(values):
    # TODO: attempt the requested shape and capture its incompatibility
    attempted = ...
    repaired = ...
    return attempted, repaired
Show a hint

Count required elements before changing the code.

Reveal reference solution and reasoning
Diagnose an impossible reshape · Python solution
# Diagnose an impossible reshape (Challenge): An incompatible reshape is an element-count error.
try:
    x.reshape(2,4)
except TypeError:
    print("Expected element-count mismatch")
else:
    raise AssertionError("Expected reshape to fail")
assert x.reshape(2,3).size==6

An incompatible reshape is an element-count error. Changing a dtype or moving devices cannot fix it. Choose a shape whose product matches six.

Check your understanding

For an array of shape (2,3)(2, 3), what shape results from sum(axis=0)?

Choose one answer

Diagnose the result

An incompatible reshape is an element-count error. Changing a dtype or moving devices cannot fix it. Choose a shape whose product matches six.

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

Carry forward

  • The calculation reuses one mean per column. An explicit hand calculation verifies both the values and the meaning of the reduction.
  • The host reference is an inspection copy. Its existence says nothing about accelerator throughput.

Keep your evidence

Download evidence template

Keep the labeled table, row/column calculations, centered-data check, array dtype/device report and the failed reshape with its element-count 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