Run TorchTitan on TPU¶
Use this guide when you want to train a large language model (or FLUX) on Cloud TPU with TorchTitan's TPU lane, torchtitan/experiments/tpu in Google's fork (https://github.com/google-pytorch/torchtitan): a first job on one TPU VM, then a shipped recipe on a multi-host GKE slice, with the flags, profile and MFU check that tell you the run is healthy. Chapter 14 explains the configuration model, the two trainers, SimpleFSDP, Graph Trainer and multi-slice HSDP; this page is the procedure.
Prerequisites¶
- A Google Cloud project with TPU access and quota (Install TorchTPU on a TPU VM, step 1).
- For steps 1 to 3: a
v6e-4TPU VM. For step 4 onward: Cluster Toolkit'sgclusterCLI, Docker, and an Artifact Registry repository. - Python 3.14 on the VM, as the TPU lane's README uses.
Steps¶
1. Create a TPU VM and connect¶
The TPU lane's README creates the VM through the Cloud TPU API:
export TPU_NAME=your-tpu-name
export PROJECT_ID=your-project
export ZONE=your-zone
export ACCELERATOR_TYPE=v6e-4
export VERSION=v2-alpha-tpuv6e
gcloud compute tpus tpu-vm create $TPU_NAME \
--project=$PROJECT_ID \
--zone=$ZONE \
--accelerator-type=$ACCELERATOR_TYPE \
--version=$VERSION
gcloud compute tpus tpu-vm ssh $TPU_NAME \
--zone=$ZONE \
--project=$PROJECT_ID
Add --spot for a Spot VM or --reserved to use a reservation. A Compute Engine VM created as in Install TorchTPU on a TPU VM works too.
Check: the SSH session opens and ls /dev/vfio/ is not empty.
2. Install TorchTitan and TorchTPU¶
python3.14 -m venv venv; source venv/bin/activate
git clone https://github.com/google-pytorch/torchtitan
cd torchtitan
pip install torch==2.15.0 torch_tpu==0.2.0 -r torchtitan/experiments/tpu/requirements.txt \
--extra-index-url https://download.pytorch.org/whl/test/cpu
pip install -r requirements.txt -r .ci/docker/requirements-flux.txt
The two pip install commands are separate because tokamax and tyro declare conflicting typeguard versions; pip warns and completes. PyTorch 2.15.0 is on the test index until its final release; after it, use --extra-index-url https://download.pytorch.org/whl/cpu.
Check: both installs complete (a typeguard conflict warning is expected).
3. Run the first job on one host¶
Qwen3 1.7B with FSDP on v6e-4, using the tokenizer and the c4_test sample data bundled with the repository, so no downloads or Hugging Face token are needed:
torchrun --nproc_per_node=4 -m torchtitan.experiments.tpu.train \
--module=torchtitan.experiments.tpu.qwen3 \
--config=qwen3_1_7b \
--training.steps=10
--nproc_per_node is the number of TPU devices on the host. --module names the recipe package and --config the function in its config_registry.py; any field can be overridden as --section.field=value. Add --debug.print-config to print the merged configuration, libtpu and XLA flags included.
Check: the job logs 10 training steps and exits cleanly. The first step is much slower than the rest: it compiles.
4. Build and push the training image¶
From the root of the torchtitan checkout:
docker build -t torchtitan-container:latest -f torchtitan/experiments/tpu/Dockerfile \
--build-arg TORCH_TPU_VERSION=0.2.0 \
--build-arg TORCH_VERSION=2.15.0 \
--build-arg TORCH_INDEX_URL=https://download.pytorch.org/whl/test/cpu .
gcloud auth configure-docker us-central1-docker.pkg.dev --quiet
gcloud artifacts repositories create ${REPOSITORY} \
--repository-format=docker \
--location=us-central1 \
--description="Docker repository for torchtitan training"
docker tag torchtitan-container:latest us-central1-docker.pkg.dev/${PROJECT_ID}/${REPOSITORY}/torchtitan-container:latest
docker push us-central1-docker.pkg.dev/${PROJECT_ID}/${REPOSITORY}/torchtitan-container:latest
Check: the end of the build log shows the installed versions, for example torch 2.15.0+cpu torch_tpu 0.2.0.
5. Create a GKE cluster with Cluster Toolkit¶
Set PROJECT_ID, REGION, ZONE, CLUSTER_NAME, COMPUTE_TYPE (for example ct6e-standard-4t), TOPOLOGY (for example 2x4 for a v6e-8 slice), AUTHORIZED_CIDR and BUCKET_NAME, then, from the Cluster Toolkit directory:
gcloud auth application-default login
gcluster deploy examples/gke-tpu-v6e/gke-tpu-v6e.yaml \
--vars project_id=${PROJECT_ID},deployment_name=${CLUSTER_NAME} \
--vars region=${REGION},zone=${ZONE} \
--vars machine_type=${COMPUTE_TYPE},tpu_topology=${TOPOLOGY},num_slices=1 \
--vars authorized_cidr=${AUTHORIZED_CIDR},enable_gcsfuse_csi=true
Type a to apply the Terraform plan. The blueprint creates the network, the cluster and one TPU slice, and installs Kueue and JobSet. It provisions on-demand TPUs; reservations, Spot and flex-start are consumption options in the blueprint's deployment file. Keep the ${CLUSTER_NAME} deployment directory: you need it to delete the cluster.
Check: gcluster deploy finishes after 10 to 20 minutes or more without errors.
6. Submit a recipe¶
The Llama 3 8B recipe for v6e-8 (two hosts of four chips), with WORKLOAD_IMAGE set to the image you pushed:
export WORKLOAD_NAME="llama3-8b-v6e8-$(date +%H%M%S)"
gcluster job submit \
--name "$WORKLOAD_NAME" --cluster "$CLUSTER_NAME" \
--compute-type ct6e-standard-4t --topology 2x4 --num-slices 1 \
--location "$ZONE" --project "$PROJECT_ID" --image "$WORKLOAD_IMAGE" \
--env="WORKERS_0_HOSTNAME=${WORKLOAD_NAME}-main-job-0-0.${WORKLOAD_NAME}" \
--env="WORKLOAD_NAME=$WORKLOAD_NAME" \
--command "torchrun \
--nnodes=2 --nproc_per_node=4 \
--rdzv_backend=static --rdzv_endpoint=\$WORKERS_0_HOSTNAME:29501 --node_rank=\$TPU_WORKER_ID \
-m torchtitan.experiments.tpu.train \
--module=torchtitan.experiments.tpu.llama3 --config=llama3_8b \
--hf_assets_path=tests/assets/tokenizer --dataloader.dataset_path=tests/assets/c4_test \
--training.steps=20 \
--training.num_tokens_per_microbatch_per_dp_rank=16384 \
--training.max_context_length=8192 \
--compile.enable \
--parallelism.use_simple_fsdp \
--splash_attention_kernel.use_splash_attention_kernel \
--splash_attention_kernel.sa_block_kv_compute=2048 \
--tpu_config.eager_mode=DEFER_AND_FUSE \
--libtpu-init-flags='xla_tpu_scoped_vmem_limit_kib=131072 tpu_program_stack_shrink_after_unload=false'"
Other recipes live under torchtitan/experiments/tpu/recipes/trillium/ (v6e) and recipes/ironwood/ (v7x), each with its command and expected metrics. For several slices, the multi-slice recipes add MEGASCALE_NUM_SLICES, --parallelism.data_parallel_replicate_degree=$MEGASCALE_NUM_SLICES and --parallelism.enable_min_cost_redistribute (chapter 14, "Several slices").
Check: the recipe README's expected metrics for this configuration are 5,383 tokens per second per chip and 33.96% MFU (43,068 tokens per second over 8 chips).
7. Profile and confirm the MFU¶
Add profiling to the training command:
--profiler.enable_profiling \
--profiler.profile_freq=5 \
--profiler.profiler_warmup=3 \
--profiler.profiler_active=1
Traces go under the dump folder's profile_trace for each process; open them with XProf or TensorBoard (Capture and read an XProf trace). The optimization guide's first number to read is the idle percentage. For one aggregate MFU measurement, set --tpu_config.enable_mfu_benchmark (it starts at --tpu_config.mfu_benchmark_start_step, default 5).
Check: recompute the MFU by hand with TorchTitan's convention: tokens per second per chip times FLOPs per token, over the chip's peak. For this recipe, \(5{,}383 \times 57.91 \times 10^{9} / 918 \times 10^{12} = 33.96\%\); python code/ch14_fsdp/fsdp_memory.py in this book reproduces it. Keep both numbers per chip or both per device: on v7x a chip is two devices.
8. Change flags one at a time¶
Flags live in the recipe config (libtpu_init_flags, xla_flags). On the command line, --extra-libtpu-init-flags and --extra-xla-flags add or override single flags, '!flag' drops one, and --libtpu-init-flags='' drops the recipe's whole set; an exported LIBTPU_INIT_ARGS or XLA_FLAGS has the last word.
--extra-libtpu-init-flags=xla_tpu_dvfs_p_state=5
--extra-libtpu-init-flags='!xla_tpu_enable_latency_hiding_layer_scheduler'
Check: after every flag change, compare the step-1 loss and gradient norm with the previous run. Bit-identical means the flag only changed scheduling; a small difference is a rounding-order change that needs a loss-curve comparison (Parity-check a port).
9. Clean up¶
gcluster job cancel ${WORKLOAD_NAME} \
--cluster ${CLUSTER_NAME} \
--location ${REGION} \
--project ${PROJECT_ID}
gcluster destroy ${CLUSTER_NAME}
Run gcluster destroy from the directory where you ran gcluster deploy.
Troubleshooting¶
| Symptom | Cause | Fix |
|---|---|---|
| Out of memory at step 1, peak at the all-gathers | No per-layer activation checkpointing, or ZeRO-3 on one unrolled Graph Trainer graph | Use a memory policy that recomputes; scan or the graph splitter for large models |
| Out of memory at the LM head with a large vocabulary | The [tokens, vocab] logits |
The fused Pallas cross-entropy; its token count must be a multiple of loss_b_block_size (1024) |
| Step time never settles | Recompiles: shapes that change | Fixed batch and sequence length; dynamic=False |
| Loss drifts from the reference over many steps | reduce_dtype=torch.bfloat16, or a flag that reorders reductions |
reduce_dtype=torch.float32; check step-1 loss and gradient norm after every flag change |
| Multi-slice job refuses to start, or trains slowly | data_parallel_replicate_degree left at 1 |
--parallelism.data_parallel_replicate_degree=$MEGASCALE_NUM_SLICES and --parallelism.enable_min_cost_redistribute |
| Host memory exhausted on a v7x multi-slice job with offload | MegaScale's pinned pool per process | --megascale_grpc_premap_memory_bytes=4294967296 --megascale_use_numa_aware_block_allocator=false in LIBTPU_INIT_ARGS |
| Segfault when Graph Trainer compiles, libtpu 0.0.48+ | Shardy HLO sharding v3 | xla_enable_hlo_sharding_v3=False |
| Optimizer checkpoint fails to load | compile.use_scan_layers flipped since it was saved |
Resume with the same structure |
| Device fails to initialize after a crash | Stale libtpu lock | rm -f /tmp/libtpu_lockfile |
| Throughput far below the recipe's figure | Eager run, a fastbuild TorchTPU wheel, or compile steps in the timed window | Compile; build wheels with -c opt; exclude warm-up steps (Benchmark a training run) |
| Flags from the recipe ignored | An exported LIBTPU_INIT_ARGS overrides them |
Unset it, or check --debug.print-config |
References¶
- TorchTitan TPU experiments: README
- TorchTitan TPU experiments: Recipe for training Llama3-8B model on 8 TPU trillium cluster (v6e-8)
- TorchTitan TPU experiments: Guide to optimizing LLMs on TorchTPU
- TorchTitan TPU experiments: tpu_job_config.py
- Integrating TorchTPU into TorchTitan and Optimizing Models for TPU
- TorchTitan with TorchTPU (google-pytorch/torchtitan)
- Google Cloud: Cluster Toolkit overview
- Companion code: code/ch14_fsdp/
- Chapter 14: FSDP and TorchTitan on TPU