Distributed ML Training on Kubernetes: Ray Operator & NVIDIA GPU Operator
Production guide to orchestrating distributed deep learning training clusters on AWS EKS using KubeRay, PyTorch Distributed Data Parallel (DDP), and the NVIDIA GPU Operator.
Distributed ML Training on Kubernetes: Ray Operator & NVIDIA GPU Operator
Section titled βDistributed ML Training on Kubernetes: Ray Operator & NVIDIA GPU OperatorβTraining modern deep learning models, computer vision networks, and large language models requires massive compute that exceeds the memory and processing power of a single GPU or physical server.
Platform engineers must orchestrate distributed training clusters that scale dynamically across dozens of multi-GPU nodes. On Kubernetes, the industry-standard architecture pairs the NVIDIA GPU Operator for host-level hardware virtualization with Ray (KubeRay) and PyTorch Distributed Data Parallel (DDP) for elastic job orchestration.
1. Kubernetes Hardware Virtualization: NVIDIA GPU Operator
Section titled β1. Kubernetes Hardware Virtualization: NVIDIA GPU OperatorβKubernetes cannot schedule GPUs out of the box. Installing NVIDIA drivers, container toolkits, and monitoring daemons manually on every worker node causes driver version mismatches and cluster instability during node upgrades.
The NVIDIA GPU Operator automates the entire GPU lifecycle using Kubernetes DaemonSets:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ Kubernetes Worker Node (e.g. AWS EC2 g5.12xlarge) ββ ββ ββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β NVIDIA GPU Operator DaemonSets β ββ β ββ NVIDIA Driver Container (Kernel Modules) β ββ β ββ NVIDIA Container Toolkit (CRI hooks) β ββ β ββ NVIDIA Device Plugin (Advertises nvidia.com/gpu)β ββ β ββ NVIDIA DCGM Exporter (GPU Prometheus Metrics) β ββ β ββ GPU Feature Discovery (GFD) β ββ ββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β ββ βΌ ββ ββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β Hardware Layer: 4x NVIDIA A10G GPUs (96GB VRAM) β ββ ββββββββββββββββββββββββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββOnce installed via Helm, Kubernetes nodes automatically advertise GPU resources:
# Pod manifest requesting GPU computeresources: limits: nvidia.com/gpu: 2 # Allocates 2 physical GPUs to container2. Distributed Training Frameworks: PyTorch DDP vs Model Parallelism
Section titled β2. Distributed Training Frameworks: PyTorch DDP vs Model ParallelismβWhen scaling deep learning models across multiple GPUs:
| Strategy | When to Use | Mechanism |
|---|---|---|
| Data Parallelism (PyTorch DDP) | Model fits in single GPU memory, but dataset is massive | Every GPU holds a full replica of the model weights. The dataset is split into batches across GPUs; gradients are synchronized via an AllReduce network operation after each backward pass. |
| Tensor Parallelism (TP) | Single layer exceeds GPU VRAM | Matrices are split across GPUs (e.g., Megatron-LM) connected by ultra-fast NVLink. |
| Pipeline Parallelism (PP) | Entire model exceeds single GPU VRAM | Different layers are placed on sequential GPUs (e.g., Layers 1-12 on GPU 0, Layers 13-24 on GPU 1). |
3. Distributed Orchestration with Ray & KubeRay
Section titled β3. Distributed Orchestration with Ray & KubeRayβWhile Kubernetes manages pods, distributed AI workloads require dynamic task scheduling, actor systems, and low-latency shared object memory. Ray is the leading open-source compute engine for distributed AI, and KubeRay provides native Kubernetes Custom Resources (RayCluster, RayJob).
3.1 Production RayJob Manifest on AWS EKS
Section titled β3.1 Production RayJob Manifest on AWS EKSβapiVersion: ray.io/v1kind: RayJobmetadata: name: pytorch-distributed-training-job namespace: mlopsspec: entrypoint: python train_ddp.py --epochs 50 --batch-size 128 shutdownAfterJobFinishes: true ttlSecondsAfterFinished: 600
# Ephemeral Ray Cluster Specification rayClusterSpec: rayVersion: '2.9.3' # 1. Head Node (Coordinates workers and dashboard) headGroupSpec: rayStartParams: dashboard-host: '0.0.0.0' template: spec: containers: - name: ray-head image: rayproject/ray-ml:2.9.3-py310-gpu resources: requests: cpu: "4" memory: "16Gi" limits: cpu: "8" memory: "32Gi"
# 2. Worker Group (Multi-GPU Compute Nodes) workerGroupSpecs: - groupName: gpu-training-workers replicas: 4 minReplicas: 1 maxReplicas: 8 rayStartParams: {} template: spec: # Toleration to run on Karpenter/EKS GPU Spot nodes tolerations: - key: "nvidia.com/gpu" operator: "Exists" effect: "NoSchedule" nodeSelector: node.kubernetes.io/instance-type: "g5.4xlarge" containers: - name: ray-worker image: rayproject/ray-ml:2.9.3-py310-gpu resources: requests: cpu: "14" memory: "56Gi" nvidia.com/gpu: "1" limits: cpu: "16" memory: "64Gi" nvidia.com/gpu: "1"4. PyTorch Distributed Data Parallel (DDP) Code Example
Section titled β4. PyTorch Distributed Data Parallel (DDP) Code ExampleβWhen running inside the Ray cluster, PyTorch initializes the distributed process group over the high-speed Kubernetes network:
import osimport torchimport torch.distributed as distimport torch.nn as nnfrom torch.nn.parallel import DistributedDataParallel as DDPfrom torch.utils.data.distributed import DistributedSampler
def setup_distributed(): """Initializes PyTorch distributed process group using NCCL backend.""" dist.init_process_group( backend="nccl", # NVIDIA Collective Communications Library for GPU interconnect init_method="env://" ) local_rank = int(os.environ["LOCAL_RANK"]) torch.cuda.set_device(local_rank) return local_rank
def train(): local_rank = setup_distributed()
# Wrap model with DDP model = nn.Linear(1024, 10).to(local_rank) ddp_model = DDP(model, device_ids=[local_rank])
# DistributedSampler ensures every GPU gets a non-overlapping slice of data sampler = DistributedSampler(train_dataset, shuffle=True) dataloader = DataLoader(train_dataset, batch_size=64, sampler=sampler)
for epoch in range(10): sampler.set_epoch(epoch) for inputs, targets in dataloader: inputs, targets = inputs.to(local_rank), targets.to(local_rank) outputs = ddp_model(inputs) loss = criterion(outputs, targets)
optimizer.zero_grad() loss.backward() # NCCL automatically synchronizes gradients across all GPUs optimizer.step()
dist.destroy_process_group()5. Production SRE & FinOps Best Practices for GPU Clusters
Section titled β5. Production SRE & FinOps Best Practices for GPU Clustersβ- Leverage EC2 Spot Instances with Karpenter: GPU training jobs that support checkpointing (saving model weights every epoch to S3) can run on AWS EC2 Spot instances, cutting compute bills by up to 70%.
- Monitor GPU Saturation via DCGM: Track
DCGM_FI_DEV_GPU_UTILandDCGM_FI_DEV_MEM_COPY_UTILin Prometheus. If GPU utilization drops below 80%, your training script is bottle-necked on data loading I/O, not compute. - Use Shared High-Throughput Storage: Standard EBS volumes cannot feed multi-node GPU clusters at wire speed. Mount Amazon FSx for Lustre or S3 Express One Zone to eliminate data loading stalls.