Phase 00 / Setup & first steps
Meet your arrays and devices
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
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.
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/00-welcome/02-meet-your-arrays-and-devices/code/main.py.\.venv\Scripts\python.exe phases/00-welcome/02-meet-your-arrays-and-devices/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 welcome-02.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: Shape: ; Dtype: float32; Row sums: [ . .]. 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.
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 and from the program below. Summing across each row gives : one answer per observation. Summing down the rows gives : 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 , each three-feature row sum increases by , while each two-observation column sum increases by . The new outputs are and . Use the different increments to explain the reduction instead of memorizing axis numbers.
Read the table before using an API
Start with the six values through . Reshape them into two rows: and . The first axis selects an observation; the second selects a measurement. Shape 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 consumes the feature axis and leaves one total per observation. From the displayed rows and , calculate and ; the result has shape . Summing along axis consumes the observation axis instead, leaving one total per feature: , shape .
With keepdims=True, the column means retain a leading singleton dimension, shape . 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 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.
Rows are groups of observations
Predict before looking: Which row should sum to ?
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 .
Read across the top row to find , then across the bottom row to find . The picture therefore represents an array with shape : 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 and . That is why summing along axis returns two values. Summing down rows instead would return , 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
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: x has two observations and three features.
x = jnp.arange(6, dtype=jnp.float32).reshape(2, 3) 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.
# 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 unlesskeepdims=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.
# 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.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: 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: ; Dtype: float32; Row sums: [ . .]. 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.
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.
Center each measurement
# 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 ; centered rows are and .
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
# 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.
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.
import jax.numpy as jnp
def column_summary(x):
# TODO: reduce observations and return feature-wise values and shape
values = ...
shape = ...
return values, shapeReveal the 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 . 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.
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_meansShow a hint
Keep observation rows and measurement columns.
Reveal reference solution and reasoning
# 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 , while the measurement count stays three.
Diagnose an impossible reshape
Challenge
Try reshaping six values to . 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.
import jax.numpy as jnp
def diagnose_reshape(values):
# TODO: attempt the requested shape and capture its incompatibility
attempted = ...
repaired = ...
return attempted, repairedShow a hint
Count required elements before changing the code.
Reveal reference solution and reasoning
# 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==6An incompatible reshape is an element-count error. Changing a dtype or moving devices cannot fix it. Choose a shape whose product matches six.
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.
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
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.
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.