Get started with the ML Diagnostics SDK
The ML Diagnostics Python SDK can be integrated with ML workloads to monitor workloads, collect and manage model metrics, configs, and profiles on Google Cloud. Use the SDK for programmatic profiling and to view model metrics. Model metrics are not available if you use on-demand profiling without the SDK.
This guide shows you how to create machine learning runs, monitor workloads, collect and manage workload metrics and configs, deploy managed XProf resources, and enable programmatic and on-demand profile capture.
In order to have workload monitoring, metrics and config collection, and enable profiling, use an SDK version at least as recent as 1.0.6.
For more information on using the ML Diagnostics SDK, see the google-cloud-mldiagnostics repository.
Install ML Diagnostics SDK
Install the google-cloud-mldiagnostics
library:
pip install google-cloud-mldiagnostics
Import the following packages in your ML workload code:
from google_cloud_mldiagnostics import machinelearning_run
from google_cloud_mldiagnostics import metrics
from google_cloud_mldiagnostics import xprof
Enable Cloud Logging
The SDK uses the standard Python logging module to output metrics and config
information. To route these logs to Cloud Logging, install and configure the
google-cloud-logging library. This lets you view SDK logs, logged metrics, and
your own application logs within the Google Cloud console.
Install the google-cloud-logging library:
pip install google-cloud-logging
Configure logging in your script by attaching the Cloud Logging handler to the Python root logger. Add the following lines to the beginning of your Python script:
import logging
import google.cloud.logging
# Instantiate a Cloud Logging client
logging_client = google.cloud.logging.Client()
# Attach the Cloud Logging handler to the Python root logger
logging_client.setup_logging()
# Standard logging calls will go to Cloud Logging
logging.info("SDK logs and application logs will appear in Cloud Logging.")
Enable debug logging
By default, the logging level is set to INFO. To receive more detailed logs
from the SDK, such as machine learning run details, set the logging level to
DEBUG after calling setup_logging():
import logging
import google.cloud.logging
logging_client = google.cloud.logging.Client()
logging_client.setup_logging()
logging.getLogger().setLevel(logging.DEBUG) # Enable DEBUG level logs
logging.debug("This is a debug message.")
logging.info("This is an info message.")
With DEBUG enabled, you receive additional SDK diagnostics in
Cloud Logging. For example:
DEBUG:google_cloud_mldiagnostics.core.global_manager:current run details:
{'name': 'projects/my-gcp-project/locations/us-central1/mlRuns/my-run-12345',
'gcs_path': 'gs://my-bucket/profiles', ...}
Configure OpenTelemetry integration
OpenTelemetry (OTel) is an open-source observability framework for collecting, processing, and exporting telemetry data such as metrics and logs. The ML Diagnostics SDK supports pluggable telemetry and dual routing. In addition to sending telemetry to Cloud Logging, you can configure the SDK to export metrics and logs to an OpenTelemetry collector. Exporting telemetry to an OpenTelemetry collector lets you integrate with local monitoring stacks such as Prometheus, Loki, and Grafana.
Prerequisites
Before you configure OpenTelemetry integration, complete the following tasks:
Install the
opentelemetry-sdkandopentelemetry-exporter-otlppackages, or install thegoogle_cloud_mldiagnosticspackage with theotelextra:pip install google_cloud_mldiagnostics[otel]Run an OpenTelemetry collector that is accessible from your workload.
Optional: Set up Prometheus, Loki, and Grafana to consume data from your OpenTelemetry collector.
Configure exporters in the SDK
Configuring exporters in the SDK lets you control where your workload sends system and user-defined metrics, such as routing telemetry to Cloud Logging, an OpenTelemetry collector, or both destinations at the same time.
To configure where the SDK exports metrics, set the metrics_exporter_config
parameter in the machinelearning_run function with the following fields:
mode: specifies the exporters for system metrics. Valid values include"otel"and"cloud_logging".userConfig: specifies the exporters for user-defined metrics. Valid values include"otel"and"cloud_logging".
If you omit the metrics_exporter_config parameter, the SDK only exports
metrics to Cloud Logging.
The following example configures the machinelearning_run function to export
both system and user metrics to OpenTelemetry and Cloud Logging:
machinelearning_run(
# ... other parameters ...
metrics_exporter_config={
# Export system metrics to both OTel and Cloud Logging
"mode": ["otel", "cloud_logging"],
# Export user metrics to both OTel and Cloud Logging
"userConfig": ["otel", "cloud_logging"],
},
)
If you use the Google Cloud exporter in your OpenTelemetry collector,
configure the default_log_name setting in the collector configuration. The
Google Cloud exporter requires a log name; if the SDK doesn't provide the
gcp.log_name attribute, the collector drops logs unless the default_log_name
setting is configured. For more information, see the OpenTelemetry
Google Cloud Exporter
documentation.
Environment variables
You can set environment variables in your shell, container image, or Kubernetes workload manifest to configure the collector endpoint, export interval, TLS settings, and logging verbosity without modifying your Python workload code.
You can set the following environment variables:
DIAGON_ENABLE_OTEL: enables the OpenTelemetry exporter when set to the'true'value.OTEL_EXPORTER_OTLP_ENDPOINT: specifies the endpoint of the OpenTelemetry collector, such as thehttp://otel-collector.diagon.svc.cluster.local:4317endpoint.OTEL_METRIC_EXPORT_INTERVAL: specifies the metric export interval in milliseconds. Default:5000.OTEL_PYTHON_LOG_LEVEL: specifies the log level for the OpenTelemetry Python SDK, such as theDEBUGlevel.OTEL_EXPORTER_OTLP_INSECURE: disables TLS for the OTLP exporter when set to the'true'value.
For example, you can set the OTLP collector endpoint and export interval in your shell environment before running your workload script:
export DIAGON_ENABLE_OTEL='true'
export OTEL_EXPORTER_OTLP_ENDPOINT="http://otel-collector.diagon.svc.cluster.local:4317"
export OTEL_METRIC_EXPORT_INTERVAL=5000
export OTEL_PYTHON_LOG_LEVEL=DEBUG
export OTEL_EXPORTER_OTLP_INSECURE='true'
Create a machine learning run
To use the ML Diagnostics platform, you need to first create a machine learning run. This involves instrumenting your ML workload with the SDK to perform logging, collect metrics, and enable profile tracing.
The following is a basic example that initializes Cloud Logging, creates a
machine learning run (MLRun), records metrics, and captures a profile:
import logging
import os
import google.cloud.logging
from google_cloud_mldiagnostics import machinelearning_run, metrics, xprof, metric_types
# 1. Set up Cloud Logging
# Make sure to pip install google-cloud-logging
logging_client = google.cloud.logging.Client()
logging_client.setup_logging()
# Optional: Set logging level to DEBUG for more detailed SDK logs
logging.getLogger().setLevel(logging.DEBUG)
# 2. Define and start machinelearning run
try:
run = machinelearning_run(
name="<run_name>",
run_group="<run_group>",
configs={ "epochs": 100, "batch_size": 32 },
project="<some_project>",
region="<some_zone>",
gcs_path="gs://<some_bucket>",
on_demand_xprof=True,
framework=FRAMEWORK,
)
logging.info(f"MLRun created: {run.name}")
# 3. Collect metrics during your run
metrics.record(metric_types.MetricType.LOSS, 0.123, step=1)
logging.info("Loss metric recorded.")
# 4. Capture profiles programmatically
with xprof():
# ... your code to profile here ...
pass
logging.info("Profile captured.")
except Exception as e:
logging.error(f"Error during MLRun: {e}", exc_info=True)
The code example uses the following variables:
| Variable | Requirement | Description |
|---|---|---|
name |
Required | An identifier for the specific run. The SDK automatically creates a
machine-learning-run-id to ensure that run
names are unique. |
run_group |
Optional | An identifier that can help group multiple runs belonging to the same experiment. For example, all runs associated with a TPU slice size sweep could belong to the same group. |
project |
Optional | If not specified, the project is extracted from Google Cloud CLI. |
region |
Required | All Cluster Director locations
are supported except us-east5. This flag can be set by an
argument for each command, or with the command:
gcloud config set compute/region. |
configs |
Optional | Key-value pairs containing configuration parameters for the run. If configs are not defined, default software and system configs appear but the ML workload configs do not. |
gcs_path |
Conditionally Required | The Google Cloud Storage location where all profiles are saved.
For example: gs://my-bucket or gs://my-bucket/folder1.
Required only if the SDK is used for profile capture. |
on-demand-xprof |
Optional | Starts xprofz daemon on port 9999 to enable on-demand
profiling. You can enable both on-demand profiling and programmatic profiling
in the same code, as long as they don't occur at the same time. |
framework |
Optional | Default: JAX. For TorchTPU, use Framework.PYTORCH. |
The following configs are automatically collected by the SDK and don't need to
be specified within machinelearning_run:
- Software configs: Framework, framework version, XLA flags.
- System configs: Device type, number of slices, slice size, number of hosts.
Project and region information is stored as machine learning run metadata. The region used for the machine learning run does not have to match the region used for the workload run.
Write configs
Many workloads contain too many configs to define directly in the
machinelearning_run definition. In these cases, you can write configs to your
run using JSON or YAML.
import yaml
import json
# Read the YAML file
with open('config.yaml', 'r') as yaml_file:
# Parse YAML into a Python dictionary
yaml_data = yaml.safe_load(yaml_file)
# Define machinelearning run
machinelearning_run(
name="RUN_NAME",
run_group="GROUP_NAME",
configs=yaml_data,
project="PROJECT_NAME",
region="ZONE",
gcs_path="gs://BUCKET_NAME",
)
Collect metrics
You can collect model metrics, model performance metrics, and system metrics with the SDK. You can create visualizations of these metrics as average values and with time series charts.
The SDK provides two functions for recording metrics: metrics.record() for
capturing individual data points, and metrics.record_metrics() for recording
multiple metrics in a single batch. Both functions write metrics to
Cloud Logging, enabling visualization and analysis.
To record a single metric:
# Record a metric only with time as the x-axis
metrics.record(metric_types.MetricType.LOSS, 0.123)
# Record a metric with time and step as the x-axis
metrics.record(metric_types.MetricType.LOSS, 0.123, step=1)
To record multiple metrics:
from google_cloud_mldiagnostics import metric_types
# User codes
# machinelearning_run should be called
# ......
for step in range(num_steps):
if (step + 1) % 10 == 0:
metrics.record_metrics([
# Model quality metrics
{"metric_name": metric_types.MetricType.LEARNING_RATE, "value": step_size},
{"metric_name": metric_types.MetricType.LOSS, "value": loss},
{"metric_name": metric_types.MetricType.GRADIENT_NORM, "value": gradient},
{"metric_name": metric_types.MetricType.TOTAL_WEIGHTS, "value": total_weights},
# Model performance metrics
{"metric_name": metric_types.MetricType.STEP_TIME, "value": step_time},
{"metric_name": metric_types.MetricType.THROUGHPUT, "value": throughput},
{"metric_name": metric_types.MetricType.LATENCY, "value": latency},
{"metric_name": metric_types.MetricType.TFLOPS, "value": tflops},
{"metric_name": metric_types.MetricType.MFU, "value": mfu},
], step=step+1)
The following system metrics are automatically collected by the SDK from libTPU,
psutil, and JAX libraries:
- TPU TensorCore utilization
- TPU duty cycle
- HBM utilization
- Host CPU utilization
- Host memory utilization
You don't need to manually specify these metrics. These system metrics have time as the default x-axis.
The following predefined metric keys will automatically appear in the Google Cloud console if assigned. These metrics aren't calculated automatically; they are predefined keys that you can assign values to.
- Model quality metric keys:
LEARNING_RATE,LOSS,GRADIENT_NORM,TOTAL_WEIGHTS. - Model performance metric keys:
STEP_TIME,THROUGHPUT,LATENCY,MFU,TFLOPS.
The predefined metrics, as well as other user-defined metrics can be recorded
with x-axis as time, or both time and step. You can record any custom
metric in the workload.
The following example captures a single metric for the workload, which you can view in the Model Metrics tab for the specific machine learning run:
metrics.record("custom_metrics_1", step_size, step=step + 1)
To record multiple metrics in one call, use the record_metrics method. For
example:
metrics.record_metrics([
# Model quality metrics
{"metric_name": metric_types.MetricType.LEARNING_RATE, "value": step_size},
{"metric_name": metric_types.MetricType.LOSS, "value": loss},
{"metric_name": metric_types.MetricType.GRADIENT_NORM, "value": gradient},
{"metric_name": metric_types.MetricType.TOTAL_WEIGHTS, "value": total_weights},
# Model performance metrics
{"metric_name": metric_types.MetricType.STEP_TIME, "value": step_time},
{"metric_name": metric_types.MetricType.THROUGHPUT, "value": throughput},
{"metric_name": metric_types.MetricType.LATENCY, "value": latency},
{"metric_name": metric_types.MetricType.TFLOPS, "value": tflops},
{"metric_name": metric_types.MetricType.MFU, "value": mfu},
# Custom metrics
{"custom_metrics_1", "value":<value>},
{"custom_metrics_2", "value":<value>},
{"avg_mtp_acceptance_rate_percent", "value":<value>},
{"dpo_reward_accuracy", "value":<value>},
], step=step+1)
System metrics
You can automatically collect system metrics at either the default 1-minute interval or a more fine-grained interval.
Default interval
Collect system metrics automatically with 1-minute intervals from
Cloud Monitoring by setting log_system_metrics=false. See Monitor
workloads for details on
system metrics that are automatically collected with this default.
The following is an example of how to receive default system metrics from Cloud Monitoring:
machinelearning_run(
name="my-run-123",
run_group="my-group",
project="gcp-project",
region="us-central1",
gcs_path="gs://my_bucket_path",
on_demand_xprof=True,
log_system_metrics=False
)
Fine-grained interval
Collect system metrics automatically with fine-grained intervals (10 seconds) by
setting log_system_metrics=true. With this option, the following system
metrics are automatically collected by the SDK from libTPU, psutil, and JAX
libraries:
- TPU TensorCore utilization
- TPU duty cycle
- HBM utilization
- Host CPU utilization
- Host memory utilization
The following is an example of how to collect fine-grain system metrics:
machinelearning_run(
name="my-run-123",
run_group="my-group",
project="gcp-project",
region="us-central1",
gcs_path="gs://my_bucket_path",
on_demand_xprof=True,
log_system_metrics=True
)
These system metrics have time as the default x-axis.
Capture profiles
You can capture XProf profiles of your ML workload in the following ways:
- Programmatic capture: Embeds profiling commands directly into your machine learning code, explicitly specifying when to start and stop recording data.
- On-demand capture: Occurs in real time when you trigger the profiler while the workload is actively running. Triggering an on-demand capture records a profile in the future over a time period that you define.
- Continuous profiling in snapshot mode (Preview): When enabled, continuously captures a 2 GB profile in a circular buffer on your TPU host. When a snapshot is triggered, the latest 2 GB profile in the buffer is saved as a profile session in the Cloud Storage bucket. Capturing profiles using continuous profiling snapshots records activity leading up to the trigger, letting you debug issues with your workload at the time of a workload event.
- Automatic profile capture from workload monitoring (Preview): When a
workload monitoring
performance degradation analyzer reports a
"bad"state, ML Diagnostics can automatically capture a profile at the time of the event instead of waiting for you to view the analyzer result and manually trigger an on-demand profile capture. This lets you accurately diagnose the cause of the event based on a profile captured when the event occurred.
The SDK commands to capture profiles are framework-agnostic since all framework-level profiling commands are automatically integrated into ML Diagnostics profiling commands. This means that your profiling code is not dependent on the framework you use.
Programmatic profile capture
Programmatic capture requires you to annotate your model code and specify where you want to capture profiles. Typically, you capture a profile for a few training steps, or profile a specific block of code within your model.
You can perform programmatic profile capture with the ML Diagnostics SDK in the following ways:
- API-based collection: Control profiling with
start()andstop()methods. - Decorator-based collection: Annotate functions with
@xprof(run)for automatic profiling. - Context manager: Use with
xprof()for scope-based profiling that automatically handlesstart()andstop()operations.
You can use the same profile capture code across all frameworks. All the profile sessions are captured in the Cloud Storage bucket defined in the machine learning run.
# Support collection via APIs
prof = xprof() # Updates metadata and starts xprofz collector
prof.start() # Collects traces to bucket
# ..... Your code execution here
# ....
prof.stop()
# Also supports collection via decorators
@xprof()
def abc(self):
# does something
pass
# Use xprof as a context manager to automatically start and stop collection
with xprof() as prof:
# Your training or execution code here
train_model()
evaluate_model()
Multi-host (process) profiling
During programmatic profiling, the SDK starts profiling on each process where
your ML workload code is running. If you don't specify a list of process
indices using the process_index_list parameter, the SDK starts profiling on
all processes. For JAX, a process corresponds to a TPU host. For TorchTPU, a
process corresponds to a distributed rank (an individual TPU chip).
# starts profiling on all nodes
prof = xprof()
prof.start()
# ...
prof.stop()
By default, calling the prof.start() method without the session_id argument
on multiple hosts results in separate trace sessions - one for each host. To
group traces from different hosts into a single, unified multi-host session in
XProf, ensure that the prof.start() method is called with the same
session_id argument on all participating hosts. For example:
# Use the same session_id on all hosts to group traces
prof = xprof()
prof.start(session_id="profiling_session")
# ...
prof.stop()
To enable profiling for specific hosts:
# starts profiling on node with index 0 and 2
prof = xprof(process_index_list=[0,2])
prof.start()
# ...
prof.stop()
On-demand profile capture
Use on-demand profile capture when you want to capture profiles in an ad hoc manner, or when programmatic profile capture is not already enabled. On-demand capture is helpful when there are problems with model performance during the run, and you want to capture profiles in those moments to diagnose the issues.
To enable on-demand profile capture, configure the run with on-demand support:
# Define machinelearning run
machinelearning_run(
name="<run_name>",
# specify where profiling data is stored
gcs_path="gs://<bucket>",
...
# enable on demand profiling, starts xprofz daemon on port 9999
on_demand_xprof=True
)
You can use the same profile capture code across all frameworks. All profile sessions are captured in the Cloud Storage bucket defined in the machine learning run.
For on-demand profiling on GKE, deploy GKE
connection-operator and injection-webhook into the GKE cluster. This
ensures that your machine learning run can locate the GKE nodes
it is running on, and the on-demand capture drop-down can autopopulate those
nodes. For more information, see Configure
GKE cluster.
Package workload for GKE
You can use a Dockerfile to package an application that uses the ML Diagnostics
SDK. Install the google-cloud-logging package for Cloud Logging
integration. For example:
# Base image (user's choice, e.g., python:3.10-slim, or a base with ML frameworks)
FROM python:3.11-slim
# Install base utilities
RUN pip install --no-cache-dir --upgrade pip
# Install SDK and Logging client
# psutil is installed as a dependency of google-cloud-mldiagnostics
RUN pip install --no-cache-dir \
google-cloud-mldiagnostics \
google-cloud-logging
# Optional: For JAX/TPU workloads
# RUN pip install --no-cache-dir "jax[tpu]" -f https://storage.googleapis.com/jax-releases/libtpu_releases.html &&
# pip install --no-cache-dir libtpu xprof
# Add your application code
COPY ./app /app
WORKDIR /app
# Run your script
CMD ["python", "your_train_script.py"]
Package workload for Slurm
On Cluster Director-managed Slurm and self-managed Slurm clusters that use
Pyxis and Enroot, you can package an ML Diagnostics SDK workload as a container
image. After you push the image to Artifact Registry, you can run it using the srun
command with the --container-image flag.
Before you begin, deploy the Diagon daemon on your compute nodes by using a Slurm Task Prolog script. On Slurm clusters, ML Diagnostics supports SDK metrics, programmatic profiling, on-demand profiling, and continuous profiling. Workload monitoring isn't supported on Slurm.
For more information, see Configure Slurm for ML Diagnostics.
Configure your workload script for Slurm
Before you build your container image, configure your Python workload script for Slurm:
- Multi-host JAX initialization: Call the
jax.distributed.initializefunction before calling themachinelearning_runfunction. Run one process per host so that JAX discovers the other hosts from the Slurm environment. - Run initialization on every host: Call the
machinelearning_runfunction in every process. Don't restrict this call to rank 0. - Unique run name: Include the
SLURM_JOB_IDenvironment variable in thenameparameter so that you can identify each Slurm job. For example, set thenameparameter tof"my-slurm-run-{os.environ.get('SLURM_JOB_ID', 'local')}". - On-demand profiling and system metrics: Set the
on_demand_xprofandlog_system_metricsparameters toTruein themachinelearning_runfunction.
The following example initializes distributed JAX execution, creates a machine learning run, captures a programmatic profile, and records a loss metric:
import os
import jax
from google_cloud_mldiagnostics import (
machinelearning_run,
metric_types,
metrics,
xprof,
)
jax.distributed.initialize()
machinelearning_run(
name=f"my-slurm-run-{os.environ.get('SLURM_JOB_ID', 'local')}",
run_group="my-slurm-run-group",
configs={"model": "mlp", "batch_size": 8192},
project="PROJECT_ID",
region="REGION",
gcs_path="gs://BUCKET_NAME/FOLDER_PATH",
on_demand_xprof=True,
log_system_metrics=True,
)
prof = xprof()
# Capture a programmatic profile of the initial training steps
prof.start(session_id="programmatic-session")
# Run your training steps here
prof.stop()
metrics.record(metric_types.MetricType.LOSS, float(loss), step=step)
Replace the following:
PROJECT_ID: your Google Cloud project IDREGION: the region for your machine learning run metadata, such asus-central1BUCKET_NAME: the name of the Cloud Storage bucket where profiles are savedFOLDER_PATH: the folder path in your Cloud Storage bucket
Build and push the container image
To package your workload and push the container image to Artifact Registry, complete the following steps:
Create a
Dockerfilethat packages your JAX TPU workload with the ML Diagnostics SDK, XProf, and the Cloud Logging client library:# Base image, such as python:3.11-slim or an image with ML frameworks FROM python:3.11-slim # Install base utilities RUN pip install --no-cache-dir --upgrade pip # Install JAX for TPU, libtpu, and XProf RUN pip install --no-cache-dir "jax[tpu]" \ -f https://storage.googleapis.com/jax-releases/libtpu_releases.html && \ pip install --no-cache-dir libtpu xprof # Install the SDK and Cloud Logging client # psutil is installed as a dependency of google-cloud-mldiagnostics RUN pip install --no-cache-dir \ google-cloud-mldiagnostics \ google-cloud-logging # Add your application code COPY ./app /app WORKDIR /app # Run your workload script CMD ["python3", "-u", "train_with_sdk.py"]Build the container image and push it to Artifact Registry:
docker build \ -t LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE_NAME:IMAGE_TAG . docker push \ LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE_NAME:IMAGE_TAGReplace the following:
LOCATION: the regional or multi-regional location of your Artifact Registry repository, such asus-central1PROJECT_ID: your Google Cloud project IDREPOSITORY: the name of your Artifact Registry Docker repositoryIMAGE_NAME: the name of your container imageIMAGE_TAG: the tag for your container image, such asv1
Deploy workload
After you integrate the SDK with your workload, deploy and run the workload on GKE, Slurm, or Compute Engine.
Deploy on GKE
After you package your workload in an image, create your
YAML file with the specified image. For programmatic profiling, label the
workload in the YAML file with managed-mldiagnostics-gke=true. On-demand
profiling doesn't require this label.
To deploy the workload on GKE, complete the following steps:
Deploy the workload:
kubectl apply -f YAML_FILE_NAMEReplace
YAML_FILE_NAMEwith the name of your YAML file.Find your job name in your workload namespace:
kubectl get job -n NAMESPACEReplace
NAMESPACEwith your workload namespace.Find the run name and link in your
kubectllogs by passing the job name, namespace, and workload container. You must specify the workload container because the ML Diagnostics sidecar handles its own logging:kubectl logs jobs/JOB_NAME \ -n NAMESPACE \ -c CONTAINER_NAMEReplace the following:
JOB_NAME: the name of your job, such ass5-tpu-slice-0CONTAINER_NAME: the name of your workload container, such asworkload
Deploy on Slurm
After you package and push your container image for Slurm, complete the following steps:
Create a batch script named
run_multihost.sbatchthat pulls the container image and runs one task per host. The following example runs a multi-host JAX workload on one TPU v5p 2x2x2 slice with two hosts and four chips per host on Cluster Director-managed Slurm:#!/bin/bash #SBATCH --job-name=mldiag-jax-multihost #SBATCH --partition=tpu #SBATCH --layout=v5p=2x2x2 #SBATCH --ntasks-per-node=1 #SBATCH --output=logs/%x_%j.log # # --layout sets the node count (2 for v5p 2x2x2); don't also pass -N. IMAGE="LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE_NAME:IMAGE_TAG" # Optional: confirm that the Diagon daemon (installed by the Slurm prolog) # is running on every node. srun --ntasks-per-node=1 bash -c \ 'echo "=== $(hostname): diagon-daemon.service is $( systemctl is-active diagon-daemon.service)"' # Configure Enroot credentials for Artifact Registry using the node service # account token. export ENROOT_CONFIG_PATH="${HOME}/.enroot_config" mkdir -p "${ENROOT_CONFIG_PATH}" ACCESS_TOKEN=$(curl -s -H "Metadata-Flavor: Google" \ "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" \ | sed -n 's/.*"access_token":"\([^"]*\)".*/\1/p') printf "machine LOCATION-docker.pkg.dev login oauth2accesstoken password %s\n" \ "${ACCESS_TOKEN}" > "${ENROOT_CONFIG_PATH}/.credentials" chmod 600 "${ENROOT_CONFIG_PATH}/.credentials" # Run one process per host. srun copies the batch environment (including # HOSTNAME from the first node) to every task, and the SDK reads $HOSTNAME, # so reset it to each node's own hostname. srun --ntasks-per-node=1 --container-image="docker://${IMAGE}" \ bash -c 'export HOSTNAME=$(cat /proc/sys/kernel/hostname) exec python3 -u /app/train_with_sdk.py'Replace the following:
LOCATION: the regional or multi-regional location of your Artifact Registry repository, such asus-central1PROJECT_ID: your Google Cloud project IDREPOSITORY: the name of your Artifact Registry Docker repositoryIMAGE_NAME: the name of your container imageIMAGE_TAG: the tag for your container image, such asv1
Reset the
HOSTNAMEenvironment variable inside each task as shown in the example. Otherwise, every task reports the first node's hostname to the SDK, and the run can't be associated with all of its nodes.The
--layoutflag is specific to TPU partitions on Cluster Director-managed Slurm. On other Slurm clusters, request nodes by using the-Nor--nodesflag with--ntasks-per-node=1. The--container-imageflag requires Pyxis and Enroot.From the Slurm login node, create the
logsdirectory and submit the job:mkdir -p logs sbatch run_multihost.sbatchCheck the job status:
squeue -u $USERAfter the job starts, view the job output file to find the run name and the link to the run in the Google Cloud console:
tail -f logs/mldiag-jax-multihost_JOB_ID.logReplace
JOB_IDwith the job ID returned by thesbatchcommand.
Deploy on Compute Engine
Connect to the VM by using SSH and run the Python code for your workload:
source venv/bin/activate
python3.11 WORKLOAD_FILE_NAME
Replace WORKLOAD_FILE_NAME with the filename of your
Python workload script.