Onboarding · Local CPULaptop CPULesson 3 of 4 in Phase 00

Phase 00 / Setup & first steps

Practice with four virtual CPU devices

Revision v0.18.1 ·

Lesson · about 60 minutes · Logical CPU devices

Start four logical CPU devices, inspect row-sharded and replicated arrays, and diagnose an indivisible batch.

Phase study guide: preparation, milestones and project evidence

Before you start

Before this: Meet your arrays and devices
Hardware: 4 logical CPU devices on one host

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/03-virtual-cpu-devices/code/main.py

PowerShell command · repository folder
.\.venv\Scripts\python.exe phases/00-welcome/03-virtual-cpu-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: CPU devices: 44. Four input shards of shape (1,2)(1,2). Global shape (4,2)(4,2); result [[1,3][[1,3],[5,7][5,7],[9,11][9,11],[13,15]][13,15]]. Device repr and JAX version 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

  • Start four virtual CPU devices in a fresh process.
  • Explain global shape, shard index and local shape.
  • Compare row partitioning with replication.
  • Diagnose divisibility and distinguish CPU practice from TPU evidence.

The problem

You can explore how JAX splits an array across devices using just your laptop. We’ll create four logical CPU devices, give each one a piece of an array, and compare the result with NumPy. Start with the setup and array/device lessons. These logical devices share your CPU: they help us learn placement, but they do not reproduce accelerator speed or memory.

The idea

Logical CPU devices let us practice how a global array is divided and addressed. They share a physical host. Treat them as a way to make placement visible, then use a real accelerator run to investigate accelerator memory, communication and speed.

Choose the beginner CPU route or the optional placement branch

If array shapes and transformed functions are new to you, continue from the first array lesson to Arrays & pure functions. Ordinary CPU lessons do not require virtual devices or cloud setup. Return here after JAX transformations and the first distributed-placement lesson. This branch assumes you can name the axis split across devices, explain what a replica contains and distinguish a JIT specialization from a new array value.

For a minimal placement prediction, imagine four logical devices and an array with eight rows. A row partition gives each device two rows; replication gives each device all eight. Inspect the reported shard indices to distinguish those cases. Four logical CPU devices do not create four physical accelerators. A physical TPU target additionally needs a reviewed source, pinned environment, expected backend and expected topology.

Distinguish ownership from extra computing power

Suppose a global array has four rows and each logical device owns one row. The global shape still describes all four rows; a local shard describes the one row stored for that owner. Asking for the global shape and inspecting a local buffer are different operations.

The ownership heatmap assigns a category to each device. A darker device color does not mean more work or a faster device. Follow the row boundary and the device label together.

Set the logical-device configuration before JAX initializes its backend, then inspect the actual device count in a fresh process. Changing a flag after initialization does not retroactively repartition an already-running process.

Xglobal∈RD0×D1  →shard  {X(d)∈R(D0/P)×D1}d=0P−1X_{\text{global}} \in \mathbb{R}^{D_0 \times D_1} \;\xrightarrow{\text{shard}}\; \{X^{(d)} \in \mathbb{R}^{(D_0 / P) \times D_1}\}_{d=0}^{P-1}

Configure the runtime before it exists

Open the lesson workspace from setup and create main.py. The first block imports JAX, chooses CPU, and requests four CPU devices. Importing jax is allowed before the configuration; querying devices or creating an array can initialize the backend. That initialization is the boundary after which changing the count is too late.

Run python main.py as a fresh process. In Jupyter or Colab, restart the kernel/runtime and use Run all so this configuration is the first JAX operation. If you already ran an earlier lesson in that kernel, merely rerunning this cell cannot reliably rebuild the runtime. The explicit count check gives you a repair instruction instead of silently proceeding with one device. A terminal alternative is JAX_PLATFORMS=cpu JAX_NUM_CPU_DEVICES=4 python main.py; Windows PowerShell uses $env:JAX_PLATFORMS="cpu" and $env:JAX_NUM_CPU_DEVICES="4" before python main.py.

Distinguish logical devices from your CPU hardware

Four reported CPU devices do not mean you bought four CPUs or reserved four isolated cores. They share your computer and its resources. Each is a target JAX can place an array on. Keep the actual JAX version, device platform, process count and device count in your report so readers know what was tested.

This exercise has one controller process and four addressable devices. Multi-host JAX involves additional processes and coordination; this exercise does not test those. Even if you time an operation here, the observation belongs to this CPU setup and workload. It is distinct from whether the same partitioning is fast on a TPU.

A global array contains local pieces

The input x has global shape (4,2)(4,2): four rows, two features each. The mesh names the four logical devices along data, and P("data",None) assigns the first array axis across them while keeping both features of a row together. The recorded shard report makes this concrete: device 0 owns row 0 with values [0,1][0,1], device 1 owns [2,3][2,3], through device 3 owning [6,7][6,7]. Each local shape is (1,2)(1,2), while x.shape remains (4,2)(4,2).

Use shard.index to map a local piece back to global positions and shard.data to inspect its values. In this single-process exercise, np.asarray(x) gathers the fully addressable global array to the host. Predict the local shape again for twelve rows: four-way row partitioning should give (3,2)(3,2) on each device. Five rows cannot be divided evenly; replication keeps all five rows on every device instead of dropping one.

Global rows [0,1] [2,3] [4,5] [6,7]
             ↓     ↓     ↓     ↓
CPU device   0     1     2     3
local shape (1,2) on every device; global shape (4,2)

Check arithmetic separately from placement

The arithmetic 2*x + 1 is elementwise, so each output depends only on the matching input cell. For row [0,1][0,1], hand-calculate [1,3][1,3]; for row [6,7][6,7], calculate [13,15][13,15]. The recorded global result contains those rows at its beginning and end, and the NumPy comparison checks all entries. The shard report checks placement, so neither check can stand in for the other.

block_until_ready waits for the result before reporting. Here it provides completion ordering; no timing claim follows from it. Now predict the local shape for five rows before running: a four-way row split cannot give equal integer row counts, so the recorded error is expected. Choose replication when all five rows must remain available on each logical device, and inspect the local shapes to confirm the repair.

Read the figure

Each cell represents a position in the global array, and its number identifies the logical CPU device that owns that position. The colors are categories: device 33 is not “more powerful” than device 00.

Both cells in row 00 belong to device 00; both cells in row 11 belong to device 11, and the same pattern continues through row 33. Horizontal bands show that this layout partitions rows while keeping each row’s features together.

Connect it to the computation

The global shape is (4,2)(4,2), so splitting its first axis across four devices gives each device a local piece with shape (1,2)(1,2). This is the spatial meaning of the row partition in the code. The numbers in the figure are ownership labels, not the original array’s contents.

You can check the interpretation by locating row 22, feature 11: its owner is device 22. These logical devices share the host CPU. The figure establishes where values are placed, not a measured speedup or the behavior of four physical accelerators.

Figure data and execution details

Recorded environment: JAX 0.9.2 · 4 CPU devices

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 Start a fresh CPU runtime

Create main.py in your course workspace. Paste this block first. If using a notebook, restart its kernel before running any cell.

main.py · append build step 1
# Step 1 — Start a fresh CPU runtime
import jax
jax.config.update("jax_platforms", "cpu")
# Select the CPU backend and virtual device count before initializing JAX.
jax.config.update("jax_num_cpu_devices", 4)
import jax.numpy as jnp
import numpy as np
from jax.sharding import Mesh, NamedSharding, PartitionSpec as P
devices = jax.devices("cpu")
if len(devices) != 4:
    raise RuntimeError("Expected four CPU devices. Restart the notebook kernel, then Run all; do not run an earlier JAX cell first.")
mesh = Mesh(np.array(devices), ("data",))
rows = NamedSharding(mesh, P("data", None))
replicated = NamedSharding(mesh, P())

Configuration happens before devices() or array creation initializes a backend. This file explicitly chooses CPU even on a GPU machine.

Explain the APIs in this step
  • Mesh(devices, axis_names): Names device axes in a mesh used to describe array placement.
  • NamedSharding(mesh, spec): Combines a device mesh and partition specification to describe array placement.

2 Place and compute

Append this block in the same file. Predict the shapes and values before running.

main.py · append build step 2
# Step 2 — Place and compute: Mesh axis names describe placement.
host = np.arange(8, dtype=np.float32).reshape(4, 2)
# Place `x` explicitly onto the target JAX device.
x = jax.device_put(host, rows)
# Wrap with `jax.jit` (`y`) so XLA traces and compiles the function.
y = jax.jit(lambda a: 2 * a + 1, in_shardings=rows, out_shardings=rows)(x)
# Wait for device work to finish before timing it or comparing its result on the host.
y.block_until_ready()

Mesh axis names describe placement. They are separate from the numerical array dimensions.

Explain the APIs in this step
  • array.reshape(new_shape): Reorganizes tensor axes without changing the total element count (array.size).
  • jax.device_put(x, device=...): Places or transfers an array to the requested device or sharding; dispatch is asynchronous.
  • jax.jit(fn) / @jax.jit: Traces a function for its input signatures and compiles it; changed shapes, dtypes, or static arguments can trigger another compilation.
  • output.block_until_ready(): Waits for asynchronous device work on this array to finish, which is needed before measuring completed computation time.

3 Inspect and verify

Append the checks, save the file and run python main.py with the setup lesson environment.

main.py · append build step 3
# Step 3 — Inspect and verify
print("JAX version:", jax.__version__)
print("CPU devices:", len(devices))
for shard in x.addressable_shards:
    print("Device", shard.device.id, "index", shard.index, "values", np.asarray(shard.data))
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_array_equal(np.asarray(y), 2 * host + 1)
assert len(x.addressable_shards) == 4
# Check tensor shape invariant: `all(shard.data.shape == (1, 2) for shard in x.addressable_shards)`
assert all(shard.data.shape == (1, 2) for shard in x.addressable_shards)
print("Global shape:", x.shape, "result:", np.asarray(y).tolist())

Assertions compare against host calculations or hand-derived values; printing a sharding object alone is separate from correctness.

View the cumulative build in main.py

These blocks append in order to your separate practice file.

main.py · cumulative Python build
# Step 1 — Start a fresh CPU runtime
import jax
jax.config.update("jax_platforms", "cpu")
# Select the CPU backend and virtual device count before initializing JAX.
jax.config.update("jax_num_cpu_devices", 4)
import jax.numpy as jnp
import numpy as np
from jax.sharding import Mesh, NamedSharding, PartitionSpec as P
devices = jax.devices("cpu")
if len(devices) != 4:
    raise RuntimeError("Expected four CPU devices. Restart the notebook kernel, then Run all; do not run an earlier JAX cell first.")
mesh = Mesh(np.array(devices), ("data",))
rows = NamedSharding(mesh, P("data", None))
replicated = NamedSharding(mesh, P())

# Step 2 — Place and compute: Mesh axis names describe placement.
host = np.arange(8, dtype=np.float32).reshape(4, 2)
# Place `x` explicitly onto the target JAX device.
x = jax.device_put(host, rows)
# Wrap with `jax.jit` (`y`) so XLA traces and compiles the function.
y = jax.jit(lambda a: 2 * a + 1, in_shardings=rows, out_shardings=rows)(x)
# Wait for device work to finish before timing it or comparing its result on the host.
y.block_until_ready()

# Step 3 — Inspect and verify
print("JAX version:", jax.__version__)
print("CPU devices:", len(devices))
for shard in x.addressable_shards:
    print("Device", shard.device.id, "index", shard.index, "values", np.asarray(shard.data))
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_array_equal(np.asarray(y), 2 * host + 1)
assert len(x.addressable_shards) == 4
# Check tensor shape invariant: `all(shard.data.shape == (1, 2) for shard in x.addressable_shards)`
assert all(shard.data.shape == (1, 2) for shard in x.addressable_shards)
print("Global shape:", x.shape, "result:", np.asarray(y).tolist())

Run the example

python3 phases/00-welcome/03-virtual-cpu-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 — Start a fresh CPU runtime
import jax
jax.config.update("jax_platforms", "cpu")
# Select the CPU backend and virtual device count before initializing JAX.
jax.config.update("jax_num_cpu_devices", 4)
import jax.numpy as jnp
import numpy as np
from jax.sharding import Mesh, NamedSharding, PartitionSpec as P
devices = jax.devices("cpu")
if len(devices) != 4:
    raise RuntimeError("Expected four CPU devices. Restart the notebook kernel, then Run all; do not run an earlier JAX cell first.")
mesh = Mesh(np.array(devices), ("data",))
rows = NamedSharding(mesh, P("data", None))
replicated = NamedSharding(mesh, P())

# Step 2 — Place and compute: Mesh axis names describe placement.
host = np.arange(8, dtype=np.float32).reshape(4, 2)
# Place `x` explicitly onto the target JAX device.
x = jax.device_put(host, rows)
# Wrap with `jax.jit` (`y`) so XLA traces and compiles the function.
y = jax.jit(lambda a: 2 * a + 1, in_shardings=rows, out_shardings=rows)(x)
# Wait for device work to finish before timing it or comparing its result on the host.
y.block_until_ready()

# Step 3 — Inspect and verify
print("JAX version:", jax.__version__)
print("CPU devices:", len(devices))
for shard in x.addressable_shards:
    print("Device", shard.device.id, "index", shard.index, "values", np.asarray(shard.data))
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_array_equal(np.asarray(y), 2 * host + 1)
assert len(x.addressable_shards) == 4
# Check tensor shape invariant: `all(shard.data.shape == (1, 2) for shard in x.addressable_shards)`
assert all(shard.data.shape == (1, 2) for shard in x.addressable_shards)
print("Global shape:", x.shape, "result:", np.asarray(y).tolist())

Expected result: CPU devices: 44. Four input shards of shape (1,2)(1,2). Global shape (4,2)(4,2); result [[1,3][[1,3],[5,7][5,7],[9,11][9,11],[13,15]][13,15]]. Device repr and JAX version 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:31.513460+00:00 · Python 3.14.3 · JAX 0.9.2 · 4 CPU devices

JAX version: 0.9.2
CPU devices: 4
Device 0 index (slice(0, 1, None), slice(None, None, None)) values [[0. 1.]]
Device 1 index (slice(1, 2, None), slice(None, None, None)) values [[2. 3.]]
Device 2 index (slice(2, 3, None), slice(None, None, None)) values [[4. 5.]]
Device 3 index (slice(3, 4, None), slice(None, None, None)) values [[6. 7.]]
Global shape: (4, 2) result: [[1.0, 3.0], [5.0, 7.0], [9.0, 11.0], [13.0, 15.0]]
JAX version: 0.9.2
CPU devices: 4
Device 0 index (slice(0, 1, None), slice(None, None, None)) values [[0. 1.]]
Device 1 index (slice(1, 2, None), slice(None, None, None)) values [[2. 3.]]
Device 2 index (slice(2, 3, None), slice(None, None, None)) values [[4. 5.]]
Device 3 index (slice(3, 4, None), slice(None, None, None)) values [[6. 7.]]
Global shape: (4, 2) result: [[1.0, 3.0], [5.0, 7.0], [9.0, 11.0], [13.0, 15.0]]
Negative input result: [[-3.0, -5.0], [-7.0, -9.0], [-11.0, -13.0], [-15.0, -17.0]]
Replicated local shapes: [(4, 2), (4, 2), (4, 2), (4, 2)]
Expected indivisible row dimension
Expected indivisible row dimension
PASS: welcome-cpu

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

Keep the shape, change the values

Keep the shape, change the values · Python experiment
# Experiment — Keep the shape, change the values
negative = -host - 2
# Place `negative_x` explicitly onto the target JAX device.
negative_x = jax.device_put(negative, rows)
# Wrap with `jax.jit` (`negative_y`) so XLA traces and compiles the function.
negative_y = jax.jit(lambda a: 2*a+1, in_shardings=rows, out_shardings=rows)(negative_x)
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_array_equal(np.asarray(negative_y), 2*negative+1)
# Check tensor shape invariant: `all(s.data.shape == (1,2) for s in negative_x.addressable_shards)`
assert all(s.data.shape == (1,2) for s in negative_x.addressable_shards)
print("Negative input result:", np.asarray(negative_y).tolist())

Expected: Result [[−3,−5][[-3,-5],[−7,−9][-7,-9],[−11,−13][-11,-13],[−15,−17]][-15,-17]]; local shapes remain (1,2)(1,2).

Placement follows the declared shape/specification, not the signs or magnitudes of array elements.

Replicate instead of partitioning

Replicate instead of partitioning · Python experiment
# Experiment — Replicate instead of partitioning: Replication stores full copies.
copies = jax.device_put(host, replicated)
assert copies.is_fully_replicated
assert len(copies.addressable_shards) == 4
for shard in copies.addressable_shards:
    # Transfer the device result to the host for an independent NumPy comparison.
    np.testing.assert_array_equal(np.asarray(shard.data), host)
print("Replicated local shapes:", [s.data.shape for s in copies.addressable_shards])

Expected: Four local arrays of shape (4,2)(4,2), each containing the entire input.

Replication stores full copies. A global array shape alone cannot tell you how much of it lives on each device.

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.

Predict and verify the per-device shapes for twelve rows, then demonstrate how replication repairs an indivisible five-row placement without deleting data.

Show a writing guide and starter scaffold

How to write this exercise code

Learner-only inputs, outputs, checks and hints

Inputs

  • Four virtual CPU devices and the row-sharded placement from the lesson.
  • Twelve rows with two features, plus a five-row placement case.

Outputs

  • Observed shard shapes and slices for twelve rows.
  • A captured uneven-placement failure and a replicated placement retaining all five rows.

Invariants to check

  • Every source row appears in the reference comparison.
  • Replication preserves data but does not prove uneven partition support.
  • Label logical CPU devices accurately.

Hints

  • Use shard indices to select matching reference rows.
  • Keep partition failure and replicated repair as separate observations.
Your attempt · complete the TODOs
import jax
import numpy as np

def audit_row_placements(row_sharding, devices):
    # TODO: place the requested arrays and inspect shard metadata
    raise NotImplementedError
Reveal the reference solution
Reference solution
# Exercise solution
twelve = np.arange(24,dtype=np.float32).reshape(12,2)
# Place `z` explicitly onto the target JAX device.
z = jax.device_put(twelve, rows)
# Wrap with `jax.jit` (`z2`) so XLA traces and compiles the function.
z2 = jax.jit(lambda a:a*a, in_shardings=rows, out_shardings=rows)(z)
# Check tensor shape invariant: `all(s.data.shape == (3,2) for s in z2.addressable_shards)`
assert all(s.data.shape == (3,2) for s in z2.addressable_shards)
for shard in z2.addressable_shards:
    # Transfer the device result to the host for an independent NumPy comparison.
    np.testing.assert_array_equal(np.asarray(shard.data), (twelve*twelve)[shard.index])

uneven = np.arange(10,dtype=np.float32).reshape(5,2)
try:
    jax.device_put(uneven, rows)
except ValueError:
    print("Expected indivisible row dimension")
else:
    raise AssertionError("Expected divisibility failure")
# Place `fixed` explicitly onto the target JAX device.
fixed = jax.device_put(uneven, replicated)
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_array_equal(np.asarray(fixed), uneven)
assert fixed.is_fully_replicated

Move from four rows to twelve

Challenge

Create twelve two-feature rows with values 00 through 2323. Predict shard shape and check every slice of a squared output.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • Four row-sharded devices and twelve two-feature rows.
  • The squared output for each row.

Outputs

  • Every output shard and its matching NumPy slice.

Invariants to check

  • Each shard index selects matching global rows.
  • Local shape matches an even partition.

Hints

  • Build the full reference before selecting slices.
  • Compare the complete shard payload.
Your attempt · complete the TODOs
import jax
import numpy as np

def verify_twelve_rows(row_sharding):
    # TODO: square the sharded data and compare every indexed slice
    raise NotImplementedError
Show a hint

Use each shard index to select the corresponding NumPy reference slice.

Reveal reference solution and reasoning
Move from four rows to twelve · Python solution
# Move from four rows to twelve (Challenge): The twelve rows split into four groups of three.
twelve = np.arange(24,dtype=np.float32).reshape(12,2)
# Place `z` explicitly onto the target JAX device.
z = jax.device_put(twelve, rows)
# Wrap with `jax.jit` (`z2`) so XLA traces and compiles the function.
z2 = jax.jit(lambda a:a*a, in_shardings=rows, out_shardings=rows)(z)
# Check tensor shape invariant: `all(s.data.shape == (3,2) for s in z2.addressable_shards)`
assert all(s.data.shape == (3,2) for s in z2.addressable_shards)
for shard in z2.addressable_shards:
    # Transfer the device result to the host for an independent NumPy comparison.
    np.testing.assert_array_equal(np.asarray(shard.data), (twelve*twelve)[shard.index])

The twelve rows split into four groups of three. Index-based comparisons establish that the right values occupy each piece, rather than checking only a total.

Repair a batch that does not divide evenly

Challenge

Place a (5,2)(5,2) array with the same row sharding. Capture the failure. Repair this placement demonstration by replicating it, and explain why that does not prove the partitioned algorithm supports uneven batches.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • The same four-way row sharding and a five-by-two input.

Outputs

  • A captured partitioning failure and a replicated placement with all rows.

Invariants to check

  • No row is dropped to force divisibility.
  • Replication is not described as uneven partition support.

Hints

  • Capture the expected placement error.
  • Inspect the replicated values and state the evidence limit.
Your attempt · complete the TODOs
import jax
import numpy as np

def diagnose_uneven_rows(row_sharding):
    # TODO: capture the partition attempt, then test replicated placement
    raise NotImplementedError
Show a hint

Do not drop a row to hide the error.

Reveal reference solution and reasoning
Repair a batch that does not divide evenly · Python solution
# Repair a batch that does not divide evenly (Challenge): Five rows cannot be evenly split across the four-way data axis.
uneven = np.arange(10,dtype=np.float32).reshape(5,2)
try:
    jax.device_put(uneven, rows)
except ValueError:
    print("Expected indivisible row dimension")
else:
    raise AssertionError("Expected divisibility failure")
# Place `fixed` explicitly onto the target JAX device.
fixed = jax.device_put(uneven, replicated)
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_array_equal(np.asarray(fixed), uneven)
assert fixed.is_fully_replicated

Five rows cannot be evenly split across the four-way data axis. Replication preserves all observations but changes the memory/communication plan; padding requires a mask when computing means.

Check your understanding

What does a (12,2)(12,2) global array sharded with P("data",None) over four devices mean?

Choose one answer

Diagnose the result

Five rows cannot be evenly split across the four-way data axis. Replication preserves all observations but changes the memory/communication plan; padding requires a mask when computing means.

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

Carry forward

  • Configure the runtime before it exists
  • Distinguish logical devices from your CPU hardware
  • A global array contains local pieces
  • Check arithmetic separately from placement

Keep your evidence

Download evidence template

Keep package/device reports, global and local shapes, shard index/value tables, NumPy comparisons, changed-shape predictions, and the five-row failure/repair. State that the run uses one host and does not validate TPU performance.

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 reference configures logical CPU devices to practice placement and sharding. Logical devices do not measure TPU performance. Use the execution matrix to review device selection and data ownership before adapting a separate target program. Execution matrix and target qualification.

Primary references