Cloud TPU Mini-Course · Step 1 of 3Cloud TPU VM + CPU verifierLesson 2 of 2 in Phase 19

Phase 19 / TPU Setup: Provisioning & Runtime Verification

Bootstrap .venv and verify a TPU runtime receipt

Revision v0.18.1 ·

Lesson · about 20 minutes · CPU practice

Use the pinned TPU runtime, compare synchronized arithmetic with its oracle and distinguish requested backend/device readiness from a CPU rehearsal; retrieve the receipt and clean up only named owned resources.

Phase study guide: preparation, milestones and project evidence

Before you start

Before this: Select a TPU slice and provision your Cloud TPU VM
Hardware: CPU contract verifier; Cloud TPU VM or Colab TPU for target receipt

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/19-tpu/02-bootstrap-venv-and-verify-tpu-runtime-receipt/code/main.py

PowerShell command · repository folder
.\.venv\Scripts\python.exe phases/19-tpu/02-bootstrap-venv-and-verify-tpu-runtime-receipt/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: Prints the expected sum table and a receipt with separate arithmetic and requested-target status. The CPU rehearsal can verify the arithmetic but is not TPU readiness.

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

  • Bootstrap ~/jax-tpu-lab/.venv on a Cloud TPU VM and install jax[tpu] from the official libtpu wheel index.
  • Verify jax.default_backend(), jax.device_count(), and a synchronized jax.pmap reduction across 1, 4, or 8 chips.
  • Copy the JSON runtime receipt back to your workstation with gcloud compute tpus tpu-vm scp.
  • Delete the named TPU VM or its owning queued resource and verify those named resources are absent; unrelated TPU resources may remain.

The problem

After gcloud compute tpus tpu-vm create reports READY, you still cannot trust a benchmark or training job until Python inside your TPU VM's .venv proves it can load libtpu, see all attached TPU chips, execute a synchronized collective across them, and tear down cleanly so nothing keeps billing.

The idea

Bootstrap an isolated ~/jax-tpu-lab/.venv on the TPU VM Linux host with jax[tpu], run a deterministic jax.pmap runtime receipt across all local chips, copy the receipt back to your laptop with gcloud compute tpus tpu-vm scp, and delete the TPU VM (tpu-vm delete + tpu-vm list) whenever your session ends.

Why a synchronized pmap receipt is stronger than import jax

Importing jax confirms only that the package is available on the host. A mapped sum followed by jax.block_until_ready checks that the selected backend can finish device work and return the result. For DD devices, the fixture gives each device 8 consecutive integers and checks S(D)=∑k=08D−1k2S(D)=\sum_{k=0}^{8D-1}k^2. One CPU device produces 140; the requested four-device run should produce 10,416. The recorded rehearsal produced 140 on one CPU device, so its arithmetic check passed while backend and topology checks failed. A NumPy plot of the four-row calculation is an oracle, not evidence that four TPU devices ran. Read the receipt's backend, count and synchronized total together.

S(D)=∑k=08D−1k2=(8D−1)(8D)(16D−1)6,D=observed devicesS(D) = \sum_{k=0}^{8D-1} k^2 = \frac{(8D-1)(8D)(16D-1)}{6}, \quad D=\text{observed devices}

1. Bootstrap ~/jax-tpu-lab/.venv and install jax[tpu] over SSH

Create the virtual environment on the named TPU VM after it reaches READY, then install the reviewed requirements and the matching pinned TPU extra. Keep this environment identity with the receipt so a future run can be compared to the same package set. Do not interpret a successful install or import as device readiness; the next section checks actual synchronized execution.

Run instructions: Create ~/jax-tpu-lab/.venv and install jax[tpu] on the Cloud TPU VM
bash
# Install the pinned environment on the Cloud TPU VM
gcloud compute tpus tpu-vm ssh "$TPU_NAME" --zone="$ZONE" --command="mkdir -p ~/jax-tpu-lab"
gcloud compute tpus tpu-vm scp projects/reproducible-experiments/requirements.txt "$TPU_NAME":~/jax-tpu-lab/ --zone="$ZONE"
gcloud compute tpus tpu-vm ssh "$TPU_NAME" --zone="$ZONE" --command='set -euo pipefail; mkdir -p ~/jax-tpu-lab; python3 -m venv ~/jax-tpu-lab/.venv; ~/jax-tpu-lab/.venv/bin/python -m pip install -r ~/jax-tpu-lab/requirements.txt; ~/jax-tpu-lab/.venv/bin/python -m pip install \"jax[tpu]==0.9.2\" -f https://storage.googleapis.com/jax-releases/libtpu_releases.html'

Expected:

Uses the pinned requirements file and jax[tpu]==0.9.2; record both source and environment identity.

2. Run the runtime receipt script, copy the JSON receipt back, and delete the TPU VM

Run the saved script on the requested target, copy the receipt to your workstation, and check the three gates separately. arithmetic_ok compares the synchronized result with the sum-of-squares oracle; expected_backend_ok checks TPU rather than CPU; expected_topology_ok checks exactly four JAX devices. requested_target_ready is true only when all three pass. In the recorded CPU run, the observed total 140 matches the one-device oracle, but the requested four-device total is 10,416 and readiness is false.

Keep that receipt as evidence, then clean up the resource selected during provisioning. Delete the direct VM if that was the route, or delete its owning queued resource for Flex-start; verify the named resource is absent before considering the setup complete.

Run instructions: Run the runtime receipt verifier on the TPU VM and copy the receipt home
bash
# Run the runtime receipt verifier on the TPU VM and copy the receipt home
gcloud compute tpus tpu-vm ssh "$TPU_NAME" --zone="$ZONE" --command="mkdir -p ~/jax-tpu-lab"
gcloud compute tpus tpu-vm scp public/exercises/tpu-04.py "$TPU_NAME":~/jax-tpu-lab/ --zone="$ZONE"
gcloud compute tpus tpu-vm ssh "$TPU_NAME" --zone="$ZONE" \
  --command="set -euo pipefail; TPU_REQUIRE_TARGET=1 JAX_PLATFORMS=tpu ~/jax-tpu-lab/.venv/bin/python ~/jax-tpu-lab/tpu-04.py | tee ~/jax-tpu-lab/tpu-receipt.txt"
gcloud compute tpus tpu-vm scp "$TPU_NAME":~/jax-tpu-lab/tpu-receipt.txt ./ --zone="$ZONE"

Expected:

The receipt records source SHA256, pinned environment identity, expected and observed backend, expected and observed device count, arithmetic_ok, expected_backend_ok, expected_topology_ok, and requested_target_ready. On CPU, arithmetic may pass but target readiness must be false.

Run instructions: Delete this route’s TPU resources and verify their named absence
bash
# Flex-start: deleting the owning request with --force deletes its allocated VM too.
if [ -n "${QUEUED_RESOURCE_ID:-}" ]; then
  gcloud alpha compute tpus queued-resources delete "$QUEUED_RESOURCE_ID" --project="$PROJECT_ID" --zone="$ZONE" --force --quiet
else
  gcloud compute tpus tpu-vm delete "$TPU_NAME" --project="$PROJECT_ID" --zone="$ZONE" --quiet
fi
remaining_vm=$(gcloud compute tpus tpu-vm list --project="$PROJECT_ID" --zone="$ZONE" --filter="name=$TPU_NAME" --format="value(name)")
[ -z "$remaining_vm" ] || { echo "Named TPU VM still exists: $remaining_vm"; exit 1; }
if [ -n "${QUEUED_RESOURCE_ID:-}" ]; then
  remaining_request=$(gcloud alpha compute tpus queued-resources list --project="$PROJECT_ID" --zone="$ZONE" --filter="name=$QUEUED_RESOURCE_ID" --format="value(name)")
  [ -z "$remaining_request" ] || { echo "Owning queued resource still exists: $remaining_request"; exit 1; }
fi
printf "Named route resources are absent; unrelated resources may remain.\n"

Expected:

The named VM and, when used, its owning queued resource are absent. The filtered checks allow unrelated resources to remain.

Read the figure

The horizontal axis lists four row shards assigned to the selected four-chip fixture: values 0–7, 8–15, 16–23 and 24–31. The vertical axis is sum of squares. The per-shard bars are 140, 1,100, 3,084 and 6,092; the cumulative series ends at 10,416, the four-shard oracle. This is a NumPy calculation, not a recorded device result or receipt. The recorded CPU receipt instead has one device and total 140, matching only the first row. Next, require all four target devices and the TPU backend in the saved receipt.

Connect it to the computation

The total 10,416 is the oracle for the requested four-device fixture. The current local receipt instead records backend cpu, count 1 and total 140; its arithmetic is correct for what ran, while requested_target_ready is false. Do not promote the calculated four-device bar into a TPU claim. Retrieve the saved target receipt and verify its source and environment identity, backend, device count and synchronized result.

Figure data and execution details

Calculated expectation, without a device execution record

This figure is a calculated expectation. It does not report device execution.

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 the closed-form sum-of-squares oracle and pmap receipt builder

Create main.py with closed_form_sum_of_squares and build_runtime_receipt.

main.py · append build step 1
# Step 1 — Define the closed-form sum-of-squares oracle and pmap receipt builder
import hashlib
import json
import platform
from pathlib import Path
import jax
import jax.numpy as jnp
import numpy as np


def closed_form_sum_of_squares(num_devices, width=8):
    n = int(num_devices) * int(width)
    return float((n - 1) * n * (2 * n - 1) // 6)


def build_runtime_receipt(expected_backend="tpu", expected_device_count=4):
    devices = jax.local_devices()
    n_dev = len(devices)
    x = jnp.arange(n_dev * 8, dtype=jnp.float32).reshape(n_dev, 8)
    # Reduce across the target axis to summarize `per_device`.
    per_device = jax.pmap(lambda row: jnp.sum(row * row))(x)
    # Wait for device work to finish before timing it or comparing its result on the host.
    observed_total = float(jax.block_until_ready(jnp.sum(per_device)))
    expected_total = closed_form_sum_of_squares(n_dev, 8)
    backend = jax.default_backend()
    arithmetic_ok = bool(np.isclose(observed_total, expected_total))
    expected_backend_ok = backend == expected_backend
    expected_topology_ok = jax.device_count() == expected_device_count
    source_value = globals().get("__file__")
    source_path = Path(source_value) if isinstance(source_value, str) and source_value else None
    source_sha256 = hashlib.sha256(source_path.read_bytes()).hexdigest() if source_path is not None and source_path.is_file() else None
    source_identity = str(source_path.resolve()) if source_sha256 is not None else "unavailable: interactive execution has no readable __file__"
    payload = {
        "source_sha256": source_sha256,
        "source_identity": source_identity,
        "environment_lock": "projects/reproducible-experiments/requirements.txt; jax[tpu]==0.9.2",
        "python": platform.python_version(), "jax": jax.__version__,
        "expected_backend": expected_backend, "observed_backend": backend,
        "expected_device_count": expected_device_count, "device_count": jax.device_count(),
        "process_count": jax.process_count(),
        "local_device_count": n_dev, "per_device_sums": [float(v) for v in np.asarray(per_device)],
        "observed_total": observed_total, "expected_total": expected_total,
        "arithmetic_ok": arithmetic_ok, "expected_backend_ok": expected_backend_ok,
        "expected_topology_ok": expected_topology_ok,
        "requested_target_ready": bool(arithmetic_ok and expected_backend_ok and expected_topology_ok),
    }
    payload["receipt_sha256"] = hashlib.sha256(
        json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()[:16]
    return payload

Each local device computes the sum of squares of its 8-element row via jax.pmap, and the host verifies the synchronized total against the exact polynomial identity.

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).
  • jax.pmap(fn, in_axes=..., out_axes=...): Maps a function across leading array axes and executes replicas in parallel on XLA devices.
  • jnp.sum(x, axis=...): Adds JAX array values along the selected axis.

2 Verify the active runtime receipt and tabulate multi-chip expectations

Append slice_expectations and the receipt verification assertions to main.py.

main.py · append build step 2
# Step 2 — Verify the active runtime receipt and tabulate device-count expectations
slice_expectations = [
    {"slice": "1-device (CPU / v5e-1)", "devices": 1, "expected_sum": closed_form_sum_of_squares(1)},
    {"slice": "4-device (v5litepod-4 / v6e-4)", "devices": 4, "expected_sum": closed_form_sum_of_squares(4)},
    {"slice": "8-device (v5litepod-8 / v6e-8)", "devices": 8, "expected_sum": closed_form_sum_of_squares(8)},
]
receipt = build_runtime_receipt(expected_backend="tpu", expected_device_count=4)
# CPU rehearsal validates arithmetic while explicitly showing the TPU target is not ready.
assert receipt["arithmetic_ok"] is True
if receipt["observed_backend"] == "cpu":
    assert receipt["requested_target_ready"] is False
# Actual TPU launch/preflight commands set TPU_REQUIRE_TARGET=1 and require exact backend/count.
if __import__("os").environ.get("TPU_REQUIRE_TARGET") == "1":
    if receipt["source_sha256"] is None:
        raise SystemExit("TPU_REQUIRE_TARGET=1 requires a saved verifier script with a readable source identity")
    if not receipt["requested_target_ready"]:
        raise SystemExit("Requested TPU target is not ready: expected TPU backend and exactly 4 JAX devices")
print("Runtime receipt:", json.dumps(receipt, sort_keys=True))
print("Expected pmap sums by slice:", {s["slice"]: s["expected_sum"] for s in slice_expectations})

Knowing the exact expected sum for 1, 4, and 8 devices lets you immediately spot if a 4-chip or 8-chip TPU VM only initialized a single device.

3 Step 3: Verify invariants on the completed state

Run the final shape and numerical assertions to confirm the state built in Steps 1 and 2.

main.py · append build step 3
receipt = build_runtime_receipt(expected_backend="tpu", expected_device_count=4)
assert receipt["arithmetic_ok"] is True

Checking these invariants confirms the computation is ready for the full worked experiment.

View the cumulative build in main.py

These blocks append in order to your separate practice file.

main.py · cumulative Python build
# Step 1 — Define the closed-form sum-of-squares oracle and pmap receipt builder
import hashlib
import json
import platform
from pathlib import Path
import jax
import jax.numpy as jnp
import numpy as np


def closed_form_sum_of_squares(num_devices, width=8):
    n = int(num_devices) * int(width)
    return float((n - 1) * n * (2 * n - 1) // 6)


def build_runtime_receipt(expected_backend="tpu", expected_device_count=4):
    devices = jax.local_devices()
    n_dev = len(devices)
    x = jnp.arange(n_dev * 8, dtype=jnp.float32).reshape(n_dev, 8)
    # Reduce across the target axis to summarize `per_device`.
    per_device = jax.pmap(lambda row: jnp.sum(row * row))(x)
    # Wait for device work to finish before timing it or comparing its result on the host.
    observed_total = float(jax.block_until_ready(jnp.sum(per_device)))
    expected_total = closed_form_sum_of_squares(n_dev, 8)
    backend = jax.default_backend()
    arithmetic_ok = bool(np.isclose(observed_total, expected_total))
    expected_backend_ok = backend == expected_backend
    expected_topology_ok = jax.device_count() == expected_device_count
    source_value = globals().get("__file__")
    source_path = Path(source_value) if isinstance(source_value, str) and source_value else None
    source_sha256 = hashlib.sha256(source_path.read_bytes()).hexdigest() if source_path is not None and source_path.is_file() else None
    source_identity = str(source_path.resolve()) if source_sha256 is not None else "unavailable: interactive execution has no readable __file__"
    payload = {
        "source_sha256": source_sha256,
        "source_identity": source_identity,
        "environment_lock": "projects/reproducible-experiments/requirements.txt; jax[tpu]==0.9.2",
        "python": platform.python_version(), "jax": jax.__version__,
        "expected_backend": expected_backend, "observed_backend": backend,
        "expected_device_count": expected_device_count, "device_count": jax.device_count(),
        "process_count": jax.process_count(),
        "local_device_count": n_dev, "per_device_sums": [float(v) for v in np.asarray(per_device)],
        "observed_total": observed_total, "expected_total": expected_total,
        "arithmetic_ok": arithmetic_ok, "expected_backend_ok": expected_backend_ok,
        "expected_topology_ok": expected_topology_ok,
        "requested_target_ready": bool(arithmetic_ok and expected_backend_ok and expected_topology_ok),
    }
    payload["receipt_sha256"] = hashlib.sha256(
        json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()[:16]
    return payload

# Step 2 — Verify the active runtime receipt and tabulate device-count expectations
slice_expectations = [
    {"slice": "1-device (CPU / v5e-1)", "devices": 1, "expected_sum": closed_form_sum_of_squares(1)},
    {"slice": "4-device (v5litepod-4 / v6e-4)", "devices": 4, "expected_sum": closed_form_sum_of_squares(4)},
    {"slice": "8-device (v5litepod-8 / v6e-8)", "devices": 8, "expected_sum": closed_form_sum_of_squares(8)},
]
receipt = build_runtime_receipt(expected_backend="tpu", expected_device_count=4)
# CPU rehearsal validates arithmetic while explicitly showing the TPU target is not ready.
assert receipt["arithmetic_ok"] is True
if receipt["observed_backend"] == "cpu":
    assert receipt["requested_target_ready"] is False
# Actual TPU launch/preflight commands set TPU_REQUIRE_TARGET=1 and require exact backend/count.
if __import__("os").environ.get("TPU_REQUIRE_TARGET") == "1":
    if receipt["source_sha256"] is None:
        raise SystemExit("TPU_REQUIRE_TARGET=1 requires a saved verifier script with a readable source identity")
    if not receipt["requested_target_ready"]:
        raise SystemExit("Requested TPU target is not ready: expected TPU backend and exactly 4 JAX devices")
print("Runtime receipt:", json.dumps(receipt, sort_keys=True))
print("Expected pmap sums by slice:", {s["slice"]: s["expected_sum"] for s in slice_expectations})

receipt = build_runtime_receipt(expected_backend="tpu", expected_device_count=4)
assert receipt["arithmetic_ok"] is True

Run the example

python3 phases/19-tpu/02-bootstrap-venv-and-verify-tpu-runtime-receipt/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 — Define the closed-form sum-of-squares oracle and pmap receipt builder
import hashlib
import json
import platform
from pathlib import Path
import jax
import jax.numpy as jnp
import numpy as np


def closed_form_sum_of_squares(num_devices, width=8):
    n = int(num_devices) * int(width)
    return float((n - 1) * n * (2 * n - 1) // 6)


def build_runtime_receipt(expected_backend="tpu", expected_device_count=4):
    devices = jax.local_devices()
    n_dev = len(devices)
    x = jnp.arange(n_dev * 8, dtype=jnp.float32).reshape(n_dev, 8)
    # Each device reduces its eight values to one local sum of squares.
    per_device = jax.pmap(lambda row: jnp.sum(row * row))(x)
    # Wait for device work to finish before timing it or comparing its result on the host.
    observed_total = float(jax.block_until_ready(jnp.sum(per_device)))
    expected_total = closed_form_sum_of_squares(n_dev, 8)
    backend = jax.default_backend()
    arithmetic_ok = bool(np.isclose(observed_total, expected_total))
    expected_backend_ok = backend == expected_backend
    expected_topology_ok = jax.device_count() == expected_device_count
    source_value = globals().get("__file__")
    source_path = Path(source_value) if isinstance(source_value, str) and source_value else None
    source_sha256 = hashlib.sha256(source_path.read_bytes()).hexdigest() if source_path is not None and source_path.is_file() else None
    source_identity = str(source_path.resolve()) if source_sha256 is not None else "unavailable: interactive execution has no readable __file__"
    payload = {
        "source_sha256": source_sha256,
        "source_identity": source_identity,
        "environment_lock": "projects/reproducible-experiments/requirements.txt; jax[tpu]==0.9.2",
        "python": platform.python_version(), "jax": jax.__version__,
        "expected_backend": expected_backend, "observed_backend": backend,
        "expected_device_count": expected_device_count, "device_count": jax.device_count(),
        "process_count": jax.process_count(),
        "local_device_count": n_dev, "per_device_sums": [float(v) for v in np.asarray(per_device)],
        "observed_total": observed_total, "expected_total": expected_total,
        "arithmetic_ok": arithmetic_ok, "expected_backend_ok": expected_backend_ok,
        "expected_topology_ok": expected_topology_ok,
        "requested_target_ready": bool(arithmetic_ok and expected_backend_ok and expected_topology_ok),
    }
    payload["receipt_sha256"] = hashlib.sha256(
        json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()[:16]
    return payload


# Step 2 — Verify the active runtime receipt and tabulate device-count expectations
slice_expectations = [
    {"slice": "1-device (CPU / v5e-1)", "devices": 1, "expected_sum": closed_form_sum_of_squares(1)},
    {"slice": "4-device (v5litepod-4 / v6e-4)", "devices": 4, "expected_sum": closed_form_sum_of_squares(4)},
    {"slice": "8-device (v5litepod-8 / v6e-8)", "devices": 8, "expected_sum": closed_form_sum_of_squares(8)},
]
receipt = build_runtime_receipt(expected_backend="tpu", expected_device_count=4)
# CPU rehearsal validates arithmetic while explicitly showing the TPU target is not ready.
assert receipt["arithmetic_ok"] is True
if receipt["observed_backend"] == "cpu":
    assert receipt["requested_target_ready"] is False
# Actual TPU launch/preflight commands set TPU_REQUIRE_TARGET=1 and require exact backend/count.
if __import__("os").environ.get("TPU_REQUIRE_TARGET") == "1":
    if receipt["source_sha256"] is None:
        raise SystemExit("TPU_REQUIRE_TARGET=1 requires a saved verifier script with a readable source identity")
    if not receipt["requested_target_ready"]:
        raise SystemExit("Requested TPU target is not ready: expected TPU backend and exactly 4 JAX devices")
print("Runtime receipt:", json.dumps(receipt, sort_keys=True))
print("Expected pmap sums by slice:", {s["slice"]: s["expected_sum"] for s in slice_expectations})

Expected result: Prints the expected sum table and a receipt with separate arithmetic and requested-target status. The CPU rehearsal can verify the arithmetic but is not TPU readiness.

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

Runtime receipt: {"arithmetic_ok": true, "device_count": 1, "environment_lock": "projects/reproducible-experiments/requirements.txt; jax[tpu]==0.9.2", "expected_backend": "tpu", "expected_backend_ok": false, "expected_device_count": 4, "expected_topology_ok": false, "expected_total": 140.0, "jax": "0.9.2", "local_device_count": 1, "observed_backend": "cpu", "observed_total": 140.0, "per_device_sums": [140.0], "process_count": 1, "python": "3.14.3", "receipt_sha256": "64561213664a634b", "requested_target_ready": false, "source_identity": "unavailable: interactive execution has no readable __file__", "source_sha256": null}
Expected pmap sums by slice: {'1-device (CPU / v5e-1)': 140.0, '4-device (v5litepod-4 / v6e-4)': 10416.0, '8-device (v5litepod-8 / v6e-8)': 85344.0}
Runtime receipt: {"arithmetic_ok": true, "device_count": 1, "environment_lock": "projects/reproducible-experiments/requirements.txt; jax[tpu]==0.9.2", "expected_backend": "tpu", "expected_backend_ok": false, "expected_device_count": 4, "expected_topology_ok": false, "expected_total": 140.0, "jax": "0.9.2", "local_device_count": 1, "observed_backend": "cpu", "observed_total": 140.0, "per_device_sums": [140.0], "process_count": 1, "python": "3.14.3", "receipt_sha256": "64561213664a634b", "requested_target_ready": false, "source_identity": "unavailable: interactive execution has no readable __file__", "source_sha256": null}
Expected pmap sums by slice: {'1-device (CPU / v5e-1)': 140.0, '4-device (v5litepod-4 / v6e-4)': 10416.0, '8-device (v5litepod-8 / v6e-8)': 85344.0}
Per-chip sums on a 4-chip slice: [140.0, 1100.0, 3084.0, 6092.0] Total: 10416.0
Named-resource cleanup checks passed; unrelated nodes may remain.
4-device expected sum: 10416.0 8-device expected sum: 85344.0 receipt hash: 64561213664a634b
Requested four-device TPU readiness: False ; simulated wrong-count contract rejected: True
Real runtime receipt qualifies as four-device TPU: False
Overnight idle cost avoided (USD): 74.4
PASS: tpu-04

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

Compare per-device row sums on a 4-chip TPU slice

Compare per-device row sums on a 4-chip TPU slice · Python experiment
# Experiment — Compare per-device row sums on a 4-chip TPU slice
x4 = jnp.arange(4 * 8, dtype=jnp.float32).reshape(4, 8)
# Reduce along axis=1 to compute `row_sums_4`.
row_sums_4 = [float(v) for v in jnp.sum(x4 * x4, axis=1)]
print("Per-chip sums on a 4-chip slice:", row_sums_4, "Total:", sum(row_sums_4))
assert row_sums_4 == [140.0, 1100.0, 3084.0, 6092.0] and sum(row_sums_4) == 10416.0

Expected: Chip 0 sums 0^2..7^2 = 140.0, chip 1 sums 8^2..15^2 = 1100.0, chip 2 sums 16^2..23^2 = 3084.0, and chip 3 sums 24^2..31^2 = 6092.0 (total 10416.0).

Inspecting per_device_sums confirms that distinct shards of x were placed and squared on each of the 4 chips.

Verify absence of named route-owned resources

Verify absence of named route-owned resources · Python experiment
import json
def named_resources_absent(gcloud_nodes_json, target_vm_name, queued_requests_json="[]", queued_resource_id=None):
    nodes = json.loads(gcloud_nodes_json)
    requests = json.loads(queued_requests_json)
    vm_absent = all(row.get("name") != target_vm_name for row in nodes)
    request_absent = queued_resource_id is None or all(row.get("name") != queued_resource_id for row in requests)
    return vm_absent and request_absent

# An unrelated VM can remain; the named VM and owning request are absent.
assert named_resources_absent('[{"name":"other-course-vm","state":"READY"}]', "jax-tpu-course", "[]", "jax-tpu-course-request") is True
assert named_resources_absent('[{"name":"jax-tpu-course","state":"READY"}]', "jax-tpu-course") is False
print("Named-resource cleanup checks passed; unrelated nodes may remain.")

Expected: The cleanup verifier accepts remaining unrelated TPU VMs, rejects a still-present target VM, and checks the owning queued request when one was used.

Cleanup must prove absence of the resources created by this route. Requiring an empty zone could encourage deleting unrelated user resources.

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 the 4-device and 8-device oracle values. On the available runtime, assert arithmetic_ok; assert requested_target_ready only when observed_backend is tpu and device_count is exactly 4.

Show a writing guide and starter scaffold

How to write this exercise code

Learner-only inputs, outputs, checks and hints

Inputs

  • The closed-form sum helper and the active CPU/TPU receipt with expected and observed backend/device counts.

Outputs

  • Calculated four-/eight-device oracle values, actual arithmetic result and requested-target readiness.

Invariants to check

  • arithmetic_ok is separate from expected_backend_ok and expected_topology_ok.
  • requested_target_ready requires the requested TPU backend and exact expected count; a CPU rehearsal does not qualify TPU hardware.

Hints

  • Use observed_backend and device_count from the actual receipt.
  • Test a schema-only wrong-count control separately from real hardware observations.
Your attempt · complete the TODOs
def audit_runtime_sum_receipt(receipt, closed_form_sum_of_squares):
    # TODO: compare both theoretical totals and assert readiness matches the requested backend/count contract.
    raise NotImplementedError
Reveal the reference solution
Reference solution
# Exercise solution
s4 = closed_form_sum_of_squares(4)
s8 = closed_form_sum_of_squares(8)
print("4-device expected sum:", s4, "8-device expected sum:", s8, "receipt hash:", receipt["receipt_sha256"])
# Assert invariant `s4 == 10416.0 and s8 == 85344.0 and receipt["arithmetic_ok"] is True` holds
assert s4 == 10416.0 and s8 == 85344.0 and receipt["arithmetic_ok"] is True
if receipt["observed_backend"] == "cpu":
    assert receipt["requested_target_ready"] is False

# Readiness is a requested contract, not a synonym for successful arithmetic.
expected_ready = bool(receipt['arithmetic_ok'] and receipt['observed_backend'] == 'tpu'
                      and receipt['device_count'] == 4)
assert receipt['requested_target_ready'] is expected_ready
# A schema-only negative control is not hardware evidence.
wrong_count = dict(receipt, observed_backend='tpu', device_count=8)
wrong_count_ready = bool(wrong_count['arithmetic_ok'] and wrong_count['observed_backend'] == 'tpu'
                         and wrong_count['device_count'] == 4)
assert wrong_count_ready is False
print('Requested four-device TPU readiness:', expected_ready,
      '; simulated wrong-count contract rejected:', not wrong_count_ready)

Detect a silent fallback from 4 TPU chips to 1 CPU device

Foundations

Write is_four_chip_tpu_receipt(r) using the real receipt schema: return True only when r['observed_backend'] == 'tpu', r['local_device_count'] == 4, r['device_count'] == 4, and r['observed_total'] is 10416.0. Missing keys should return False.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • A candidate runtime receipt mapping with backend, local device count, and observed total fields.

Outputs

  • A Boolean predicate for the exact four-chip TPU receipt contract.

Invariants to check

  • Use observed_backend from the emitted receipt.
  • Missing keys, CPU backend, wrong local/global device count, or wrong synchronized total return False.

Hints

  • Validate backend, count, and total independently.
  • Use a tolerance only for the floating representation of the exact integer total.
Your attempt · complete the TODOs
import numpy as np

def is_four_chip_tpu_receipt(receipt):
    try:
        # Use the schema returned by build_runtime_receipt.
        return bool(
            receipt["observed_backend"] == "tpu"
            and receipt["local_device_count"] == 4
            and receipt["device_count"] == 4
            and np.isclose(receipt["observed_total"], 10416.0)
        )
    except (KeyError, TypeError):
        return False
Show a hint

Read backend from observed_backend, not backend; test the local count, global JAX device count, and synchronized sum independently. Handle missing fields as a failed check.

Reveal reference solution and reasoning
Detect a silent fallback from 4 TPU chips to 1 CPU device · Python solution
# Detect a silent fallback from 4 TPU chips to 1 CPU device (Foundations)
def is_four_chip_tpu_receipt(r):
    try:
        return bool(
            r["observed_backend"] == "tpu"
            and r["local_device_count"] == 4
            and r["device_count"] == 4
            and np.isclose(r["observed_total"], 10416.0)
        )
    except (KeyError, TypeError):
        return False

cpu_result = is_four_chip_tpu_receipt(receipt)
print("Real runtime receipt qualifies as four-device TPU:", cpu_result)
assert cpu_result is (receipt["observed_backend"] == "tpu" and receipt["device_count"] == 4)

The predicate uses fields actually emitted by build_runtime_receipt. It rejects missing fields, CPU fallback, and either local or global device-count mismatch.

Estimate hourly billing savings from immediate teardown

Transfer / diagnosis

If a 4-chip TPU slice costs 4.804.80 USD/hour and verification plus experiment takes 0.50.5 hours, compute how much you save by deleting the VM immediately instead of keeping it running for 1616 total hours, including the active time.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • Hourly slice cost, active verification duration of 0.5 hours, and total elapsed VM time of 16 hours.

Outputs

  • Avoided idle duration and the corresponding teardown savings.

Invariants to check

  • Total elapsed time includes the active work, so idle time is total time minus active time; immediate teardown and the overnight choice share the active-time cost.

Hints

  • Subtract active hours from total hours to get avoidable idle hours.
  • Multiply only those idle hours by the hourly rate; 16 idle hours would be $76.80, while 16 total hours including 0.5 active hour yields $74.40.
Your attempt · complete the TODOs
def idle_teardown_savings(hourly_cost, active_hours, total_hours):
    # TODO: compute avoidable idle hours and savings when total_hours includes active work.
    raise NotImplementedError
Show a hint

Compare 16.0 * 4.80 against 0.5 * 4.80.

Reveal reference solution and reasoning
Estimate hourly billing savings from immediate teardown · Python solution
# Estimate hourly billing savings from immediate teardown (Transfer / diagnosis)
hourly_rate = 4.80
saved_usd = round((16.0 - 0.5) * hourly_rate, 2)
print("Overnight idle cost avoided (USD):", saved_usd)
# Assert invariant `saved_usd == 74.4` holds
assert saved_usd == 74.4

Deleting the Cloud TPU VM immediately after copying artifacts back avoids paying for 15.5 idle hours.

Check your understanding

Why does build_runtime_receipt() run jax.pmap across jax.local_devices() and call jax.block_until_ready instead of only checking jax.default_backend()?

Choose one answer

Diagnose the result

If pip install 'jax[tpu]' fails to find libtpu, verify that -f https://storage.googleapis.com/jax-releases/libtpu_releases.html was passed to pip install inside the activated ~/jax-tpu-lab/.venv on the Linux TPU VM.

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

Carry forward

  • Always install jax[tpu] inside an isolated ~/jax-tpu-lab/.venv on the TPU VM host.
  • Verify backend, local_device_count, and a synchronized jax.pmap sum-of-squares receipt before starting longer experiments.
  • Copy your receipt back with gcloud compute tpus tpu-vm scp, run tpu-vm delete, and confirm tpu-vm list is empty.

Keep your evidence

Download evidence template

Keep arithmetic_ok, expected_backend_ok, expected_topology_ok, requested_target_ready, expected/observed backend and counts, source identity or its explicit absence, observed/expected reduction and receipt digest. Separate calculated 4-/8-device expectations from observed execution and require the gated target preflight to fail closed.

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. A separate runtime receipt collector is implemented in the target instructions. Bounded hardware receipts cover v5e1 launch, resume and precision checks; four single-device Pallas cases; and a four-device v5e collective fixture. Each receipt applies only to its recorded source, environment, cases and hardware. Other lessons and TPU configurations require separate qualification. Execution matrix and target qualification.

Primary references

Phase 19 Integration Project

Bring this phase together: Inspect CPU device inventory, BF16 storage, and collective participant arithmetic

Checkpoint to prove: Select a single-host TPU topology, provision a Cloud TPU VM (or Colab TPU), bootstrap jax[tpu] in an isolated .venv, verify pmap execution, and confirm clean VM deletion.

Work in projects/tpu-runtime-audit/starter/model.py. Complete stages 1 and 2 for independent calculations and changed-condition diagnosis, then retain the stage 3 evidence with --evidence-dir runs/tpu-runtime-audit. Stage 4 integrates the checks. Learner commands explicitly select the starter; --implementation solution is instructor reference execution. This bounded practice does not certify the entire phase or target hardware.