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

Phase 01 / Arrays & pure functions

Shapes, broadcasting, and dtypes

Revision v0.18.1 ·

Lesson · about 50 minutes · CPU practice

Specify broadcasting contracts and detect silent pairwise-loss and dtype mistakes.

Phase study guide: preparation, milestones and project evidence

Before you start

Before this: From NumPy to jax.numpy
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/02-shapes-broadcasting-and-dtypes/code/main.py

PowerShell command · repository folder
.\.venv\Scripts\python.exe phases/01-arrays/02-shapes-broadcasting-and-dtypes/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: Rows: [11.,22.,33.][11., 22., 33.] and [14.,25.,36.][14., 25., 36.]; shape (2,3)(2, 3), dtype float32.

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

  • Apply the trailing-dimension broadcasting rule before execution.
  • Distinguish feature-wise and observation-wise offsets with explicit singleton axes.
  • Find a silent pairwise-residual bug using values and shape checks.
  • State dtype and precision assumptions for numerical experiments.

The problem

Your code runs, but has it added the bias to the right axis? This is a common array puzzle: a legal operation can still answer the wrong question. We’ll use small tables to see exactly which values combine, then catch a broadcasting mistake that turns one error per example into a whole matrix of errors.

The idea

Before adding or subtracting arrays, name what each axis represents. Broadcasting aligns dimensions from the right and reuses singleton dimensions. A legal broadcast can still answer the wrong question, especially when a final mean hides the resulting shape.

Broadcast along the missing axis
  1. Batchx: (2, 3)

    Two rows, three features per row.

  2. Shared biasb: (3,)

    Align the trailing feature axis.

  3. Resultx + b: (2, 3)

    Add the same three bias values to each row.

Conceptual example: broadcasting repeats values logically; it does not add a new example axis. A target (2, 1) and prediction (2,) can accidentally form a (2, 2) result.

Conceptual illustration. Verify the computation in the lesson’s Python experiments.

Catch the scalar that hides a shape mistake

Take predictions [1,3][1,3] and matching targets [1,3][1,3]. Their aligned residuals are [0,0][0,0], so mean squared error is zero. If the same targets are stored as a column with shape (2,1)(2,1), subtraction broadcasts the two vectors into a (2,2)(2,2) matrix: [[0,2],[−2,0]][[0,2],[-2,0]]. Squaring and averaging those four residuals gives 22, even though every target matches its corresponding prediction.

Both routes end in a scalar, so checking only the loss value's type or whether it can be differentiated will miss the semantic error. Inspect the residual shape before reducing it, and first test an aligned example whose expected residuals are known. A singleton axis communicates which data should be reused; it is not a cosmetic reshape.

Feature bias reuses a vector across observations; row offsets reuse each scalar across features. The final row creates all-pairs residuals. A mean would hide the unwanted (n,n)(n,n) intermediate. Each row describes a different shape contract.

Open full-size diagram
(A+b)i,j=Ai,j+bj,A∈RM×N,  b∈R1×N(A + b)_{i,j} = A_{i,j} + b_j, \qquad A \in \mathbb{R}^{M \times N},\; b \in \mathbb{R}^{1 \times N}

Work the shape rule one dimension at a time

Align (2,3)(2, 3) and (3,)(3,) as (2,3)(2, 3) and (1,3)(1, 3). The trailing 33 matches, and the leading 11 can broadcast to 22. By contrast, (2,)(2,) aligns as (1,2)(1, 2): trailing 22 conflicts with 33. That expression cannot add one scalar per row without another axis.

Represent row offsets as (2,1)(2, 1). The leading 22 matches observations and the trailing 11 broadcasts over the three features. A singleton axis is a statement about how data should be reused, not a random reshape to silence an exception.

feature bias: (2,3) + (1,3) → (2,3)
row offset:  (2,3) + (2,1) → (2,3)
wrong row offset: (2,3) + (2,) → incompatible

Do not test axes with only square arrays

If a batch happens to have B=DB=D, a vector of length BB can accidentally fit as a feature vector. The expression succeeds while doing the wrong calculation. A test with two observations and three features forces those meanings apart.

Use distinguishable values, such as feature bias [10,20,30][10, 20, 30] and row offsets [100,200][100, 200]. Then inspect at least two rows and columns. Shape checks alone do not detect every semantically wrong operation; the values need a known reference too.

A legal broadcast can change your loss

Predictions with shape (B,)(B,) and targets with shape (B,1)(B,1) align as (1,B)(1,B) and (B,1)(B,1), producing all pairwise residuals of shape (B,B)(B,B). For the recorded three-element example, matching predictions and targets should give three zeros, but the broadcast matrix has rows [0,2,4][0,2,4], [−2,0,2][-2,0,2], and [−4,−2,0][-4,-2,0]. The output scalar after a mean hides that extra pairwise comparison.

This is a plausible loss with the wrong meaning, not a numerical instability. Enforce shape equality at the boundary where each prediction must pair with one target, then reduce. For feature-wise bias, (D,)(D,) repeats across rows; for row-wise offsets, (B,1)(B,1) repeats across features.

(B,) − (B,1) → (B,B)
Intended aligned-example contract: prediction.shape == target.shape

Shape and dtype are separate contracts

Shape says how values are arranged; dtype says how each value is represented. Use explicit float32 inputs for this course experiment so the precision assumption is visible. Default JAX precision and X64 configuration can differ from expectations brought from a NumPy workflow.

A correctly shaped float32 calculation can still lose a small change at large magnitude. That is numerical representation, not an axis error. Record both shape and dtype in debugging output, and choose comparisons appropriate to their scale. Enabling a different dtype is not a substitute for correcting a broadcast.

Make boundary checks before reducing

A reduction often hides shape information. Before averaging residuals, check whether the array is the expected (B,)(B,) vector or an unintended matrix. Likewise, check that feature statistics have one entry per feature and that row offsets have the observation dimension.

These checks belong at meaningful boundaries, rather than after every elementary addition. A descriptive failure before a loss is calculated is more useful than a plausible scalar whose semantics have already been lost.

Read the figure

This heatmap shows the added amount, computed as the output minus the input batch. It does not show the final output array. Rows are observations and columns are features; the cell values and color bar measure added bias.

Both rows read (10,20,30)(10,20,30). The repeated vertical bands show that feature 00 receives 1010 in every observation, feature 11 receives 2020, and feature 22 receives 3030.

Connect it to the computation

The bias has shape (3,)(3,), which aligns with the last axis of the (2,3)(2,3) batch. Broadcasting applies the same feature-wise addition to both rows. For example, the input (1,2,3)(1,2,3) becomes (11,22,33)(11,22,33), while (4,5,6)(4,5,6) becomes (14,25,36)(14,25,36).

Identical rows in this picture mean identical additions, not identical predictions. If you intended a different offset for each observation, you would need a row-wise bias with a compatible shape, such as (2,1)(2,1); this figure would then have horizontal bands.

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 Define two examples with three float32 features

Create a (2, 3) batch whose rows are examples and columns are features.

main.py · append build step 1
import jax.numpy as jnp
batch = jnp.array([[1., 2., 3.], [4., 5., 6.]], dtype=jnp.float32)

The named axes tell us that a length-three bias should align with the last, feature axis.

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

2 Broadcast one feature bias across both rows

Add the length-three bias to the (2, 3) batch.

main.py · append build step 2
bias = jnp.array([10., 20., 30.], dtype=jnp.float32)
y = batch + bias

JAX aligns the bias with the trailing dimension, so each feature receives the same offset in both examples.

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

3 Verify the resulting shape and one concrete row

Check that the batch remains (2, 3) and that the second row has the expected offsets.

main.py · append build step 3
assert y.shape == (2, 3)
assert jnp.allclose(y[1], jnp.array([14., 25., 36.]))

The shape check catches accidental expansion; the row values independently confirm which axis received the bias.

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.

main.py · cumulative Python build
import jax.numpy as jnp
batch = jnp.array([[1., 2., 3.], [4., 5., 6.]], dtype=jnp.float32)

bias = jnp.array([10., 20., 30.], dtype=jnp.float32)
y = batch + bias

assert y.shape == (2, 3)
assert jnp.allclose(y[1], jnp.array([14., 25., 36.]))

Run the example

python3 phases/01-arrays/02-shapes-broadcasting-and-dtypes/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
# Shapes, broadcasting, and dtypes: Before adding or subtracting arrays, name what each axis represents.
import jax.numpy as jnp
batch = jnp.array([[1., 2., 3.], [4., 5., 6.]], dtype=jnp.float32)
bias = jnp.array([10., 20., 30.], dtype=jnp.float32)
y = batch + bias
print(y)
print("Shape:", y.shape, "dtype:", y.dtype)
# Check tensor shape invariant: `y.shape == (2, 3)`
assert y.shape == (2, 3)
assert jnp.allclose(y[1], jnp.array([14., 25., 36.]))

Expected result: Rows: [11.,22.,33.][11., 22., 33.] and [14.,25.,36.][14., 25., 36.]; shape (2,3)(2, 3), dtype float32.

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

[[11. 22. 33.]
 [14. 25. 36.]]
Shape: (2, 3) dtype: float32
aligned residuals: [0. 0. 0.]
pairwise residuals: [[ 0.  2.  4.]
 [-2.  0.  2.]
 [-4. -2.  0.]]
float32 large + 1 − large: 0.0
PASS: arrays-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

Make the pairwise bug visible

Make the pairwise bug visible · Python experiment
# Experiment — Make the pairwise bug visible: The final result is scalar in both cases.
predictions = jnp.array([1., 3., 5.])
targets = jnp.array([1., 3., 5.])
correct_residuals = predictions - targets
pairwise_residuals = predictions - targets[:, None]
print("aligned residuals:", correct_residuals)
print("pairwise residuals:", pairwise_residuals)
# Check tensor shape invariant: `correct_residuals.shape == (3,)`
assert correct_residuals.shape == (3,)
# Check tensor shape invariant: `pairwise_residuals.shape == (3, 3)`
assert pairwise_residuals.shape == (3, 3)
assert jnp.allclose(jnp.mean(correct_residuals ** 2), 0.)
assert jnp.allclose(jnp.mean(pairwise_residuals ** 2), 16. / 3.)

Expected: The incorrect broadcast produces shape (3,3)(3, 3) and loss 16/316/3, despite perfect aligned predictions.

The final result is scalar in both cases. Checking only the final loss shape would miss this objective bug.

Observe a precision limit separately

Observe a precision limit separately · Python experiment
# Experiment — Observe a precision limit separately: This scalar example isolates precision from broadcasting.
large = jnp.array(100_000_000., dtype=jnp.float32)
print("float32 large + 1 − large:", float((large + 1.) - large))
assert float((large + 1.) - large) == 0.
# Check tensor shape invariant: `large.shape == ()`
assert large.shape == ()

Expected: The recorded difference is zero because the representable spacing at this magnitude exceeds 11.

This scalar example isolates precision from broadcasting. Autodiff and compilation do not make every arithmetic operation exact.

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 different scalar offset to each row using offsets [100.,200.][100., 200.]. Make its shape explicit.

Show a writing guide and starter scaffold

How to write this exercise code

Learner-only inputs, outputs, checks and hints

Inputs

  • A (2, 3) batch and one scalar row offset per observation.

Outputs

  • An explicit offset shape and the row-offset result.

Invariants to check

  • The feature axis remains length three.
  • Each row receives its own scalar offset.
  • The batch shape is unchanged.

Hints

  • Make the singleton feature dimension explicit.
  • Keep row offsets distinct from feature biases.
Your attempt · complete the TODOs
import jax.numpy as jnp

def add_row_offsets(batch, row_offsets):
    # TODO: arrange offsets to broadcast over features
    offsets_by_row = ...
    result = ...
    return result, offsets_by_row
Reveal the reference solution
Reference solution
# Exercise solution: Add a different scalar offset to each row using offsets [100., 200.].
offsets = jnp.array([100., 200.])[:, None]
z = batch + offsets
# Check tensor shape invariant: `offsets.shape == (2, 1)`
assert offsets.shape == (2, 1)
assert jnp.allclose(z, jnp.array([[101.,102.,103.],[204.,205.,206.]]))

Use both kinds of offsets together

Practice

Add the feature bias and row offsets to the original batch. Derive every row before running, then check with an explicitly constructed array.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • The lesson batch, feature bias, and two row offsets.

Outputs

  • The combined table with both offsets applied.

Invariants to check

  • Feature bias and row offsets have different axes.
  • The output retains the original batch shape.

Hints

  • Give each offset an explicit shape before adding.
  • Verify every row and feature.
Your attempt · complete the TODOs
import jax.numpy as jnp

def combine_offsets(batch, feature_bias, row_offsets):
    # TODO: apply feature and observation offsets with distinct shapes
    raise NotImplementedError
Show a hint

Use bias shape (3,)(3,) and offsets shape (2,1)(2, 1). Do not swap their semantic roles.

Reveal reference solution and reasoning
Use both kinds of offsets together · Python solution
# Use both kinds of offsets together (Practice)
combined = batch + bias + jnp.array([100., 200.])[:, None]
# Check tensor shape invariant: `combined.shape == (2, 3)`
assert combined.shape == (2, 3)
assert jnp.allclose(combined, jnp.array([[111., 122., 133.], [214., 225., 236.]]))

The first row receives 100100 in every feature and the second receives 200200, while the feature bias differs by column.

Reject an aligned-loss contract violation

Challenge

Write an MSE function that requires prediction and target shapes to match. Test zero loss for matching vectors and rejection of a column target. Explain why an automatic reshape might hide a data-ordering problem.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • Prediction and target arrays with matching vector shapes, then a column-shaped target.

Outputs

  • A scalar MSE for aligned vectors and a descriptive mismatch error.

Invariants to check

  • Shape metadata is checked before subtraction.
  • Do not silently reshape or broadcast mismatched data.

Hints

  • Compare shape tuples before arithmetic.
  • Use a clear exception for invalid alignment.
Your attempt · complete the TODOs
import jax.numpy as jnp

def aligned_mse(prediction, target):
    # TODO: reject shape mismatch before computing scalar mean squared error
    raise NotImplementedError
Show a hint

Raise a descriptive ValueError before subtracting. The check is based on shape metadata, not array truth values.

Reveal reference solution and reasoning
Reject an aligned-loss contract violation · Python solution
# Reject an aligned-loss contract violation (Challenge)
def aligned_mse(prediction, target):
    if prediction.shape != target.shape:
        raise ValueError("aligned prediction and target shapes must match")
    return jnp.mean((prediction - target) ** 2)
assert jnp.allclose(aligned_mse(predictions, targets), 0.)
try:
    aligned_mse(predictions, targets[:, None])
except ValueError:
    pass
else:
    raise AssertionError("Column targets must be rejected")

Fix shapes at the data/model interface according to the intended example order. Blindly reshaping inside a loss can conceal mismatched semantics.

Check your understanding

Which offset shape adds one scalar to each row of a (2,3)(2, 3) batch?

Choose one answer

Diagnose the result

When broadcasting fails, align trailing dimensions on paper. When it succeeds with a surprising loss, inspect the residual shape before reduction and compare with hand-derived values. When a small change disappears, inspect dtype and magnitude. Use asymmetric shape tests so accidentally equal dimension sizes do not conceal a wrong axis.

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

Carry forward

  • Broadcasting compatibility does not imply semantic correctness.
  • A singleton axis declares reuse along a particular dimension.
  • Prediction/target mismatch can silently create all-pairs residuals.
  • Check dtype separately from shape and record numerical scale.

Keep your evidence

Download evidence template

Keep an axis sketch, asymmetric offset checks, aligned-versus-pairwise residual arrays, a rejected shape mismatch, and the float32 precision observation. Explain the intended residual contract.

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