Skip to content

Install TorchTPU on a TPU VM

Use this guide when you want TorchTPU on a TPU v6e or v5p VM (or a v5e queued resource), on one host or on every worker of a multi-host slice, and a check that proves each host sees and uses its devices. For TPU v7x (Ironwood), use Run TorchTPU on GKE instead: TorchTPU's VM guide says GKE "is necessary to access recent TPU hardware". The reasons behind each step (capacity models, the CPU index, why every worker must agree) are in chapter 8.

v7x provisioning in the public documentation

The public documents differ on how TPU v7x is provisioned. The vLLM-TorchTPU Cloud TPU Setup page generates queued-resource commands for v7x. Google Cloud's TPU queued resources documentation says the Cloud TPU API does not support Ironwood (TPU7x) or later generations, and TorchTPU's VM guide says GKE "is necessary to access recent TPU hardware". Plan on GKE for v7x; chapter 8 explains the choice.

Prerequisites

  • The gcloud CLI and a Google Cloud project with an active paid billing account. A new project is safer than a reused one (see the troubleshooting table).
  • The global accelerator quota GPUS_ALL_REGIONS above 0 and the regional TPU quota for your generation: PREEMPTIBLE_TPU_V6E, PREEMPTIBLE_TPU_V5P, or tpu-v5s-litepod-serving-preemptible / tpu-v5s-litepod-preemptible for v5e. New projects start GPUS_ALL_REGIONS at 0, which blocks every TPU request.
  • A zone with capacity for your machine type. The TPU Builders Program Getting Started Guide lists us-east5-a, us-east5-b, us-central1-a, europe-west4-a and southamerica-west1-a for ct6e-standard-4t.
  • For the preflight check: code/ch08_install/preflight.py from this book's repository (source).

Steps

1. Prepare the project

gcloud auth login
gcloud config set project YOUR_PROJECT_ID
gcloud services enable tpu.googleapis.com compute.googleapis.com
gcloud components install alpha --quiet      # needed for queued-resources commands

Optionally run the pre-flight diagnostic script, which checks billing, the default VPC, organization policies, API access, service account permissions and quotas, and writes tpu_diagnostic_report.txt; it is published in the TPU Builders Program Getting Started Guide. Download it, read it, then run it:

curl -sSO https://gist.githubusercontent.com/RobMulla/ee1a530f9ff0bdb9aa5b493c7faf9aa2/raw/tpu_diagnostic.py
less tpu_diagnostic.py      # read it first: it runs gcloud commands as your account
python3 tpu_diagnostic.py

Check: the script writes tpu_diagnostic_report.txt. In the Cloud Console quotas page, GPUS_ALL_REGIONS is 8 or more.

2. Create the VM

A four-chip v6e VM with flex-start capacity:

gcloud compute instances create tpu-v6e-vm \
    --zone=us-east5-a \
    --machine-type=ct6e-standard-4t \
    --provisioning-model=FLEX_START \
    --request-valid-for-duration=2h \
    --max-run-duration=4h \
    --instance-termination-action=DELETE \
    --image-project=ubuntu-os-accelerator-images \
    --image-family=ubuntu-accel-2204-amd64-tpu-v5e-v5p-v6e \
    --maintenance-policy=TERMINATE \
    --metadata=startup-script="echo 'TPU VM Booted'"

Variants:

You want Change
v5p --machine-type=ct5p-hightpu-4t
Spot (cheaper, preemptible at any time) --provisioning-model=SPOT instead of FLEX_START
On-demand Drop --provisioning-model, --request-valid-for-duration, --max-run-duration and --instance-termination-action
A run longer than 24 hours --max-run-duration up to 168h; without it a flex-start VM terminates after 24 hours
More boot disk --boot-disk-size=100GB (the default is 10 GB)
Data that survives the VM A hyperdisk-balanced disk and a startup script, as in chapter 8 ("Keep data and setup off the VM")

For v5e, request a queued resource through the legacy Cloud TPU API:

gcloud alpha compute tpus queued-resources create tpu-v5e-request \
    --zone=us-west4-a \
    --accelerator-type=v5litepod-4 \
    --runtime-version=v2-alpha-tpuv5-lite \
    --node-id=tpu-v5e-node \
    --provisioning-model=flex-start \
    --max-run-duration=4h \
    --valid-until-duration=4h \
    --labels=purpose=flex-start

Check: gcloud compute instances describe tpu-v6e-vm --zone=us-east5-a shows the instance running, or gcloud alpha compute tpus queued-resources describe tpu-v5e-request --zone=us-west4-a shows ACTIVE. Any other state is not yet a VM you can log in to.

3. Connect and confirm the devices exist

gcloud compute ssh tpu-v6e-vm --zone=us-east5-a
ls /dev/vfio/

Check: /dev/vfio/ is not empty. An empty or missing directory means no TPU is attached, and no Python setting will fix it.

4. Install TorchTPU

Install in this order, Python first and then the package, with a pinned version and the PyTorch CPU index:

sudo apt update && sudo apt install -y python3.12 python3.12-venv
python3.12 -m venv env
source env/bin/activate
pip install torch_tpu==0.2.0 --extra-index-url https://download.pytorch.org/whl/cpu

Without --extra-index-url https://download.pytorch.org/whl/cpu, pip installs the CUDA build of torch, which TorchTPU does not use. There is no import torch_tpu step: import torch loads the backend and registers the tpu device.

Check: run the TorchTPU API reference's device query.

import torch

device = torch.device("tpu")
print(f"torch.accelerator.is_available(): {torch.accelerator.is_available()}")
print(f"torch.accelerator.device_count(): {torch.accelerator.device_count()}")
print(f"torch.accelerator.current_device_index(): {torch.accelerator.current_device_index()}")
print(f"torch.tpu.get_device_properties().name: {torch.tpu.get_device_properties().name}")

is_available() is True, and the device count equals chips times devices per chip: 4 on ct6e-standard-4t (one device per chip on v6e and v5p). The current index in a single process is 0.

5. Compute on the device

Run the VM guide's tensor example (TorchTPU's examples/simple_pytorch/simple_pytorch.py is the same code in one file), then its sum:

import torch

device = torch.device("tpu")
print(f"TPU Initialization complete. Primary device: {device}")

cpu_tensor = torch.ones((5, 5))
tpu_tensor = cpu_tensor.to(device)
direct_tpu_tensor = torch.randn((5, 5), device="tpu")
print(f"cpu_tensor is on: {cpu_tensor.device}")
print(f"tpu_tensor is on: {tpu_tensor.device}")
print(f"direct_tpu_tensor is on: {direct_tpu_tensor.device}")

result_on_cpu = (tpu_tensor + direct_tpu_tensor).cpu()
print(f"Result Checksum (Sum): {result_on_cpu.sum():.4f}")

Check: the example's README gives the expected placement lines:

TPU Initialization complete. Primary device: tpu:0
cpu_tensor is on: cpu
tpu_tensor is on: tpu:0
direct_tpu_tensor is on: tpu:0

The checksum is random (one operand is torch.randn) but must be a finite number. The .cpu() call is where a device error would surface.

6. Run the preflight script

Copy code/ch08_install/preflight.py onto the VM and run it in the activated environment:

python3 preflight.py --chips 4

Check: the last line ends with status=PASS, for example:

PREFLIGHT host=... python=3.12.3 torch=2.11.0+cpu torch_tpu=0.2.0 accelerator=tpu devices=4 name='TPU v6e' status=PASS

A cpu_build warning means torch came without the CPU index; reinstall before going further. Keep the JSON report (--json PATH) from the first passing run as the record for your TorchTPU version and machine type. On a laptop, python code/ch08_install/preflight.py --cpu-smoke shows what each check catches and ends cpu-smoke: OK, every fixture parsed and classified as expected.

7. Multi-host slices: repeat on every worker

A slice larger than one host is several VMs, each with its own Python. Request a 16-chip v6e slice as a queued resource; check the flags against the current queued-resources documentation before relying on them:

gcloud alpha compute tpus queued-resources create "${TPU_NAME}-qr" \
  --node-id="${TPU_NAME}" --zone="${ZONE}" \
  --accelerator-type=v6e-16 --runtime-version=v2-alpha-tpuv6e \
  --provisioning-model=flex-start --max-run-duration=168h --valid-until-duration=4h

Once it is ACTIVE, install on all workers, copy the preflight script to each, run it everywhere and compare the logs:

ssh-add ~/.ssh/google_compute_engine
gcloud compute tpus tpu-vm ssh "${TPU_NAME}" --zone="${ZONE}" --worker=all --command="
  sudo apt update && sudo apt install -y python3.12 python3.12-venv
  python3.12 -m venv ~/env && source ~/env/bin/activate
  pip install torch_tpu==0.2.0 --extra-index-url https://download.pytorch.org/whl/cpu
"
for w in 0 1 2 3; do
  gcloud compute tpus tpu-vm scp code/ch08_install/preflight.py "${TPU_NAME}":~ --zone="${ZONE}" --worker=$w
done
mkdir -p preflight-logs
gcloud compute tpus tpu-vm ssh "${TPU_NAME}" --zone="${ZONE}" --worker=all \
    --command="source ~/env/bin/activate && python3 preflight.py --chips 4 --launch-env" \
    --output-directory=preflight-logs
python code/ch08_install/preflight.py --aggregate preflight-logs --expect-hosts 4

gcloud compute tpus tpu-vm ssh reaches only worker 0 unless you pass --worker; --output-directory writes one <worker id>.log per worker into a directory that must already exist. The copy loop uses one worker at a time because fan-out is documented only together with --command.

Check: the aggregate step prints verdict: PASS. It fails if any worker failed or never ran the check, if workers disagree on the Python, torch or torch_tpu version, the device count or the chip name, or if the number of logs is not --expect-hosts. --launch-env also runs python3 -m torch.tpu.distributed and checks that WORLD_SIZE equals the number of slice builder addresses and that NNODES and NODE_RANK are consistent.

8. Clean up

A waiting or failed request still holds quota. Delete what you created:

gcloud alpha compute tpus queued-resources delete QR_NAME --zone=ZONE --force
gcloud compute instances delete VM_NAME --zone=ZONE --quiet

Troubleshooting

Symptom Cause Fix
Request stuck in WAITING_FOR_RESOURCES or PROVISIONING, or STOCKOUT / RESOURCE_POOL_EXHAUSTED GPUS_ALL_REGIONS is 0 on a new project or billing account Link paid billing, verify the billing account, request GPUS_ALL_REGIONS of 8 or 16, delete the stuck request and resubmit
Error: code 10, Failed to perform tenant project creation Reused legacy project Create a new project
VM deleted after exactly 24 hours Flex-start default run duration --max-run-duration (up to 168h) with --instance-termination-action=DELETE
Cannot stop or pause the VM Flex-start VMs cannot be stopped and restarted Delete it; keep data on a persistent disk and rebuild with a startup script
Disk full 10 GB default boot disk (GCE instances create; queued resources default to 100 GB) --boot-disk-size=100GB, or stream data from Cloud Storage
v5e request fails with "Code 13: Internal Error" Backend quota issue in the v5e alpha API Ask program support to allowlist the project
pip downloads a large CUDA torch Installed without the CPU index Reinstall with --extra-index-url https://download.pytorch.org/whl/cpu
No tpu device after install Wrong Python, wheel missing, or TORCH_DEVICE_BACKEND_AUTOLOAD=0 Activate the venv; unset the variable
torch.tpu.device_count() raises On PyTorch 2.11 and later these torch.tpu device APIs are internal Use torch.accelerator.device_count()
Fewer devices than expected Devices restricted or held by another process Check TPU_VISIBLE_DEVICES; make sure no other process owns the devices
Warning starting //TorchTpu/Performance/TcMalloc// glibc allocator in use; eager mode contends on it Preload tcmalloc with LD_PRELOAD (the TorchTPU Docker image already does)
A check passed on one worker only tpu-vm ssh defaults to --worker=0 --worker=all with --command; aggregate the per-worker logs
ValueError from set_tpu_launch_env() about TPU_WORKER_HOSTNAMES Multi-host launch without the worker list Run inside the slice's environment, or set the variables yourself

References