Use ML Diagnostics with TorchTPU
Integrating TorchTPU with Google Cloud ML Diagnostics lets you track workload runs, monitor hardware and model metrics, and capture profiles. TorchTPU is an open-source PyTorch backend for Cloud TPU that runs models in eager mode, compiles graphs, and scales distributed workloads across TPU slices.
This document shows machine learning engineers how to instrument distributed
TorchTPU training scripts with the ML Diagnostics SDK and deploy them. You can
collect TPU duty cycle, high-bandwidth memory (HBM), and model metrics, collect
programmatic and on-demand profiles, and inspect runs in the Google Cloud console.
If you deploy on GKE, ML Diagnostics automatically enables
workload monitoring for all
JobSet and Job workloads.
For more information, see View machine learning runs with ML Diagnostics, PyTorch on Cloud TPU, and PyTorch Distributed Overview.
How ML Diagnostics works with TorchTPU
TorchTPU uses a multiprocess architecture where the host runs one independent process, called a rank, for each TPU device attached to the host (see TorchTPU distributed support). To support this multiprocess model, the ML Diagnostics SDK coordinates run registration, metric logging, and profiling across all ranks.
When you instrument a TorchTPU workload, the rank 0 process registers the run with the ML Diagnostics control plane. Every rank initializes the ML Diagnostics SDK locally. During profiling, each rank writes its own CPU host and TPU device trace file, and the SDK synchronizes programmatic and on-demand captures across ranks.
Before you begin
Before you use ML Diagnostics with TorchTPU, complete the following prerequisites:
- Enable the Cluster Director API. For more information, see ML Diagnostics prerequisites.
- Enable Observability Analytics on your project's
_Defaultlog bucket so that model metric charts render. For instructions, see Enable Observability Analytics. - Create or identify a storage bucket to store captured XProf trace files.
- Confirm that your Google Cloud project has billing enabled and TPU quota for your target accelerator type.
Creating a Cloud TPU instance and storing logs and profiler traces incur Google Cloud charges. For more information, see ML Diagnostics pricing.
Required roles
To ensure that your workload service account has the necessary permissions to use ML Diagnostics with TorchTPU, ask your administrator to grant the following IAM roles to your workload service account on your project:
-
All:
- Cluster Director Editor (
roles/hypercomputecluster.editor) - Logs Writer (
roles/logging.logWriter) - Storage Object User (
roles/storage.objectUser)
- Cluster Director Editor (
For more information about granting roles, see Manage access to projects, folders, and organizations.
Your administrator might also be able to give your workload service account the required permissions through custom roles or other predefined roles.
For the specific permissions required to build a custom role, see IAM permissions.
Configure your TorchTPU training script
The ML Diagnostics SDK requires a standard PyTorch distributed launcher, such as
the torchrun CLI or
the torch.distributed.launcher
module, to spawn
one worker process per TPU device. The SDK reads the standard PyTorch
LOCAL_RANK and LOCAL_WORLD_SIZE environment variables that the launcher sets
on each worker process to coordinate profiling across ranks. For a basic example
of a distributed training script, see Basic use
case
in the PyTorch documentation. For more information about support for distributed
processing with TorchTPU, see TorchTPU distributed
support and
Get started with TorchTPU on
GKE.
To integrate the ML Diagnostics SDK into your worker function, complete the following stages:
- Initialize a machine learning run on every rank:
create an
MLRunresource and passframework=Framework.PYTORCHso that the SDK uses PyTorch APIs instead of JAX. - Capture profiles with the ML Diagnostics SDK: configure synchronized programmatic or on-demand profile capture across ranks.
Initialize a machine learning run on every rank
A machine learning run (MLRun) is
an ML Diagnostics resource that represents a single execution of your workload
and groups its configurations, metrics, and profiler traces. Initializing a
machine learning run registers your workload with the ML Diagnostics control
plane and prepares every worker process for metric logging and profile capture.
After the SDK registers the run, you can view it in the Google Cloud console.
In a distributed TorchTPU workload, only the rank 0 process creates the MLRun
resource on the control plane, while every rank initializes local run state and
profiling listeners. If you restrict initialization to rank 0, nonzero ranks
lack an active run context and profiling operations fail or stop responding at
collective barriers. Because the SDK defaults to JAX, you must specify PyTorch
so that the SDK discovers process ranks and TPU topologies through PyTorch
accelerator APIs.
In your worker function, before you call the machinelearning_run function,
initialize the TorchTPU distributed process group by calling
torch.distributed.init_process_group(backend="tpu_dist"). The SDK needs an
initialized process group to read each worker's rank and synchronize profiling
(see Example worker instrumentation and TorchTPU
distributed
support).
Configure the machinelearning_run call as follows:
- Initialize the run on every rank: Call the
machinelearning_runfunction unconditionally inside your worker function so that every rank runs it. - Specify the PyTorch framework: Import the
Frameworkenum from thegoogle_cloud_mldiagnostics.custom_types.mlrun_typesmodule and set theframeworkparameter to theFramework.PYTORCHenum value. - Set a shared workload ID: When you run on Compute Engine TPU VMs or
self-managed Kubernetes, set the
run_workload_idparameter or theRUN_WORKLOAD_IDenvironment variable. Use the same value across all ranks and hosts in a run, and use a unique value for each run. - Configure metric collection: Optional. To collect TPU system telemetry,
set the
log_system_metricsparameter toTrue. The SDK records telemetry every 10 seconds by default, or at the interval that you set with themetrics_record_interval_secparameter. To record model metrics such as training loss during your training loop, call themetrics.recordfunction.
Capture profiles with the ML Diagnostics SDK
Configuring profile capture with the SDK collects combined CPU host and TPU device execution traces from your TorchTPU ranks and uploads them to Cloud Storage for analysis in managed XProf.
With both programmatic and on-demand profiling, each TPU rank writes its own
trace file to the bucket path in the gcs_path parameter that you specify in
your machinelearning_run call. Each trace file uses the format
HOSTNAME_RANK.xplane.pb, where
HOSTNAME is the hostname. The
RANK value is the global worker rank index for
programmatic profiling or the host-local rank index (0 to LOCAL_WORLD_SIZE -
1) for multiprocess on-demand profiling.
Each trace file contains both that rank's CPU host trace (/host:CPU plane) and
its TPU device trace (/device:TPU:0 plane). TorchTPU configures host and TPU
device tracing through separate options (see Sanctioned configuration
options
in the TorchTPU documentation). The SDK automatically configures both options
and captures host and TPU device traces together in a single profile session.
You can configure programmatic profiling, live on-demand profiling, or both in the same workload.
Programmatic profiling
Programmatic profiling captures execution traces for targeted training steps or
code blocks defined in your script. When a programmatic profile starts and
stops, the ML Diagnostics SDK automatically runs the torch.distributed.barrier
function across all distributed PyTorch ranks. This collective barrier aligns
all worker processes on the same execution step and unifies multirank traces
into a single session in XProf.
To capture programmatic profiles, configure your worker function as follows:
- Instantiate the
xprofclass in your worker function. - Optional: To profile specific ranks instead of all ranks, pass a list of
rank indices to the
process_index_listparameter when you instantiate thexprofclass. - To capture traces around your target training steps, call the
prof.startandprof.stopmethods, use awith xprof():context manager block, or apply the@xprof()decorator.
For more information, see Programmatic profile capture.
On-demand profiling
On-demand profiling lets you trigger ad hoc profile captures from the Google Cloud console or the Google Cloud CLI while your workload is running, without modifying step ranges or restarting training. For on-demand profiling, ML Diagnostics supports selecting only the host, not individual ranks. As a result, triggering an on-demand capture collects profiles across all ranks on the selected host.
To enable live on-demand profiling, configure your machinelearning_run
function call as follows:
- Set the
on_demand_xprofparameter toTrue. - To store captured trace files, specify a Cloud Storage bucket path in
the
gcs_pathparameter.
Deploy your workload with ML Diagnostics
After you instrument your workload, install the ML Diagnostics packages in your TorchTPU runtime environment and deploy your workload on Google Kubernetes Engine (GKE) or Compute Engine:
Install the ML Diagnostics SDK and
xprofpackages alongsidetorch_tpuin your container image or Python virtual environment:pip install --no-cache-dir google-cloud-mldiagnostics xprofConfigure your compute environment for ML Diagnostics and deploy your TorchTPU workload:
- GKE: Complete the GKE setup for ML
Diagnostics. If you use on-demand
profiling, expose port
9999(containerPort: 9999) on your worker container for the on-demand XProf proxy. For TorchTPU container and KubernetesJobSetsetup, see Get started with TorchTPU on GKE. - Compute Engine: Complete the Compute Engine setup for ML Diagnostics. For TorchTPU installation and setup instructions on a TPU VM, see Get started with TorchTPU on a TPU VM.
- GKE: Complete the GKE setup for ML
Diagnostics. If you use on-demand
profiling, expose port
Verify that your machine learning run, TPU system telemetry, model metrics, and XProf traces appear in the Google Cloud console. For instructions, see View machine learning runs with ML Diagnostics.
Sample PyTorch TPU training scripts
The following examples show how to structure a distributed TorchTPU training script with the ML Diagnostics SDK. Use the first example as an integration template for an existing model codebase. Use the second example as a standalone, runnable script to test telemetry and profiling end to end.
Example worker instrumentation
The following template shows how to instrument a distributed TorchTPU worker
function with the ML Diagnostics SDK. Each rank initializes the tpu_dist
process group, registers the machine learning run with the Framework.PYTORCH
enum value, and runs all-rank and selective-rank programmatic xprof sessions.
Copy the machinelearning_run initialization and xprof profiling calls into
your existing worker function. Add your model initialization, data loading, and
training steps where the comments indicate. Launch this worker function with the
torchrun CLI or the
torch.distributed.launcher
module.
import os
import torch
import torch.distributed as dist
import torch.tpu
from google_cloud_mldiagnostics import machinelearning_run
from google_cloud_mldiagnostics import xprof
from google_cloud_mldiagnostics.custom_types.mlrun_types import Framework
def worker_main():
# 1. Initialize PyTorch Distributed with the TPU backend
dist.init_process_group(backend="tpu_dist")
device = torch.accelerator.current_accelerator()
# 2. Register the machine learning run on all ranks (don't guard with
# rank == 0)
machinelearning_run(
name=os.getenv("RUN_NAME", "my-run"),
run_group=os.getenv("RUN_GROUP", "my-run-group"),
project=os.getenv("PROJECT_ID", "PROJECT_ID"),
region=os.getenv("REGION", "us-central1"),
gcs_path=os.getenv(
"GCS_PATH", "gs://BUCKET_NAME/profiles"
),
on_demand_xprof=True,
log_system_metrics=True,
framework=Framework.PYTORCH,
# Required on Compute Engine TPU VMs and custom orchestrators
run_workload_id=os.getenv("RUN_WORKLOAD_ID"),
)
# 3. Programmatic profiling sessions (all ranks or specific ranks)
prof_all = xprof()
prof_subset = xprof(process_index_list=[0, 3, 7])
prof_all.start("all_ranks_session")
# Several lines of model training code are omitted here.
prof_all.stop()
prof_subset.start("subset_ranks_session")
# Several lines of model training code are omitted here.
prof_subset.stop()
dist.destroy_process_group()
Replace the following:
PROJECT_ID: your Google Cloud project IDBUCKET_NAME: the name of your Cloud Storage bucket for storing profiles
Complete PyTorch training script
The following standalone train.py script runs a complete 120-step synthetic
training loop on a two-layer PyTorch model wrapped with the
DistributedDataParallel class. During training, the script records loss values
every 10 steps with the metrics.record function and enables live on-demand
profiling. The script also captures an all-rank programmatic profile for steps
1-30 and a selective-rank profile for steps 61-90 on ranks 0, 3, and 7.
Use this script to validate your GKE or Compute Engine setup before instrumenting a production model. Verify that metrics and XProf traces appear in the Google Cloud console.
Save the script as train.py and set the PROJECT_ID, REGION, and GCS_PATH
environment variables (or replace the fallback placeholder values in the code).
When you run the script on a Compute Engine TPU VM or a custom
orchestrator, also set the RUN_WORKLOAD_ID environment variable to a unique
value for each run. This script assumes a two-host Cloud TPU slice with
eight TPU devices. On a single host with four TPU devices, set the
process_index_list parameter to indices from 0 to 3, such as [0, 2].
"""Distributed PyTorch TPU training script with ML Diagnostics profiling."""
import os
import time
import torch
import torch.distributed as dist
from torch.distributed import launcher
from torch.nn.parallel import DistributedDataParallel as DDP
import torch.tpu
import torch.tpu.distributed
from google_cloud_mldiagnostics import machinelearning_run
from google_cloud_mldiagnostics import metrics
from google_cloud_mldiagnostics import xprof
from google_cloud_mldiagnostics.custom_types.mlrun_types import Framework
class SimpleToyModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.fc1 = torch.nn.Linear(4096, 4096)
self.relu = torch.nn.ReLU()
self.fc2 = torch.nn.Linear(4096, 10)
def forward(self, x):
return self.fc2(self.relu(self.fc1(x)))
def worker_main():
# 1. Initialize PyTorch Distributed process group (c10d)
dist.init_process_group(backend="tpu_dist")
rank = dist.get_rank()
world_size = dist.get_world_size()
device = torch.accelerator.current_accelerator()
print(
f"[Rank {rank}/{world_size}] Initialized on device: {device}",
flush=True,
)
# 2. Register the machine learning run on all ranks (don't guard with
# rank == 0)
run_name = os.getenv("RUN_NAME", "my-run")
run_group = os.getenv("RUN_GROUP", "my-run-group")
project_id = os.getenv("PROJECT_ID", "PROJECT_ID")
region = os.getenv("REGION", "us-central1")
gcs_path = os.getenv(
"GCS_PATH", "gs://BUCKET_NAME/profiles"
)
machinelearning_run(
name=run_name,
run_group=run_group,
project=project_id,
region=region,
gcs_path=gcs_path,
on_demand_xprof=True,
log_system_metrics=True,
framework=Framework.PYTORCH,
# Required on Compute Engine TPU VMs and custom orchestrators
run_workload_id=os.getenv("RUN_WORKLOAD_ID"),
)
# 3. Build model and wrap with DDP
model = SimpleToyModel().to(device)
model = DDP(model)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
criterion = torch.nn.MSELoss()
# 4. Programmatic profiling sessions (all ranks and specific ranks)
prof_all = xprof()
prof_subset = xprof(process_index_list=[0, 3, 7])
prof_all.start("all_ranks_session")
print(f"[Rank {rank}] Running training loop...", flush=True)
for step in range(1, 121):
optimizer.zero_grad()
inputs = torch.randn(2048, 4096, device=device)
targets = torch.randn(2048, 10, device=device)
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
if step % 10 == 0:
loss_val = loss.item()
metrics.record("train_loss", loss_val, step=step)
if rank == 0:
print(f"[Step {step:03d}] Loss: {loss_val:.4f}", flush=True)
if step == 30:
prof_all.stop()
if rank == 0:
print(
"[Rank 0] All-ranks programmatic profiling completed.",
flush=True,
)
if step == 60:
time.sleep(2)
prof_subset.start("subset_ranks_session")
if rank == 0:
print(
"[Rank 0] Started selective-rank [0, 3, 7] programmatic profiling.",
flush=True,
)
if step == 90:
prof_subset.stop()
if rank == 0:
print(
"[Rank 0] Selective-rank [0, 3, 7] programmatic profiling"
" completed.",
flush=True,
)
print(f"[Rank {rank}] Training successfully finished!", flush=True)
dist.destroy_process_group()
def main():
# Multiprocess elastic launch coordination
if "LOCAL_RANK" in os.environ:
worker_main()
else:
# 1. Bootstrap TPU launch environment
torch.tpu.distributed.set_tpu_launch_env()
# 2. Derive configuration from environment and accelerator APIs
nnodes = int(os.getenv("NNODES", "1"))
master_addr = os.getenv("MASTER_ADDR", "localhost")
master_port = int(os.getenv("MASTER_PORT", "29500"))
nproc_per_node = torch.accelerator.device_count()
if nproc_per_node == 0:
raise RuntimeError("No TPU devices found on this node.")
rdzv_endpoint = (
"localhost:0" if nnodes == 1 else f"{master_addr}:{master_port}"
)
run_id = os.getenv("RUN_ID", "my-run")
config = launcher.LaunchConfig(
min_nodes=nnodes,
max_nodes=nnodes,
nproc_per_node=nproc_per_node,
run_id=run_id,
rdzv_backend="c10d",
rdzv_endpoint=rdzv_endpoint,
max_restarts=0,
)
launcher.elastic_launch(config, worker_main)()
if __name__ == "__main__":
main()
Replace the following:
PROJECT_ID: your Google Cloud project IDBUCKET_NAME: the name of your Cloud Storage bucket for storing profiles
What's next
- Learn how to view machine learning runs with ML Diagnostics.
- Learn how to analyze execution traces with managed XProf.
- Explore ML Diagnostics SDK configuration options.