Phase 01 / Arrays & pure functions
Shapes, broadcasting, and dtypes
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
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.
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/02-shapes-broadcasting-and-dtypes/code/main.py.\.venv\Scripts\python.exe phases/01-arrays/02-shapes-broadcasting-and-dtypes/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-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: Rows: and ; shape , dtype float32.
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
- 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.
- Batch
x: (2, 3)Two rows, three features per row.
- Shared bias
b: (3,)Align the trailing feature axis.
- Result
x + 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 and matching targets . Their aligned residuals are , so mean squared error is zero. If the same targets are stored as a column with shape , subtraction broadcasts the two vectors into a matrix: . Squaring and averaging those four residuals gives , 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.
Align axes before reducing
Predict: Why is checking that the loss is scalar insufficient?
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 intermediate. Each row describes a different shape contract.
Work the shape rule one dimension at a time
Align and as and . The trailing matches, and the leading can broadcast to . By contrast, aligns as : trailing conflicts with . That expression cannot add one scalar per row without another axis.
Represent row offsets as . The leading matches observations and the trailing 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,) → incompatibleDo not test axes with only square arrays
If a batch happens to have , a vector of length 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 and row offsets . 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 and targets with shape align as and , producing all pairwise residuals of shape . For the recorded three-element example, matching predictions and targets should give three zeros, but the broadcast matrix has rows , , and . 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, repeats across rows; for row-wise offsets, repeats across features.
(B,) − (B,1) → (B,B)
Intended aligned-example contract: prediction.shape == target.shapeShape 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 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.
Broadcasting repeats the bias across rows
Predict before looking: Why are both rows of the difference equal to ?
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 . The repeated vertical bands show that feature receives in every observation, feature receives , and feature receives .
Connect it to the computation
The bias has shape , which aligns with the last axis of the batch. Broadcasting applies the same feature-wise addition to both rows. For example, the input becomes , while becomes .
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 ; this figure would then have horizontal bands.
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 Define two examples with three float32 features
Create a (2, 3) batch whose rows are examples and columns are features.
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.
bias = jnp.array([10., 20., 30.], dtype=jnp.float32)
y = batch + biasJAX 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.
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.
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.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
# 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: and ; shape , 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.
[[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.
Make the pairwise bug visible
# 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 and loss , 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
# 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 .
This scalar example isolates precision from broadcasting. Autodiff and compilation do not make every arithmetic operation exact.
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 . 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.
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_rowReveal the 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.
import jax.numpy as jnp
def combine_offsets(batch, feature_bias, row_offsets):
# TODO: apply feature and observation offsets with distinct shapes
raise NotImplementedErrorShow a hint
Use bias shape and offsets shape . Do not swap their semantic roles.
Reveal reference solution and reasoning
# 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 in every feature and the second receives , 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.
import jax.numpy as jnp
def aligned_mse(prediction, target):
# TODO: reject shape mismatch before computing scalar mean squared error
raise NotImplementedErrorShow 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 (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.
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.
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
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.
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.