Pre-train Qwen3-30B-A3B on GKE with multi-host NVIDIA Megatron-Bridge on A4 VMs

Google Kubernetes Engine (GKE) lets you pre-train sparse Mixture-of-Experts (MoE) models across multi-host GPU clusters. In this tutorial, you pre-train the model Qwen3-30B-A3B from randomized model weights on two A4 (a4-highgpu-8g) virtual machine (VM) instances with a total of 16 NVIDIA B200 GPUs. Qwen3-30B-A3B has 30.5 billion total parameters, 3.3 billion active parameters, 128 experts, and Top-8 routing. The training workload randomly initializes model weights, so you don't need a Hugging Face access token to complete this tutorial.

This tutorial is intended for machine learning (ML) engineers, researchers, and platform administrators who deploy distributed GPU training workloads on Google Cloud.

Objectives

  • Provision a two-node A4 GKE cluster in Standard mode by using Cluster Toolkit.
  • Prepare a tokenized C4 dataset and tokenizer on Cloud Storage FUSE.
  • Run multi-host pre-training for Qwen3-30B-A3B across 16 NVIDIA B200 GPUs by using NVIDIA Megatron-Bridge, Kueue, and Kubernetes JobSet.
  • Monitor GPU utilization, verify asynchronous checkpoints, and resume training from a saved checkpoint.
  • Clean up all deployed resources to avoid ongoing charges.

Costs

In this document, you use the following billable components of Google Cloud:

To generate a cost estimate based on your projected usage, use the pricing calculator.

Before you begin

Set up your environment for the tutorial:

  1. Select or create a Google Cloud project and verify that billing is enabled for your project.

  2. Install and initialize the Google Cloud CLI. If you're using Cloud Shell, then the gcloud CLI is preinstalled.

  3. Install the following tools. If you're using Cloud Shell, then these tools are preinstalled:

  4. If you run this tutorial from a Linux or macOS workstation rather than Cloud Shell, then verify that your environment meets the Cluster Toolkit dependencies. The gcluster deploy --download-dependencies command downloads Terraform automatically.

  5. Enable the Kubernetes Engine API, Compute Engine API, Cloud Storage API, Identity and Access Management API, Cloud Resource Manager API, Service Usage API, Cloud Logging API, and Cloud Monitoring API in your Google Cloud project:

    Enable APIs

  6. Verify that network configurations and organization policies in your Google Cloud project allow outbound internet access for GKE nodes. When the cluster runs, nodes must pull the nvcr.io/nvidia/nemo:26.08.01 container image from NVIDIA NGC and the public Qwen/Qwen3-30B-A3B tokenizer and allenai/c4 dataset shard from Hugging Face.

Required roles

To get the permissions that you need to complete this tutorial, ask your administrator to grant you the following IAM roles on your project:

For more information about granting roles, see Manage access to projects, folders, and organizations.

You might also be able to get the required permissions through custom roles or other predefined roles.

Set up your environment variables

Configure your authentication and environment variables for the tutorial:

  1. Sign in to the gcloud CLI and generate Application Default Credentials for Terraform:

    gcloud auth login
    gcloud auth application-default login
  2. Export the environment variables that you use throughout this tutorial:

    export PROJECT_ID="YOUR_PROJECT_ID"
    export REGION="YOUR_REGION" # for example, us-central1
    export ZONE="YOUR_ZONE" # for example, us-central1-b
    export CLUSTER_NAME="YOUR_CLUSTER_NAME" # maximum 20 chars; start with a-z; only a-z, 0-9, -
    export BUCKET_NAME="YOUR_GCS_BUCKET" # globally unique Cloud Storage bucket for Terraform state
    export RESERVATION_NAME="YOUR_RESERVATION_NAME" # reservation name or RESERVATION_NAME/reservationBlocks/RESERVATION_BLOCK_NAME
    export CLUSTER_TOOLKIT_VERSION="v1.109.0"
    export NODE_COUNT=2
    export AUTHORIZED_CIDR="0.0.0.0/0" # or restrict to your workstation IP as a /32
    
    gcloud config set project "${PROJECT_ID:?}"
    gcloud config set billing/quota_project "${PROJECT_ID:?}"

    Replace the following:

    • YOUR_PROJECT_ID: the ID of your Google Cloud project.
    • YOUR_REGION: the compute region where your A4 capacity is located and where you want to deploy your cluster, such as us-central1.
    • YOUR_ZONE: the compute zone where your A4 capacity is located, such as us-central1-b.
    • YOUR_CLUSTER_NAME: the name for your GKE cluster and Cluster Toolkit deployment. The name must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens. Keep the name to 20 lowercase characters or fewer so that the generated service account ID (YOUR_CLUSTER_NAME-gke-np-sa) stays within the 30-character Identity and Access Management (IAM) limit.
    • YOUR_GCS_BUCKET: a globally unique name for the Cloud Storage bucket that stores the Terraform state for Cluster Toolkit.
    • YOUR_RESERVATION_NAME: the name of your A4 reservation, or the extended reservation block path in the format RESERVATION_NAME/reservationBlocks/RESERVATION_BLOCK_NAME.

    These commands set the values of CLUSTER_TOOLKIT_VERSION to v1.109.0, NODE_COUNT to 2, and AUTHORIZED_CIDR to 0.0.0.0/0, and they also configure your default project and billing quota project for the gcloud CLI. For production deployments, to help protect access to the cluster control plane, restrict AUTHORIZED_CIDR to your workstation's /32 CIDR range.

Create the GKE cluster

Download Cluster Toolkit and provision a GKE cluster in Standard mode:

  1. Download and extract the prebuilt Cluster Toolkit bundle for the version specified in CLUSTER_TOOLKIT_VERSION (v1.109.0), change your working directory to cluster-toolkit, and then verify the binary version:

    case "$(uname -s)-$(uname -m)" in
      Linux-x86_64)              BUNDLE="gcluster_bundle_linux_amd64.tgz" ;;
      Linux-aarch64|Linux-arm64) BUNDLE="gcluster_bundle_linux_arm64.tgz" ;;
      Darwin-x86_64)             BUNDLE="gcluster_bundle_mac_amd64.tgz" ;;
      Darwin-arm64)              BUNDLE="gcluster_bundle_mac_arm64.tgz" ;;
      *) BUNDLE=""; echo "Unsupported platform: $(uname -s)-$(uname -m)" >&2 ;;
    esac
    mkdir -p cluster-toolkit
    curl -fsSL "https://github.com/GoogleCloudPlatform/cluster-toolkit/releases/download/${CLUSTER_TOOLKIT_VERSION:?}/${BUNDLE:?}" \
      | tar -xz -C cluster-toolkit
    cd cluster-toolkit
    ./gcluster --version
  2. Create a Cloud Storage bucket to store your Cluster Toolkit Terraform state, and enable uniform bucket-level access and Object Versioning on the bucket:

    gcloud storage buckets create "gs://${BUCKET_NAME:?}" \
      --project="${PROJECT_ID:?}" \
      --location="${REGION:?}" \
      --default-storage-class=STANDARD \
      --uniform-bucket-level-access
    gcloud storage buckets update "gs://${BUCKET_NAME:?}" --versioning
  3. Populate the examples/gke-a4/gke-a4-deployment.yaml deployment configuration file for two A4 nodes:

    cat <<EOF > examples/gke-a4/gke-a4-deployment.yaml
    terraform_backend_defaults:
      type: gcs
      configuration:
        bucket: ${BUCKET_NAME:?}
    vars:
      project_id: ${PROJECT_ID:?}
      deployment_name: ${CLUSTER_NAME:?}
      region: ${REGION:?}
      zone: ${ZONE:?}
      static_node_count: ${NODE_COUNT}
      authorized_cidr: "${AUTHORIZED_CIDR}"
      reservation_affinity:
        consume_reservation_type: SPECIFIC_RESERVATION
        specific_reservations:
        - name: ${RESERVATION_NAME:?}
    EOF

    By default, the deployment file configures the reservation_affinity field to consume a specific reservation. If you don't have a specific reservation, then before you deploy the cluster, you can update examples/gke-a4/gke-a4-deployment.yaml to use Spot VMs or Flex-start VMs instead. For configuration instructions, see GKE consumption options.

  4. Deploy the GKE cluster by using the gcluster deploy command with the --download-dependencies flag, which downloads Terraform automatically:

    ./gcluster deploy \
      --download-dependencies \
      -d examples/gke-a4/gke-a4-deployment.yaml \
      examples/gke-a4/gke-a4.yaml \
      --auto-approve -w

    If you run ./gcluster deploy without the --auto-approve flag, then to apply the proposed changes, enter a when prompted.

  5. Wait for cluster deployment to finish, which takes about 18 to 20 minutes. When the deployment succeeds, the output is similar to the following:

    Apply complete! Resources: 80 added, 0 changed, 0 destroyed.
    
  6. Fetch kubectl credentials for your cluster and verify that the two A4 nodes, the nccl-rdma-installer DaemonSet, the default-rdma ResourceClaimTemplate object, the Kueue queues, and the Cloud Storage FUSE PersistentVolumeClaims (PVCs) are ready:

    gcloud container clusters get-credentials "${CLUSTER_NAME:?}" \
      --region="${REGION:?}" \
      --project="${PROJECT_ID:?}"
    kubectl get nodes -l cloud.google.com/gke-nodepool=a4-highgpu-8g-a4-pool -o wide
    kubectl get daemonset nccl-rdma-installer -n kube-system
    kubectl get resourceclaimtemplate default-rdma
    kubectl get clusterqueue,localqueue
    kubectl get pvc

    Verify that the output shows Ready for both A4 nodes, two ready Pods (2) for nccl-rdma-installer, default-rdma and the Kueue queues present, and Bound for both Cloud Storage FUSE PVCs.

  7. Optional: To verify GPUDirect RDMA (gIB) bandwidth across all 16 NVIDIA B200 GPUs, run the bundled two-node NVIDIA Collective Communications Library (NCCL) all_gather_perf JobSet from the cluster-toolkit directory, inspect the Pod logs for Node 0 (job-completion-index=0), and then delete the JobSet to release the Kueue quota:

    kubectl create -f examples/gke-a4/nccl-jobset-example.yaml
    kubectl wait --for=condition=Completed jobset -l kueue.x-k8s.io/queue-name=a4 --timeout=600s
    kubectl logs -l batch.kubernetes.io/job-completion-index=0
    kubectl delete jobset -l kueue.x-k8s.io/queue-name=a4

    The NCCL test takes about 3 minutes to finish. In the Node 0 logs, confirm that the busbw column reports approximately 370 GBps to 375 GBps for the 8 GiB message size row (8589934592 in the size column)—not the lower Avg bus bandwidth summary value across all message sizes at the end of the output.

Prepare the tokenized dataset

In this section, you use the qwen3-data-prep.yaml manifest to run a Kueue-managed Kubernetes Job that downloads the tokenizer and 100,000 C4 documents and writes tokenized .bin and .idx files to your Cloud Storage FUSE training volume.

To prepare and run the data-preparation Job, do the following:

  1. Download the Kubernetes manifest files for dataset preparation and multi-host pre-training:

    curl -fLO https://raw.githubusercontent.com/GoogleCloudSamples/AIHypercomputerSamples/main/gpu/training/qwen-megatron-gke/qwen3-data-prep.yaml
    curl -fLO https://raw.githubusercontent.com/GoogleCloudSamples/AIHypercomputerSamples/main/gpu/training/qwen-megatron-gke/qwen3-30b-a3b-pretrain-jobset.yaml
  2. Retrieve and export the names of the training and checkpointing Cloud Storage FUSE PVCs that Cluster Toolkit created:

    export TRAINING_PVC="$(kubectl get pvc -o jsonpath='{.items[?(@.spec.storageClassName=="gcsfusecsi-training")].metadata.name}')"
    export CHECKPOINT_PVC="$(kubectl get pvc -o jsonpath='{.items[?(@.spec.storageClassName=="gcsfusecsi-checkpointing")].metadata.name}')"
    echo "Training PVC:   ${TRAINING_PVC}"
    echo "Checkpoint PVC: ${CHECKPOINT_PVC}"
  3. Review the qwen3-data-prep.yaml manifest. If you didn't download it earlier, then create a file named qwen3-data-prep.yaml with the following content:

    apiVersion: batch/v1
    kind: Job
    metadata:
      name: qwen3-data-prep
      namespace: default
      labels:
        kueue.x-k8s.io/queue-name: a4
    spec:
      suspend: true
      backoffLimit: 1
      ttlSecondsAfterFinished: 3600
      template:
        metadata:
          annotations:
            gke-gcsfuse/volumes: "true"
            gke-gcsfuse/cpu-limit: "0"
            gke-gcsfuse/memory-limit: "0"
            gke-gcsfuse/ephemeral-storage-limit: "0"
        spec:
          serviceAccountName: workload-identity-k8s-sa
          restartPolicy: Never
          nodeSelector:
            cloud.google.com/gke-nodepool: a4-highgpu-8g-a4-pool
          tolerations:
          - key: "nvidia.com/gpu"
            operator: "Exists"
            effect: "NoSchedule"
          - key: "cloud.google.com/gke-queued"
            value: "true"
            effect: "NoSchedule"
          volumes:
          - name: nvidia
            hostPath:
              path: /home/kubernetes/bin/nvidia
          - name: training-data
            persistentVolumeClaim:
              claimName: ${TRAINING_PVC}
          containers:
          - name: data-prep
            image: nvcr.io/nvidia/nemo:26.08.01
            command:
            - bash
            - -c
            - |
              set -euo pipefail
              /sbin/ldconfig
              export LD_LIBRARY_PATH="/usr/lib/$(uname -m)-linux-gnu:/usr/local/nvidia/lib64:${LD_LIBRARY_PATH:-}"
              if [[ -s /training-data/dataset/c4_qwen3_text_document.bin && \
                    -s /training-data/dataset/c4_qwen3_text_document.idx && \
                    -s /training-data/tokenizer/tokenizer.json ]]; then
                echo "Tokenized C4 dataset and Qwen3 tokenizer already exist in /training-data:"
                ls -lh /training-data/tokenizer/ /training-data/dataset/
                exit 0
              fi
              mkdir -p /tmp/prep/tokenizer /training-data/tokenizer /training-data/dataset
              echo "Downloading public Qwen/Qwen3-30B-A3B Hugging Face tokenizer..."
              python3 - <<'PYEOF'
              from transformers import AutoTokenizer
              tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-30B-A3B")
              tok.save_pretrained("/tmp/prep/tokenizer")
              print("Saved tokenizer with vocab size:", len(tok))
              PYEOF
              echo "Downloading public C4 English shard (c4-train.00000-of-01024.json.gz)..."
              curl -fL --retry 3 \
                "https://huggingface.co/datasets/allenai/c4/resolve/main/en/c4-train.00000-of-01024.json.gz" \
                -o /tmp/prep/c4.json.gz
              echo "Extracting 100,000 C4 documents to local NVMe scratch..."
              gzip -dc /tmp/prep/c4.json.gz > /tmp/prep/c4_full.jsonl
              head -n 100000 /tmp/prep/c4_full.jsonl > /tmp/prep/c4_en_100k.jsonl
              rm -f /tmp/prep/c4.json.gz /tmp/prep/c4_full.jsonl
              PREPROCESS_SCRIPT="/opt/Megatron-Bridge/3rdparty/Megatron-LM/tools/preprocess_data.py"
              export PYTHONPATH="/opt/Megatron-Bridge/3rdparty/Megatron-LM:${PYTHONPATH:-}"
              echo "Tokenizing C4 JSONL into Megatron IndexedDataset (.bin/.idx)..."
              python3 "${PREPROCESS_SCRIPT}" \
                --input /tmp/prep/c4_en_100k.jsonl \
                --output-prefix /tmp/prep/c4_qwen3 \
                --tokenizer-type HuggingFaceTokenizer \
                --tokenizer-model /tmp/prep/tokenizer \
                --json-keys text \
                --append-eod \
                --workers 16 \
                --log-interval 25000
              echo "Persisting tokenized dataset and tokenizer to Cloud Storage FUSE..."
              cp -rf /tmp/prep/tokenizer/. /training-data/tokenizer/
              cp -f /tmp/prep/c4_qwen3_text_document.bin /training-data/dataset/c4_qwen3_text_document.bin
              cp -f /tmp/prep/c4_qwen3_text_document.idx /training-data/dataset/c4_qwen3_text_document.idx
              sync
              ls -lh /training-data/tokenizer/ /training-data/dataset/
              echo "Dataset preparation complete."
            volumeMounts:
            - name: nvidia
              mountPath: /usr/local/nvidia
            - name: training-data
              mountPath: /training-data
            resources:
              limits:
                nvidia.com/gpu: 1
              requests:
                nvidia.com/gpu: 1
  4. Substitute the ${TRAINING_PVC} environment variable into qwen3-data-prep.yaml, submit the Job, wait for completion, and inspect the Job logs:

    envsubst '${TRAINING_PVC}' < qwen3-data-prep.yaml | kubectl apply -f -
    kubectl wait --for=condition=complete job/qwen3-data-prep --timeout=1200s
    kubectl logs job/qwen3-data-prep -c data-prep

    Dataset preparation takes about 2 to 4 minutes on the first container image pull.

  5. Before you proceed to pre-training, verify that the logs list the saved tokenizer and tokenized .bin and .idx files, ending with the following message:

    Dataset preparation complete.
    

Run the multi-host pre-training workload

The qwen3-30b-a3b-pretrain-jobset.yaml manifest defines a two-node Kueue-managed Kubernetes JobSet that runs the official NVIDIA Megatron-Bridge B200 performance recipe (scripts/performance/bootstrap.py) across 16 NVIDIA B200 GPUs. The manifest configures the following optimizations for A4 clusters:

  • A4 topology-aligned parallelism: Configures expert parallelism (EP=8), dense data parallelism (Dense DP=16), expert data parallelism (Expert DP=2), tensor parallelism (TP=1), and pipeline parallelism (PP=1). Keeping all eight expert-parallel ranks inside each node's NVLink domain (1.8 TBps per GPU) lets the workload use the hybridep dispatcher and full_iteration CUDA graphs. Dense layers and replicated expert shards synchronize across nodes over 400 Gbps per GPU (3.2 Tbps per node) GPUDirect RDMA (gIB) with a global batch size (GBS) of 1,024 and a micro-batch size (MBS) of 4.
  • Blackwell MXFP8 precision and built-in RDMA stack: Uses the unmodified --compute_dtype fp8_mx recipe inside the pinned nvcr.io/nvidia/nemo:26.08.01 container image. The container image bundles the /etc/gcp_nccl_init.sh GPUDirect RDMA initialization script, so that you don't need a host gIB mount.
  • Local SSD staging and asynchronous checkpointing: Copies the tokenized C4 dataset and tokenizer from Cloud Storage FUSE to each node's Local SSD disk before training starts. The workload runs 50 iterations with --save_interval 25, --load_dir, and checkpoint.async_save=True so that iteration 25 saves asynchronously in torch_dist format during iterations 26 through 50.
  • GPU memory management for asynchronous checkpointing and resumption: Overrides the PYTORCH_CUDA_ALLOC_CONF environment variable (expandable_segments:False,max_split_size_mb:512,graph_capture_record_stream_reuse:True) and sets train.empty_unused_memory_level=1. These settings help prevent GPU virtual address exhaustion and out-of-memory errors when persistent asynchronous checkpoint workers run or when CUDA graphs are captured after checkpoint resumption.

Deploy and monitor the two-node pre-training JobSet:

  1. Review the qwen3-30b-a3b-pretrain-jobset.yaml manifest. If you didn't download it earlier, then create a file named qwen3-30b-a3b-pretrain-jobset.yaml with the following content:

    apiVersion: jobset.x-k8s.io/v1alpha2
    kind: JobSet
    metadata:
      name: qwen3-30b-a3b
      namespace: default
      labels:
        kueue.x-k8s.io/queue-name: a4
    spec:
      ttlSecondsAfterFinished: 3600
      suspend: true
      network:
        enableDNSHostnames: true
      replicatedJobs:
      - name: w
        replicas: 1
        template:
          spec:
            parallelism: 2
            completions: 2
            backoffLimit: 0
            template:
              metadata:
                annotations:
                  kueue.x-k8s.io/podset-preferred-topology: "kubernetes.io/hostname"
                  networking.gke.io/default-interface: "eth0"
                  gke-gcsfuse/volumes: "true"
                  gke-gcsfuse/cpu-limit: "0"
                  gke-gcsfuse/memory-limit: "0"
                  gke-gcsfuse/ephemeral-storage-limit: "0"
              spec:
                serviceAccountName: workload-identity-k8s-sa
                restartPolicy: Never
                setHostnameAsFQDN: true
                nodeSelector:
                  cloud.google.com/gke-nodepool: a4-highgpu-8g-a4-pool
                tolerations:
                - key: "nvidia.com/gpu"
                  operator: "Exists"
                  effect: "NoSchedule"
                - key: "cloud.google.com/gke-queued"
                  value: "true"
                  effect: "NoSchedule"
                resourceClaims:
                - name: rdma
                  resourceClaimTemplateName: default-rdma
                volumes:
                - name: nvidia
                  hostPath:
                    path: /home/kubernetes/bin/nvidia
                - name: shared-memory
                  emptyDir:
                    medium: "Memory"
                    sizeLimit: 512Gi
                - name: training-data
                  persistentVolumeClaim:
                    claimName: ${TRAINING_PVC}
                    readOnly: true
                - name: checkpoint-data
                  persistentVolumeClaim:
                    claimName: ${CHECKPOINT_PVC}
                containers:
                - name: megatron-bridge
                  image: nvcr.io/nvidia/nemo:26.08.01
                  securityContext:
                    privileged: true
                  env:
                  - name: MASTER_ADDR
                    value: "qwen3-30b-a3b-w-0-0.qwen3-30b-a3b"
                  - name: MASTER_PORT
                    value: "29500"
                  - name: NNODES
                    value: "2"
                  - name: GPUS_PER_NODE
                    value: "8"
                  - name: NODE_RANK
                    valueFrom:
                      fieldRef:
                        fieldPath: metadata.annotations['batch.kubernetes.io/job-completion-index']
                  - name: TRAIN_ITERS
                    value: "${TRAIN_ITERS}"
                  - name: GLOO_SOCKET_IFNAME
                    value: "eth0"
                  - name: NCCL_DEBUG
                    value: "WARN"
                  - name: OMP_NUM_THREADS
                    value: "4"
                  # Disable expandable_segments while keeping graph_capture_record_stream_reuse so
                  # PersistentAsyncCaller CUDA IPC does not exhaust driver VA/handles across MoE tensors.
                  - name: PYTORCH_CUDA_ALLOC_CONF
                    value: "expandable_segments:False,max_split_size_mb:512,graph_capture_record_stream_reuse:True"
                  command:
                  - bash
                  - -c
                  - |
                    set -euo pipefail
                    /sbin/ldconfig
                    # Configure NCCL + GPUDirect RDMA (gIB) via NeMo 26.08.01's pre-installed GCP plugin.
                    # Keep /usr/lib/<arch>-linux-gnu ahead of /usr/local/nvidia/lib64 so host libnccl.so
                    # from Cluster Toolkit's nccl-rdma-installer does not shadow the container NCCL.
                    echo "[Node ${NODE_RANK}] Sourcing /etc/gcp_nccl_init.sh"
                    source /etc/gcp_nccl_init.sh
                    export LD_LIBRARY_PATH="/usr/lib/$(uname -m)-linux-gnu:${LD_LIBRARY_PATH:-}:/usr/local/nvidia/lib64"
                    export NCCL_SOCKET_IFNAME="eth0,eth1"
                    if [[ -d /opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/datasets ]]; then
                      make -C /opt/Megatron-Bridge/3rdparty/Megatron-LM/megatron/core/datasets >/dev/null 2>&1 || true
                    fi
                    echo "[Node ${NODE_RANK}] Staging tokenized C4 dataset and Qwen3 tokenizer to local NVMe..."
                    mkdir -p /tmp/megatron-data/tokenizer /checkpoint-data/qwen3-30b-a3b /checkpoint-data/data-cache /checkpoint-data/tb-logs
                    cp -rf /training-data/tokenizer/. /tmp/megatron-data/tokenizer/
                    cp -f /training-data/dataset/c4_qwen3_text_document.bin /tmp/megatron-data/c4_qwen3_text_document.bin
                    cp -f /training-data/dataset/c4_qwen3_text_document.idx /tmp/megatron-data/c4_qwen3_text_document.idx
                    echo "[Node ${NODE_RANK}] Waiting for Master DNS (${MASTER_ADDR})..."
                    until getent hosts "${MASTER_ADDR}" >/dev/null 2>&1; do
                      sleep 2
                    done
                    cd /opt/Megatron-Bridge
                    torchrun \
                      --nproc_per_node="${GPUS_PER_NODE}" \
                      --nnodes="${NNODES}" \
                      --node_rank="${NODE_RANK}" \
                      --master_addr="${MASTER_ADDR}" \
                      --master_port="${MASTER_PORT}" \
                      scripts/performance/bootstrap.py \
                        --model_family_name qwen \
                        --model_recipe_name qwen3_30b_a3b \
                        --gpu b200 \
                        --num_gpus 16 \
                        --gpus_per_node 8 \
                        --compute_dtype fp8_mx \
                        --seq_length 4096 \
                        --global_batch_size 1024 \
                        --micro_batch_size 4 \
                        --tensor_model_parallel_size 1 \
                        --pipeline_model_parallel_size 1 \
                        --context_parallel_size 1 \
                        --expert_model_parallel_size 8 \
                        --cuda_graph_impl local \
                        --cuda_graph_scope full_iteration \
                        --moe_a2a_overlap true \
                        --moe_flex_dispatcher_backend hybridep \
                        --max_steps "${TRAIN_ITERS}" \
                        --data rp2 \
                        --dataset_paths /tmp/megatron-data/c4_qwen3_text_document \
                        --index_mapping_dir /checkpoint-data/data-cache \
                        --save_dir /checkpoint-data/qwen3-30b-a3b \
                        --load_dir /checkpoint-data/qwen3-30b-a3b \
                        --save_interval 25 \
                        tokenizer.tokenizer_model=/tmp/megatron-data/tokenizer \
                        checkpoint.async_save=True \
                        checkpoint.use_persistent_ckpt_worker=True \
                        logger.log_throughput=True \
                        logger.tensorboard_dir=/checkpoint-data/tb-logs \
                        train.manual_gc_interval=100 \
                        train.empty_unused_memory_level=1
                  volumeMounts:
                  - name: nvidia
                    mountPath: /usr/local/nvidia
                  - name: shared-memory
                    mountPath: /dev/shm
                  - name: training-data
                    mountPath: /training-data
                    readOnly: true
                  - name: checkpoint-data
                    mountPath: /checkpoint-data
                  resources:
                    limits:
                      nvidia.com/gpu: 8
                    requests:
                      nvidia.com/gpu: 8
                    claims:
                    - name: rdma
  2. Export TRAIN_ITERS=50, substitute the environment variables into qwen3-30b-a3b-pretrain-jobset.yaml, apply the JobSet, and verify that Kueue admits the workload and starts both Pods:

    export TRAIN_ITERS=50
    envsubst '${TRAINING_PVC} ${CHECKPOINT_PVC} ${TRAIN_ITERS}' < qwen3-30b-a3b-pretrain-jobset.yaml | kubectl apply -f -
    kubectl wait --for=create job/qwen3-30b-a3b-w-0 --timeout=300s
    kubectl wait --for=jsonpath='{.status.ready}'=2 job/qwen3-30b-a3b-w-0 --timeout=1200s
    kubectl get workloads,jobset,pods -o wide
  3. Optional: In a separate terminal session, stream live per-iteration loss, auxiliary load-balancing loss, step latency, and throughput (TFLOP/s/GPU) from the Node 1 Pod (job-completion-index=1):

    kubectl logs -f -l jobset.sigs.k8s.io/jobset-name=qwen3-30b-a3b,batch.kubernetes.io/job-completion-index=1 -c megatron-bridge

    Each JobSet Pod runs the megatron-bridge container: the Node 0 Pod (job-completion-index=0) logs startup and checkpoint progress, while the Node 1 Pod (job-completion-index=1) logs per-iteration training metrics. Node 1 pauses logging after iteration 50 for about 5 to 7 minutes while Node 0 flushes the final checkpoint (approximately 400 GiB) to Cloud Storage FUSE. To watch checkpoint save progress instead, replace job-completion-index=1 with job-completion-index=0. To stop streaming logs at any time, press Control+C.

  4. Wait for the qwen3-30b-a3b JobSet to reach the Completed state. Then, to verify asynchronous checkpoint overlap and iteration progress, inspect the Node 0 and Node 1 logs:

    kubectl wait --for=condition=Completed jobset/qwen3-30b-a3b --timeout=1800s
    kubectl logs --tail=-1 \
      -l jobset.sigs.k8s.io/jobset-name=qwen3-30b-a3b,batch.kubernetes.io/job-completion-index=0 \
      -c megatron-bridge | grep -E "Sourcing /|scheduled an async|successfully saved" | tail -n 25
    kubectl logs --tail=-1 \
      -l jobset.sigs.k8s.io/jobset-name=qwen3-30b-a3b,batch.kubernetes.io/job-completion-index=1 \
      -c megatron-bridge | grep -E "async checkpoint|iteration +(24|25|26|27|49|50)/|save-checkpoint" | tail -n 30

    The pre-training JobSet takes about 20 to 25 minutes in total to finish, including about 5 to 7 minutes after iteration 50 while Node 0 flushes the final checkpoint to Cloud Storage FUSE.

    Healthy Node 0 logs have the following properties:

    • Confirmation that /etc/gcp_nccl_init.sh was sourced

    • scheduled an async and successfully saved messages for iterations 25 and 50

    Healthy Node 1 logs show decreasing language-modeling loss (lm loss) with no NaN or Inf values across iterations 1 through 50. Iterations 26 through 50 continue running while the iteration 25 checkpoint flushes in the background.

    You can ignore benign container warnings, including Failed to import Triton kernels and NCCL WARN Call to ibv_query_port_speed failed with error Protocol not supported errno 93. You can also ignore WARNING: Starting a checkpoint save before previous has finished at iteration 50. That final warning occurs because 25 training steps finish faster than the background checkpoint flush to Cloud Storage FUSE; for production runs, increase the value of the --save_interval flag.

Monitor GPU metrics and verify checkpoints

In this section, you verify your pre-training run by charting GPU utilization in Monitoring and listing the saved dataset and checkpoint objects in your Cloud Storage buckets.

View GPU utilization in Monitoring

To verify that all 16 NVIDIA B200 GPUs across both hosts actively processed the pre-training workload, inspect the utilization metric for each GPU:

  1. In the Google Cloud console, go to the  Metrics explorer page:

    Go to Metrics explorer

    If you use the search bar to find this page, then select the result whose subheading is Monitoring.

  2. In the Metric menu, select Prometheus Target > Dcgm > prometheus.googleapis.com/DCGM_FI_DEV_GPU_UTIL/gauge.

  3. In the Filter field, filter by cluster equal to your cluster name (YOUR_CLUSTER_NAME).

  4. To view utilization per GPU across both hosts, group the results by Hostname and gpu.

    For a healthy pre-training run, all 16 GPUs show sustained high utilization—for example, 90% to 100% during active training iterations, with brief drops during startup and checkpoint writes.

Verify dataset and checkpoints

To confirm that the tokenized C4 dataset and both the mid-run (iter_0000025) and final (iter_0000050) asynchronous torch_dist checkpoints exist in your Cloud Storage buckets, do the following:

  1. Retrieve the training and checkpoint bucket names from your cluster's PersistentVolumes and list their contents:

    export TRAINING_BUCKET="$(kubectl get pv -o jsonpath='{.items[?(@.spec.storageClassName=="gcsfusecsi-training")].spec.csi.volumeHandle}')"
    export CHECKPOINT_BUCKET="$(kubectl get pv -o jsonpath='{.items[?(@.spec.storageClassName=="gcsfusecsi-checkpointing")].spec.csi.volumeHandle}')"
    gcloud storage ls "gs://${TRAINING_BUCKET}/dataset/"
    gcloud storage ls "gs://${CHECKPOINT_BUCKET}/qwen3-30b-a3b/"
    gcloud storage ls "gs://${CHECKPOINT_BUCKET}/qwen3-30b-a3b/iter_0000025/" | head -n 25
    gcloud storage ls "gs://${CHECKPOINT_BUCKET}/qwen3-30b-a3b/iter_0000050/" | head -n 25
  2. In the gcloud storage ls output, confirm that the following files and directories exist:

    • In the training bucket (gs://${TRAINING_BUCKET}/dataset/): c4_qwen3_text_document.bin and c4_qwen3_text_document.idx
    • In the checkpoint bucket (gs://${CHECKPOINT_BUCKET}/qwen3-30b-a3b/): latest_checkpointed_iteration.txt, iter_0000025/, and iter_0000050/
    • In each checkpoint directory (iter_0000025/ and iter_0000050/): 16 .distcp shards, run_config.yaml, and train_state.pt

Verify checkpoint resumption

Confirm that the training job resumes without errors from the saved checkpoint by doing the following:

  1. Delete the completed JobSet, relaunch it with TRAIN_ITERS=55, wait for completion, and inspect the resumed iterations in Node 1 logs:

    kubectl delete jobset qwen3-30b-a3b
    kubectl wait --for=delete pod -l jobset.sigs.k8s.io/jobset-name=qwen3-30b-a3b --timeout=300s || true
    export TRAIN_ITERS=55
    envsubst '${TRAINING_PVC} ${CHECKPOINT_PVC} ${TRAIN_ITERS}' < qwen3-30b-a3b-pretrain-jobset.yaml | kubectl apply -f -
    kubectl wait --for=create job/qwen3-30b-a3b-w-0 --timeout=300s
    kubectl wait --for=jsonpath='{.status.ready}'=2 job/qwen3-30b-a3b-w-0 --timeout=1200s
    kubectl wait --for=condition=Completed jobset/qwen3-30b-a3b --timeout=1800s && \
    kubectl logs --tail=-1 \
      -l jobset.sigs.k8s.io/jobset-name=qwen3-30b-a3b,batch.kubernetes.io/job-completion-index=1 \
      -c megatron-bridge | grep -E "iteration +(51|52|53|54|55)/" | tail -n 20

    Checkpoint resumption takes about 20 to 25 minutes in total to finish. During startup, loading approximately 400 GiB of distributed checkpoint shards from Cloud Storage FUSE produces a quiet period of about 11 to 12 minutes in the logs before training iterations resume.

  2. In the Node 1 logs, verify that iterations 51 through 55 complete with continuous lm loss values and no NaN or Inf errors.

  3. Optional: To observe checkpoint loading and final save progress while the resumed JobSet runs, in a separate terminal session, stream live Node 0 logs:

    kubectl logs -f --tail=-1 -l jobset.sigs.k8s.io/jobset-name=qwen3-30b-a3b,batch.kubernetes.io/job-completion-index=0 -c megatron-bridge

    Check the Node 0 logs to confirm that there is a successfully loaded checkpoint message at iteration 50.

Scale to larger models and clusters

This two-node setup demonstrates a multi-node scaling pattern for A4 clusters. The configuration pairs intra-node NVLink expert parallelism with cross-node GPUDirect RDMA data parallelism, Blackwell MXFP8 precision, and asynchronous checkpointing. The following table compares this configuration against a single-node baseline and a 32-node production MoE configuration:

Scale tier Example model Nodes and B200 GPUs Typical parallelism MoE dispatcher and precision Storage and checkpointing
Single-node baseline Qwen3-30B-A3B 1 node (8 GPUs) TP=1, PP=1, EP=8, Dense DP=8, Expert DP=1 (GBS=512, MBS=4) hybridep (intra-node NVLink), fp8_mx, CUDA graphs Local SSD disks or Cloud Storage FUSE
Dual-node (this tutorial) Qwen3-30B-A3B 2 nodes (16 GPUs) TP=1, PP=1, EP=8, Dense DP=16, Expert DP=2 (GBS=1024, MBS=4) hybridep (intra-node NVLink), cross-node DP and Expert DP over gIB RDMA, full_iteration CUDA graphs, fp8_mx Cloud Storage FUSE with asynchronous torch_dist
Large-scale production MoE Qwen3-235B-A22B 32 nodes (256 GPUs) TP=1, PP=8, EP=8, Dense DP=32, Expert DP=4 (GBS=8192, MBS=2) hybridep (intra-node EP=8), cross-node PP and DP over gIB RDMA, fp8_mx Google Cloud Managed Lustre, Local SSD disks, and asynchronous torch_dist

When you scale to larger MoE models (such as Qwen3-235B-A22B or DeepSeek-V3 671B) and larger A4 clusters (16 to 32 or more nodes), update the following configurations:

  • Cluster size and Kueue topology: Increase NODE_COUNT (static_node_count in examples/gke-a4/gke-a4-deployment.yaml) to match your A4 reservation block size. Update parallelism, completions, NNODES, and --num_gpus in the JobSet manifest to match. Use Kueue topology-aware scheduling (kueue.x-k8s.io/podset-preferred-topology for best-effort compact placement, or kueue.x-k8s.io/podset-required-topology set to cloud.google.com/gce-topology-block to require Pods to be colocated within a single RDMA topology block).
  • Two-tier A4 interconnect: Each a4-highgpu-8g VM instance provides 1.8 TBps of intra-node NVLink per GPU and 3.2 Tbps of inter-node RDMA over Converged Ethernet v2 (RoCEv2) (gIB) across eight 400 Gbps network interface cards (NICs). On clusters with 16 or more nodes, keep TP and hybridep EP <= 8 inside each eight-GPU NVLink domain. Scale across nodes by using PP, DP, or standard NCCL alltoall expert parallelism over gIB RDMA.
  • High-throughput storage and checkpoint I/O: For models with 100 billion or more parameters across 16 or more nodes, mount Managed Lustre for shared datasets and parallel torch_dist checkpoint writes. Alternatively, pair non-persistent Local SSD disk checkpoints with periodic asynchronous uploads to Cloud Storage.
  • Performance recipes: To target a larger MoE architecture, pass the corresponding model recipe flags directly to scripts/performance/bootstrap.py. For example, to configure Qwen3-235B-A22B on 256 NVIDIA B200 GPUs, pass --model_family_name qwen --model_recipe_name qwen3_235b_a22b --gpu b200 --num_gpus 256 --compute_dtype fp8_mx.

Clean up

To avoid incurring ongoing charges to your Google Cloud account for the resources used in this tutorial, delete the workloads, storage objects, cluster, and Terraform state bucket:

  1. Delete the pre-training JobSet, the dataset preparation Job, and the dataset and checkpoint objects stored in the Cloud Storage buckets:

    export TRAINING_BUCKET="${TRAINING_BUCKET:-$(kubectl get pv -o jsonpath='{.items[?(@.spec.storageClassName=="gcsfusecsi-training")].spec.csi.volumeHandle}' 2>/dev/null || true)}"
    export CHECKPOINT_BUCKET="${CHECKPOINT_BUCKET:-$(kubectl get pv -o jsonpath='{.items[?(@.spec.storageClassName=="gcsfusecsi-checkpointing")].spec.csi.volumeHandle}' 2>/dev/null || true)}"
    kubectl delete jobset -l kueue.x-k8s.io/queue-name=a4 --ignore-not-found || true
    kubectl delete job qwen3-data-prep --ignore-not-found || true
    if [[ -n "${TRAINING_BUCKET}" ]]; then
      gcloud storage rm --recursive "gs://${TRAINING_BUCKET}/dataset" "gs://${TRAINING_BUCKET}/tokenizer" || true
    fi
    if [[ -n "${CHECKPOINT_BUCKET}" ]]; then
      gcloud storage rm --recursive "gs://${CHECKPOINT_BUCKET}/qwen3-30b-a3b" "gs://${CHECKPOINT_BUCKET}/data-cache" "gs://${CHECKPOINT_BUCKET}/tb-logs" || true
    fi
  2. From the cluster-toolkit directory, destroy the GKE cluster and its associated infrastructure by using the gcluster destroy command:

    ./gcluster destroy "${CLUSTER_NAME:?}" --robust --auto-approve

    Destroying the cluster takes about 10 to 13 minutes to finish.

  3. Delete the Cloud Storage bucket that stores the Terraform state:

    gcloud storage rm --recursive "gs://${BUCKET_NAME:?}"

What's next