Use ML Diagnostics for reinforcement learning

Google Cloud ML Diagnostics lets you monitor and profile reinforcement learning (RL) post-training workloads on Cloud TPU. RL post-training refines a pretrained model by generating candidate responses, scoring them with reward functions, and updating model weights to improve reasoning and alignment. The RL post-training stack uses MaxText, Tunix, and Pathways to run this loop across TPU slices. ML Diagnostics integrates with this stack to register runs, stream RL metrics, and capture per-role managed XProf traces.

This document shows you how to configure per-role XProf profiling in MaxText and build a post-training container image. You also learn how to submit an RL workload on Google Kubernetes Engine (GKE) with Pathways and inspect metrics and traces in the Google Cloud console.

RL post-training stack and capabilities

Unlike supervised fine-tuning, which trains on static target examples, RL post-training improves a model through an iterative loop of online response generation and policy optimization. In each iteration, the stack generates candidate completions for prompts on a sampler mesh, scores those completions with reward functions, and updates policy weights on a trainer mesh. Disaggregating inference generation and policy training across dedicated Cloud TPU meshes lets each workload phase scale independently while synchronizing updated model weights across hosts.

To orchestrate this workflow, the RL post-training stack coordinates three components:

  • MaxText: Provides model definitions, the src/maxtext/configs/post_train/rl.yml post-training configuration file, and the maxtext.trainers.post_train.rl.train_rl training entry point.
  • Tunix: Runs the RL post-training loop, such as Group Relative Policy Optimization (GRPO) and Token-level Group Sequence Policy Optimization (GSPO-Token), coordinating policy updates on the actor role and inference generation on the rollout role.
  • Pathways: Provides single-controller distributed execution across TPU worker hosts for the trainer and sampler meshes.

When you set the managed_mldiagnostics parameter to True on an RL workload, ML Diagnostics automatically performs the following actions:

  • Registers a managed MachineLearningRun (MLRun) resource and records your workload configurations.
  • Streams RL training, reward, completion, and performance metrics to Cloud Logging as Tunix logs each step.
  • Collects separate XProf traces for the actor and rollout roles across Pathways worker hosts when you set the profiler parameter to "xplane", and uploads the traces to Cloud Storage.

Before you begin

Before you run an RL workload with ML Diagnostics, complete the following prerequisites:

  1. Complete the ML Diagnostics prerequisites, including enabling the Cluster Director API, granting the required IAM roles on your Google Cloud project, and enabling Log Analytics on the _Default log bucket in Logging.
  2. Deploy a GKE cluster with Pathways support and install the mldiagnostics-injection-webhook component so that MLRun resource metadata is automatically injected into your JobSet Pods. For more information, see Configure GKE or self-managed Kubernetes and Run workloads with Pathways.
  3. Install the gcluster CLI from Cluster Toolkit and install the kubectl command-line tool.
  4. Create a Cloud Storage bucket to store workload outputs, Pathways state, and XProf traces.

Running an RL workload on Cloud TPU and storing logs and traces in Logging and Cloud Storage incur usage charges. Managed XProf compute resources are available at no additional charge. For more information, see ML Diagnostics pricing.

Configure RL diagnostics and profiling

To collect telemetry and performance traces from an RL workload, you enable managed run registration, Tunix performance metrics, and per-role XProf profiling in MaxText. In this section, you set these options, review each configuration parameter, and learn how multi-host tracing on Pathways and role invocation counting guide your settings.

Configure ML Diagnostics and per-role invocation profiling in the src/maxtext/configs/post_train/rl.yml configuration file or by passing command-line overrides:

run_name: "RUN_NAME"
base_output_directory: "gs://BUCKET_DIR"

# Enable managed ML Diagnostics run registration and metric streaming
managed_mldiagnostics: True
managed_mldiagnostics_on_demand_profiling: False
enable_tunix_perf_metrics: True

# Enable per-role invocation XProf profiling
profiler: "xplane"
rl:
  profiler_start_invocation: 20
  profiler_num_invocations: 1
  profiler_max_num_hosts: 2

Replace the following:

  • RUN_NAME: a unique identifier for your training run
  • BUCKET_DIR: your Cloud Storage bucket and directory path for storing outputs and profiles, such as the my-bucket/rl-runs path

The following table describes the RL diagnostics and profiling parameters:

Parameter Description
run_name Required. Identifier for your training run.
base_output_directory Required. Cloud Storage output path with the gs:// URI prefix for checkpoints, logs, and profile traces.
managed_mldiagnostics Enables MLRun resource registration, RL scalar metric streaming, and profile session uploads.
managed_mldiagnostics_on_demand_profiling Enables the on-demand profiling server for the run. Default: True. Set this parameter to False when you set the profiler parameter to "xplane". Otherwise, MaxText fails at startup with a validation error because on-demand captures conflict with programmatic trace sessions.
enable_tunix_perf_metrics Enables Tunix step-timing and performance metrics under the perf/train/* metric prefix.
profiler Set to the "xplane" value to enable XProf trace capture for the actor and rollout roles.
rl.profiler_start_invocation Zero-indexed role invocation at which to start profiling, after initial compilation and warmup.
rl.profiler_num_invocations Number of consecutive invocations to profile for the actor and rollout roles.
rl.profiler_max_num_hosts Number of Pathways worker hosts to trace. Default: 1, which traces only worker 0. Set this parameter to the number of worker hosts in your TPU topology so that both trainer and sampler hosts are captured in the trace. For example, set this parameter to a value of 2 on a two-host v5litepod-8 slice.

Capture traces across all Pathways worker hosts

Multi-host tracing lets XProf capture activity from every participating TPU host when your trainer and sampler meshes run on separate VMs. Without multi-host tracing, rollout profiles can appear incomplete even when your workload runs normally.

By default, Pathways profiling traces only worker 0. If the actor trainer and rollout sampler run on separate VMs, tracing only worker 0 omits the sampler hosts without raising an error. To trace both meshes across multiple TPU worker VMs, set the rl.profiler_max_num_hosts parameter to at least the total number of worker hosts. For example, on a two-host v5litepod-8 slice with a 2x4 topology, set the rl.profiler_max_num_hosts parameter to at least 2.

Set post-warmup profiling windows per role

Per-role profiling windows let you target TPU execution after initial XLA compilation and warmup (steady-state execution) for each RL role and migrate profiler settings from standard MaxText training scripts. Because actor updates and rollout generations run on separate schedules, RL profiling tracks each role independently rather than counting global training steps.

To determine when to capture traces, the Tunix profiler maintains a separate invocation counter for each role. The profiler increments the actor counter on each policy update or evaluation pass and the rollout counter on each generation batch. When you enable XProf profiling, set the rl.profiler_start_invocation parameter high enough to skip initial XLA compilation and warmup. Set the rl.profiler_num_invocations parameter to a small count to capture compact steady-state traces for each role.

If you're migrating an existing MaxText training script that uses step-based profiler flags, replace those legacy flags with the corresponding RL profiling parameters:

Legacy MaxText flag RL profiling parameter
skip_first_n_steps_for_profiler rl.profiler_start_invocation
profiler_steps rl.profiler_num_invocations

MaxText maps these legacy flags automatically if you don't set the RL profiling parameters, but explicit RL profiling parameters always take precedence.

Prepare a Docker image for RL

Running an RL workload with ML Diagnostics on GKE requires a container image that includes both the MaxText post-training environment and the ML Diagnostics client libraries. To prepare this image, you extend the MaxText post-training base image with the google-cloud-mldiagnostics, xprof, and google-cloud-logging Python packages so that worker Pods can export runs, metrics, and traces.

To prepare the container image, complete the following steps:

  1. Create a file named Dockerfile with the following content:

    FROM us-docker.pkg.dev/cloud-tpu-images/maxtext-images/tpu_post_training:latest
    
    RUN pip install --no-cache-dir --upgrade \
        google-cloud-mldiagnostics \
        xprof \
        google-cloud-logging
    
  2. Build and push the container image to Artifact Registry or your preferred container registry.

Run an RL workload on GKE with Pathways

After you build and push your RL container image, you deploy the post-training job to your GKE cluster with Pathways orchestration enabled. In this section, you pass your ML Diagnostics and profiling overrides to the MaxText RL trainer and submit the multi-host job with Cluster Toolkit.

Before you submit the job, verify that the mldiagnostics-injection-webhook component is installed in your GKE cluster and that the target Kubernetes namespace or workload has the managed-mldiagnostics-gke=true label so that the webhook injects MLRun resource metadata into your JobSet Pods. For more information, see Label workload. Configure your target project, cluster, and location by using the gcluster job config set command, or pass the --project, --cluster, and --location flags when you submit the job.

Submit the RL workload with Pathways enabled by using the gcluster job submit command, such as on a two-host v5litepod-8 slice with a 2x4 topology:

MAXTEXT_COMMAND="ENABLE_PATHWAYS_PERSISTENCE=1 \
python3 -m maxtext.trainers.post_train.rl.train_rl \
    run_name=RUN_NAME \
    model_name=MODEL_NAME \
    base_output_directory=gs://BUCKET_DIR \
    num_batches=500 \
    managed_mldiagnostics=True \
    managed_mldiagnostics_on_demand_profiling=False \
    enable_tunix_perf_metrics=True \
    profiler=xplane \
    rl.profiler_start_invocation=20 \
    rl.profiler_num_invocations=1 \
    rl.profiler_max_num_hosts=2"

gcluster job submit \
    --image="IMAGE_URI" \
    --name="RUN_NAME" \
    --pathways \
    --compute-type="v5litepod-8" \
    --topology="2x4" \
    --num-slices=1 \
    --pathways-gcs-location="gs://BUCKET_DIR" \
    --command="${MAXTEXT_COMMAND}"

Replace the following:

  • RUN_NAME: a unique name for your run and JobSet workload (22 characters or fewer, using lowercase alphanumeric characters and hyphens, for Pathways jobs).
  • MODEL_NAME: the MaxText model name to train.
  • BUCKET_DIR: your Cloud Storage bucket and directory path for outputs, Pathways state, and profiles.
  • IMAGE_URI: the URI of the RL container image that you built.

View RL metrics and per-role profiles

While your RL job runs, ML Diagnostics records workload configurations, streams scalar training and reward metrics to Logging, and uploads per-role XProf traces to Cloud Storage. After starting the job, you retrieve your MLRun resource link from the container logs, open the run in the Google Cloud console, and inspect RL metrics and per-role traces.

To view your RL metrics and per-role XProf profiles, complete the following steps:

  1. Retrieve the registered MLRun resource name, the direct Google Cloud console link, and the Cloud Storage profiling output path from the workload-container logs on the pathways-head Pod (or use the -c jax-tpu flag if you submitted a custom JobSet manifest instead of using gcluster):

    kubectl logs \
        -l jobset.sigs.k8s.io/jobset-name=RUN_NAME,jobset.sigs.k8s.io/replicatedjob-name=pathways-head \
        -c workload-container
    

    Replace RUN_NAME with the name of your run.

  2. Open the Google Cloud console link from the container logs, or go to the Run Diagnostics tab and select your MLRun resource:

  3. View your RL metrics and per-role profiles:

    • On the Model Metrics tab, view time-series charts grouped under the following metric prefixes:

      • actor/train/*: RL policy training metrics
      • rewards/train/*: reward function scores
      • completions/train/*: generated completion lengths
      • perf/train/*: Tunix step-timing and performance metrics
    • On the Profiles tab, click a captured per-role session to open its trace in the managed XProf viewer:

      • actor_invocation_INVOCATION_NUMBER: traces for policy updates
      • rollout_invocation_INVOCATION_NUMBER: traces for rollout generation

ML Diagnostics stores per-host .xplane.pb trace files in Cloud Storage at the following path:

gs://BUCKET_DIR/RUN_NAME/managed-mldiagnostics/MLRUN_NAME/plugins/profile/ROLE_invocation_INVOCATION_NUMBER/

This path includes the following values:

  • BUCKET_DIR: the Cloud Storage bucket and directory path from the base_output_directory parameter
  • RUN_NAME: the run identifier from the run_name parameter
  • MLRUN_NAME: the generated MLRun resource name
  • ROLE: the RL role name, either the actor role or the rollout role
  • INVOCATION_NUMBER: the zero-indexed invocation number for that role

What's next