Code¶
Every chapter has companion code in code/ of the book's repository. Each script has a --cpu-smoke path that runs on a laptop with CPU PyTorch and exits 0, and most have a TPU path that needs a TPU VM with TorchTPU installed. No TPU numbers from these scripts are printed in the book unless a chapter says it measured them. Each folder's README.md lists what the CPU path checks and what only the TPU path can show.
Set up¶
From the repository root, with uv:
git clone https://github.com/ainaomotayo/torchtpu-book
cd torchtpu-book
uv venv --python 3.12 .venv
uv pip install --python .venv/bin/python -r requirements.txt # CPU torch, pytest, site tools
uv pip install --python .venv/bin/python -r requirements-optional.txt # optional: jax[cpu] for chapter 12
source .venv/bin/activate
With plain venv and pip, run python -m venv .venv, source .venv/bin/activate and pip install -r requirements.txt instead; requirements.txt already carries --extra-index-url https://download.pytorch.org/whl/cpu, so torch comes as the CPU build. Without jax, the chapter 12 kernel tests are skipped.
On a TPU VM, install TorchTPU next to the same requirements (chapter 8, Install TorchTPU on a TPU VM). The serving folders need vllm-torchtpu or sglang-torchtpu on the TPU host instead (chapter 18, chapter 19).
Run everything¶
pytest -q # every suite under tests/, CPU only
pytest tests/ch07 -q # one chapter
pytest.ini sets testpaths = tests and puts the repository root on the path. Every code/chNN_* folder has a tests/chNN/ suite that runs its --cpu-smoke path.
Folders¶
Commands run from the repository root. Multi-device TPU commands start with the launch line from chapter 13, shown below the table.
| Folder | Chapter | What it shows | CPU command | TPU command | Tests |
|---|---|---|---|---|---|
ch01_hardware |
1 | Peak FLOP/s from MXU geometry and clock, HBM and ICI time bounds, a systolic-array model | python code/ch01_hardware/hardware_math.py --cpu-smokepython code/ch01_hardware/systolic.py --cpu-smoke |
python code/ch01_hardware/hardware_math.py (also prints get_device_properties) |
tests/ch01/ |
ch02_rooflines |
2 | Arithmetic intensity, ridge points, roofline bounds, critical batch size, a timed matmul against its bounds | python code/ch02_rooflines/roofline.py --cpu-smoke |
python code/ch02_rooflines/roofline.py --m 8 --k 8192 --n 8192 |
tests/ch02/ |
ch03_stack |
3 | An environment check that proves a process runs on TorchTPU; a CUDA script ported before and after | python code/ch03_stack/check_env.py --cpu-smokepython code/ch03_stack/port_example/after_tpu.py --cpu-smoke |
python code/ch03_stack/check_env.py --json my_report.jsonpython code/ch03_stack/port_example/after_tpu.py |
tests/ch03/ |
ch04_execution |
4 | One model under each execution mode; a host-sync step against its torch.where rewrite; compile counts |
python code/ch04_execution/modes.py --cpu-smoke |
python code/ch04_execution/modes.pypython code/ch04_execution/modes.py --modes strict,debug |
tests/ch04/ |
ch05_memory |
5 | Tile padding, view decomposition, a copy counter for HLO dumps, layout and HBM probes | python code/ch05_memory/padding.py --cpu-smoke |
python code/ch05_memory/padding.py |
tests/ch05/ |
ch06_precision |
6 | Excess precision bit checks, 1, 3 and 6-pass matmul emulation, dtype-matched parity | python code/ch06_precision/excess_precision.py --cpu-smoke |
python code/ch06_precision/excess_precision.py --allow-excess-precision false (or true) |
tests/ch06/ |
ch07_dynamic_shapes |
7 | Buckets and their padding cost, bounded-dynamism bucket bounds, a static KV cache, recompile counting | python code/ch07_dynamic_shapes/bucketing.py --cpu-smoke |
python code/ch07_dynamic_shapes/bucketing.py |
tests/ch07/ |
ch08_install |
8 | Preflight of a fresh TPU VM or container, and agreement across the hosts of a slice | python code/ch08_install/preflight.py --cpu-smoke |
python preflight.py --chips 4 (copied to the VM)python code/ch08_install/preflight.py --aggregate preflight-logs --expect-hosts 4 |
tests/ch08/ |
ch09_porting |
9 | A CUDA-call scanner, a ported model with checks, MoE tensor parallelism, Hugging Face generation, Diffusers tensor parallelism | python code/ch09_porting/port_checklist.py --cpu-smokepython code/ch09_porting/port_model.py --cpu-smokepython code/ch09_porting/moe_tp.py --cpu-smokepython code/ch09_porting/hf_generate.py --cpu-smokepython code/ch09_porting/diffusers_tp.py --cpu-smoke |
python code/ch09_porting/port_model.py --json port_report.jsonpython code/ch09_porting/hf_generate.py --model Qwen/Qwen3.5-9Bpython code/ch09_porting/diffusers_tp.py --model stabilityai/stable-diffusion-3.5-medium --one-chip |
tests/ch09/ |
ch10_profiling |
10 | A profile captured and read in order: step time, idle time, top ops, bound type | python code/ch10_profiling/capture.py --cpu-smoke |
python code/ch10_profiling/capture.py --log-dir /tmp/profiler_output --steps 5 --compiled |
tests/ch10/ |
ch11_optimize |
11 | A naive and an optimized model, walked up the playbook one change at a time with parity first | python code/ch11_optimize/compare.py --cpu-smoke |
python code/ch11_optimize/compare.py |
tests/ch11/ |
ch12_pallas |
12 | A fused residual RMSNorm and SwiGLU Pallas kernel, its PyTorch reference and a tile planner (kernel part needs jax) |
python code/ch12_pallas/run.py --cpu-smoke |
python code/ch12_pallas/run.py |
tests/ch12/ |
ch13_collectives |
13 | A ring cost model for the four collectives; a demo that runs them on a 2D mesh | python code/ch13_collectives/collectives_demo.py --cpu-smoke |
torchrun --nproc_per_node=$WORLD_SIZE code/ch13_collectives/collectives_demo.py --tp 2 --mib 256 |
tests/ch13/ |
ch14_fsdp |
14 | FSDP memory, traffic and MFU arithmetic; a SimpleFSDP-style sharded run checked against one process | python code/ch14_fsdp/simple_fsdp_demo.py --cpu-smoke |
torchrun --nproc_per_node=$WORLD_SIZE code/ch14_fsdp/simple_fsdp_demo.py --tpu |
tests/ch14/ |
ch15_rl |
15 | GRPO advantages; a GRPO loop with rollout worker, trainer and weight sync, in one process or as Ray actors | python code/ch15_rl/grpo_loop.py --cpu-smoke |
python code/ch15_rl/grpo_loop.py --tpu |
tests/ch15/ |
ch16_case_study |
16 | The Muse Glimmer 30B worksheet and the MFU arithmetic behind the published figures | python code/ch16_case_study/estimate.py --cpu-smokepython code/ch16_case_study/mfu.py --cpu-smoke |
None needed: pure arithmetic | tests/ch16/ |
ch17_inference_math |
17 | Parameter counts, KV cache bytes, prefill and decode floors | python code/ch17_inference_math/kv_cache.py --cpu-smoke |
python code/ch17_inference_math/kv_cache.py --tpu |
tests/ch17/ |
ch18_vllm |
18 | vllm serve command lines from the documented recipes; a TTFT and TPOT client with a parity gate |
python code/ch18_vllm/launch_profiles.py --cpu-smokepython code/ch18_vllm/client.py --cpu-smoke |
python code/ch18_vllm/launch_profiles.py --launch quickstart-tp1 --cache-root "$HOME/tpu-cache"python code/ch18_vllm/client.py smoke --model meta-llama/Llama-3.2-1B-Instruct |
tests/ch18/ |
ch19_sglang |
19 | sglang.launch_server command lines from the recipes; an agentic client that reports radix cache hits per turn |
python code/ch19_sglang/launch_profiles.py --cpu-smokepython code/ch19_sglang/agentic_client.py --cpu-smoke |
python code/ch19_sglang/launch_profiles.py --launch gpt-oss-20b-agentic --cache-root "$HOME/tpu-cache"python code/ch19_sglang/agentic_client.py run --base-url http://localhost:30000 --model gpt-oss-20b --metrics |
tests/ch19/ |
ch20_llm_d |
20 | llm-d manifests for GKE TPU, a validator that checks them against the llm-d and vLLM-TorchTPU documentation and code, a prefix-cache routing simulation | python code/ch20_llm_d/validate_manifests.py --cpu-smokepython code/ch20_llm_d/scorer_sim.py --cpu-smoke |
Cluster: kubectl apply -f code/ch20_llm_d/manifests/baseline-v6e/ after the namespace, Secret and EPP exist |
tests/ch20/ |
ch21_operating |
21 | The chapter's PromQL, a checker against llm-d's metric names, an SLO check on benchmark percentiles | python code/ch21_operating/check_queries.py --cpu-smokepython code/ch21_operating/slo_check.py --cpu-smoke |
Cluster: python code/ch21_operating/check_queries.py --prometheus http://localhost:9090python code/ch21_operating/slo_check.py results.json --replicas 4 |
tests/ch21/ |
ch22_case_study |
22 | Estimates made before reading the case study, and ratios from its benchmark table | python code/ch22_case_study/analysis.py --cpu-smoke |
python code/ch22_case_study/analysis.py --log run.txt on a saved run of the case study notebook |
tests/ch22/ |
ch23_correctness |
23 | A parity report with sourced tolerances, a first-divergent-layer search, an injected bug found | python code/ch23_correctness/parity.py --cpu-smokepython code/ch23_correctness/bisect_demo.py --cpu-smoke |
python code/ch23_correctness/parity.pypython code/ch23_correctness/bisect_demo.py --bug-layer 7 |
tests/ch23/ |
ch24_evidence |
24 | Steady-state statistics, a fair comparison, goodput, a report that refuses numbers without provenance | python code/ch24_evidence/bench.py --cpu-smokepython code/ch24_evidence/report.py --cpu-smoke |
python code/ch24_evidence/bench.py --m 4096 --k 4096 --n 4096 --steps 50 |
tests/ch24/ |
ch25_extending |
25 | A runnable model of vLLM-TorchTPU's patch registry; a checker for ATen ops torch_tpu does not register | python code/ch25_extending/registry.py --cpu-smokepython code/ch25_extending/missing_op_check.py --cpu-smoke |
python code/ch25_extending/missing_op_check.py --dump-registrations tpu_ops.txt |
tests/ch25/ |
ch26_agents |
26 | The CPU-checkable half of the agent suite's ladder, and the gates to put around an agent's result | python code/samples/agent_suite/run_workflow.py --cpu-smokepython code/ch26_agents/gate_demo.py --cpu-smoke |
None of its own: give the same requests to tpu-agent in an installed suite; gate_demo.py --claim BASELINE CANDIDATE REPLICATES with measured numbers |
tests/ch26/, tests/samples/test_agent_suite_workflow.py |
solutions |
2, 12, 25 | Solutions to worked problems that ask for code: critical batch and MLP estimate (ch02), a fused residual RMSNorm kernel (ch12), the logaddexp parity test (ch25) |
python code/solutions/ch02/critical_batch.py --cpu-smokepython code/solutions/ch02/mlp_estimate.py --cpu-smokepython code/solutions/ch12/residual_rmsnorm.py --cpu-smokepython code/solutions/ch25/logaddexp_reference.py --cpu-smoke |
python code/solutions/ch25/logaddexp_reference.py --tpu |
tests/ch02/test_solutions.py, tests/ch12/, tests/ch25/ |
samples |
4, 9, 14, 18, 26 | Full sample scripts from the author's TorchTPU in Production series (Apache 2.0, see NOTICE); several chapter scripts build on pieces of them |
python code/samples/sample_01_torchtpu_execution_xprof_and_pallas.py --cpu-smokepython code/samples/sample_01_torchtpu_execution_xprof_and_pallas.py --hf-cpu-smokepython code/samples/sample_02_vllm_sglang_agentic_serving_and_raiden.py --cpu-smokepython code/samples/sample_03_torchtitan_simple_fsdp_scan_and_ray_grpo.py --cpu-smokepython code/samples/agent_suite/run_workflow.py --cpu-smoke |
--all, --hf-generate MODEL_ID and --tpu, listed in each script's docstring |
tests/samples/ |
The multi-device launch for chapters 9, 13 and 14 sets the topology variables before torchrun:
eval $(python3 -m torch.tpu.distributed | sed 's/^/export /')
torchrun --nproc_per_node=$WORLD_SIZE code/ch13_collectives/collectives_demo.py --tp 2 --mib 256
Chapter 15's --ray path needs Ray (pip install ray) and runs on a CPU: python code/ch15_rl/grpo_loop.py --ray.