AI Job Orchestration III: KubeRay and Distributed Python Workloads
Inside KubeRay: how RayCluster, RayJob, RayService, Plasma zero-copy memory, and Placement Groups orchestrate distributed Python for RLHF and LLM serving.

Series: Part 24 of GPU Architecture, Scale-Up Interconnects, and AI Datacenter Infrastructure Series | (Previous) AI Job Orchestration II: Kubernetes, NVIDIA GPU Operator, and Volcano / Kueue | (Next) AI Job Orchestration IV: Enterprise Schedulers, Multi-Cloud Brokering & MLOps (NVIDIA Run:ai / KAI, Kubeflow, SkyPilot, and MLflow)
Summary
Modern frontier AI workloads have outgrown homogeneous, static batch scripts. While pre-training a dense transformer fits neatly onto a uniform grid of identical GPUs running synchronous torchrun processes, post-training pipelines like RLHF and GRPO, petabyte-scale multimodal data curation, and multi-engine LLM serving demand dynamic, heterogeneous, actor-based distributed Python. In this post, we explore how Ray and the KubeRay Operator bridge the gap between Kubernetes infrastructure and Python AI frameworks. We dissect KubeRay’s three core Custom Resource Definitions (RayCluster, RayJob, and RayService), unpack how Ray’s shared-memory Plasma Object Store and zero-copy Apache Arrow eliminate serialization bottlenecks, analyze Placement Groups (STRICT_PACK vs. STRICT_SPREAD) for NVLink co-location versus high-availability serving, and wrap up our three-part orchestration arc with a master showdown matrix comparing Slurm, Kubernetes + Volcano / Kueue, and KubeRay—backed by a zero-dependency Python simulator quantifying an 8.16× end-to-end step speedup from NVLink-aware co-location and Plasma zero-copy handoffs.
Prior Reading Material
Before diving into KubeRay and distributed Python orchestration, these four articles provide essential context on the Kubernetes control plane, RLHF/GRPO post-training mechanics, vLLM serving, and intra-node NVLink fabrics:
- AI Job Orchestration II: Kubernetes, NVIDIA GPU Operator, and Volcano / Kueue: Covers Kubernetes GPU scheduling, Dynamic Resource Allocation (DRA), gang scheduling with Volcano, and multi-tenant quota management with Kueue.
- DeepSeek GRPO Deep-Dive: Group Relative Policy Optimization and Rule-Based RL: Explains the multi-stage rollout generation, verifiable reward scoring, and policy update loop that drives modern heterogeneous post-training clusters.
- Scale and Performance: Serving LLMs with vLLM and llm-d: Details Kubernetes-native LLM serving with vLLM and disaggregated routing—architectures that pair directly with KubeRay’s
RayService. - Scale-Up Interconnects: NVLink, NVSwitch, and Ultra-High-Bandwidth Node Fabrics: Breaks down the intra-node NVLink fabric that Ray’s
STRICT_PACKPlacement Groups target to keep tensor-parallel collectives off the cluster network.
1. The Rise of Ray for GenAI: Why Static Batch Scripts Break Down
In Parts 22 and 23, we examined how Slurm and Kubernetes (augmented with Volcano and Kueue) carve up massive GPU clusters into gang-scheduled multi-node allocations. That model is ideal when every single worker pod runs the exact same executable, holds the exact same model shard, and marches in lockstep across thousands of training steps.
The moment you move past pure pre-training into post-training, synthetic data pipelines, or agentic serving, that rigid symmetry shatters. Consider what happens inside a single iteration of a modern RLHF, PPO, or GRPO reasoning pipeline:
- Data Curation & Prompt Ingestion (CPU-Heavy): Streaming terabytes of multimodal documents, deduplicating, tokenizing, and filtering on high-core-count CPU nodes without wasting idle H100/B200 GPUs.
- Rollout Generation (Inference-Optimized GPUs): Generating 16 to 64 parallel reasoning trajectories per prompt using high-throughput inference engines like vLLM or SGLang, where continuous batching and paged KV caches dominate performance.
- Reward Verification & Sandboxed Execution (Heterogeneous CPU + GPU): Executing generated code inside isolated CPU sandboxes, running symbolic math verifiers, or querying a separate neural reward model on dedicated GPU actors.
- Policy Optimization (Training-Optimized GPUs): Gathering the scored trajectory groups into a tensor-parallel and FSDP-sharded PyTorch policy trainer, computing gradients, updating weights, and broadcasting fresh weights back to the rollout engines.
Trying to glue those four stages together using raw Kubernetes Job manifests, intermediate object-storage dumps to S3, and ad-hoc HTTP microservices creates massive operational friction. Every stage boundary triggers slow serialization, disk or network I/O stalls, and brittle YAML glue code.
Ray solves this by turning an entire fleet of Kubernetes pods into a single, unified distributed Python runtime. Instead of writing separate containerized microservices for every stage, engineers express stateless functions (@ray.remote) and stateful GPU-resident actors (such as a vLLM rollout engine or a PyTorch FSDP rank) inside one coherent Python program. Ray’s distributed scheduler dynamically places CPU tasks on CPU pods and GPU actors on GPU pods, passes multi-hundred-megabyte tensors between stages in memory, and scales worker pools elastically as pipeline bottlenecks shift.
flowchart TD
A["1. Ray Data CPU Workers<br/>Stream, filter & tokenize prompts (CPU-only pods)"] --> B["2. vLLM / SGLang Rollout Actors<br/>Generate 16 parallel GRPO trajectories per prompt (GPU pods)"]
B --> C["3. Plasma Shared-Memory Object Store<br/>Zero-copy Arrow trajectory buffer in /dev/shm"]
C --> D["4. Reward Verifier Pool<br/>Execute code sandboxes & score completions (CPU + GPU actors)"]
D --> E["5. Tensor-Parallel Policy Trainer<br/>Compute GRPO advantages & update model weights (NVLink GPUs)"]
E --> F["6. In-Memory Weight Sync<br/>Broadcast updated weights back to Rollout Actors for next step"]
style A fill:#0f172a,stroke:#38bdf8,stroke-width:2px,color:#f8fafc
style B fill:#0b2545,stroke:#06b6d4,stroke-width:2px,color:#f8fafc
style C fill:#042f2e,stroke:#14b8a6,stroke-width:2px,color:#f8fafc
style D fill:#1e1b4b,stroke:#8b5cf6,stroke-width:2px,color:#f8fafc
style E fill:#0d2b45,stroke:#3b82f6,stroke-width:2px,color:#f8fafc
style F fill:#062e26,stroke:#10b981,stroke-width:2px,color:#f8fafc
Figure 1: End-to-end heterogeneous RLHF/GRPO post-training loop orchestrated inside a single distributed Python Ray cluster on Kubernetes.
2. KubeRay Operator Architecture: RayCluster, RayJob, and RayService
While Ray manages Python-level tasks, actors, and object memory, it still needs a reliable infrastructure layer to provision containers, mount GPU devices via the NVIDIA GPU Operator, attach high-speed InfiniBand or RoCEv2 NICs, and enforce multi-tenant cluster boundaries. That bridge is the KubeRay Operator—an official Kubernetes controller that reconciles Ray’s distributed runtime through three purpose-built Custom Resource Definitions (CRDs).
Figure 2: Architectural comparison of KubeRay’s three core CRDs—RayCluster, RayJob, and RayService—and their target GenAI production lifecycles. Source: KubeRay Official Documentation.
RayCluster: The Foundational Compute Topology
A RayCluster CRD declaratively defines one Head Pod and one or more Worker Groups:
- Head Pod & Global Control Store (GCS): The head pod runs the GCS—Ray’s central metadata server that tracks active nodes, actor locations, Placement Groups, and the Ray Dashboard. Crucially, the GCS stays off the high-bandwidth data path; worker-to-worker tensor transfers happen peer-to-peer.
- Heterogeneous Worker Groups: A single
RayClustercan declare acpu-data-workersgroup (e.g., 64 vCPU, 0 GPUs, cheap spot instances) alongside agpu-h100-workersgroup (8× H100 GPUs per pod with/dev/shmmounted for Plasma). - Autoscaler Integration: When a Python script requests 32 GPUs that are not yet present, Ray’s built-in autoscaler patches the
RayClusterspec directly, instructing KubeRay to spin up additional Kubernetes worker pods—and scales them back down when idle.
RayJob: Ephemeral Training, RLHF, and Batch Lifecycle
Leaving interactive RayCluster pods sitting idle after a 6-hour post-training run finishes is one of the fastest ways to burn a datacenter budget. The RayJob CRD wraps a RayCluster with a declarative job submission and automatic teardown lifecycle:
- KubeRay provisions the
RayClusterdefined inrayClusterSpec. - Once the head pod reports healthy, KubeRay submits the Python
entrypoint(for example,python train_grpo.py --rollouts 16) via the Ray Jobs API. - Upon completion (success or failure), setting
shutdownAfterJobFinishes: truecauses KubeRay to immediately delete the worker and head pods, returning every GPU to the cluster pool.
Even better, RayJob integrates natively with Kueue (covered in Part 23). By labeling a RayJob with kueue.x-k8s.io/queue-name, Kueue holds the entire RayJob in a suspended state until the full multi-node CPU+GPU quota is guaranteed available—preventing partial-allocation deadlocks across multi-tenant teams.
# Example: manifests/grpo_rayjob.yaml (applied via `kubectl apply -f manifests/grpo_rayjob.yaml`)
apiVersion: ray.io/v1
kind: RayJob
metadata:
name: grpo-reasoning-posttrain
labels:
kueue.x-k8s.io/queue-name: ml-team-gpu-queue
spec:
shutdownAfterJobFinishes: true
entrypoint: python scripts/run_grpo_pipeline.py --group-size 16 --tp-size 4
rayClusterSpec:
rayVersion: "2.40.0"
headGroupSpec:
rayStartParams:
num-gpus: "0"
template:
spec:
containers:
- name: ray-head
image: rayproject/ray-ml:2.40.0-py311-gpu
resources:
limits: { cpu: "8", memory: "32Gi" }
workerGroupSpecs:
- groupName: h100-gpu-workers
replicas: 4
template:
spec:
containers:
- name: ray-worker
image: rayproject/ray-ml:2.40.0-py311-gpu
resources:
limits: { cpu: "64", memory: "512Gi", "nvidia.com/gpu": "8" }
volumeMounts:
- mountPath: /dev/shm
name: dshm
volumes:
- name: dshm
emptyDir: { medium: Memory, sizeLimit: 128Gi }
RayService: Zero-Downtime LLM Serving & HA Control Plane
For online production inference—such as serving multi-model agentic pipelines, disaggregated prefill/decode pools, or multi-engine vLLM / SGLang deployments—KubeRay provides RayService, which manages Ray Serve applications on top of RayCluster:
- Zero-Downtime Blue/Green Upgrades: When you update a container image, CUDA driver, or Ray version, KubeRay does not perform an in-place rolling restart that drops live inference streams. Instead, it spins up a brand-new pending
RayCluster, deploys the Ray Serve application graph, waits for all model weights to load into HBM and pass health checks, and atomically flips the KubernetesServiceselector from the old cluster to the new one. - Fractional GPU Allocation: Unlike standard Kubernetes device plugins that expose GPUs strictly as whole integers (
nvidia.com/gpu: 1), Ray Serve lets lightweight auxiliary actors—like embedding models, safety classifiers, or rerankers—declare fractional logical allocations (for example,num_gpus=0.25) to cleanly pack four small models onto a single physical GPU without MIG reconfiguration. - High-Availability GCS Fault Tolerance: By default, if a Ray head pod crashes, cluster metadata disappears. In production
RayServicedeployments, enabling GCS Fault Tolerance backs the head node’s GCS with an external Redis cluster (RAY_GCS_STORAGE=redis). If the head pod gets evicted or OOM-killed, existing vLLM worker pods continue serving live traffic uninterrupted while Kubernetes spins up a replacement head pod that seamlessly recovers cluster state from Redis.
Self-Hosted KubeRay vs. Managed Ray (Anyscale)
Once teams commit to Ray for post-training or LLM serving, they hit a classic build-vs-buy fork: operate open-source KubeRay on their own Kubernetes clusters, or adopt Anyscale—the managed Ray platform built by the creators of Ray.
| Dimension | Self-Hosted Open-Source KubeRay | Managed Ray (Anyscale) |
|---|---|---|
| Control Plane & Ops | You own KubeRay operator upgrades, external Redis/GCS HA, Prometheus/Grafana dashboards, and autoscaler tuning | Fully managed control plane with built-in Workspaces, Jobs, Services UI, and centralized log/metric observability |
| Deployment Footprint | Runs on any self-managed EKS, GKE, AKS, or bare-metal on-prem Kubernetes cluster | Supports BYOC (Bring Your Own Cloud) inside your own AWS/GCP/Azure VPC or existing Kubernetes cluster |
| Runtime Performance | Standard open-source Ray runtime | Includes RayTurbo optimizations (accelerated Ray Data pipelines, faster Ray Serve autoscaling, and smart spot-instance recovery) |
| Cost & Flexibility | Zero platform markup; direct integration with custom Kueue / Volcano policies and air-gapped on-prem GPUs | Platform fee on top of cloud compute, offset by reduced platform-engineering headcount and faster time-to-production |
In practice, hyperscale labs with dedicated Kubernetes infrastructure teams and bare-metal GPU fleets typically self-host KubeRay + Kueue, while fast-moving AI startups and enterprise ML teams on AWS/GCP often choose Anyscale BYOC so researchers get elastic multi-node Ray Workspaces and zero-downtime Services without maintaining an internal KubeRay control plane.
3. Distributed Memory & Scheduling: Plasma, Zero-Copy Arrow, and Placement Groups
Provisioning pods is only half the orchestration problem. Once a heterogeneous RLHF pipeline or multi-node LLM deployment is live, two runtime mechanisms determine whether your GPUs stay saturated at 90%+ utilization or stall waiting on CPUs and network sockets: how data moves between actors and where actors physically land.
Plasma Shared-Memory Object Store & Zero-Copy Apache Arrow
In traditional Python microservice or RPC architectures, passing a 512 MB batch of tokenized rollouts or embeddings from a rollout worker to a reward verifier triggers a punishing chain of copies: Python’s pickle serializer walks the object graph on a single CPU core (often bottlenecked near 1.5–2.0 GB/s), copies bytes into kernel socket buffers, pushes them across TCP/HTTP, and forces every receiving process to allocate duplicate RAM and deserialize the entire payload back into Python objects.
Ray eliminates this bottleneck using its distributed Plasma Object Store, backed by Linux shared memory (/dev/shm, which we explicitly sized to 128Gi in our RayJob YAML above):
- Immutable Shared Buffers: When an actor calls
ray.put(batch)or returns a large NumPy array or Apache Arrow table, Ray writes the data once into the local node’s Plasma shared-memory segment as an immutable, read-only buffer and returns a tiny 28-byteObjectRefpointer. - Zero-Copy
mmapDeserialization: When co-located actors on the same Kubernetes node callray.get(ref), they do not copy a single byte. Ray memory-maps (mmap) the exact same physical/dev/shmpages directly into each worker process’s virtual address space. Apache Arrow’s standardized columnar memory layout guarantees that Python, PyTorch, and C++ workers can read tensors and tables straight out of shared memory with sub-millisecond pointer-handoff latency and zero RAM duplication. - Automatic Cross-Node Transfer & Spilling: If a downstream consumer runs on a different physical node, Ray’s Object Manager automatically streams the serialized Arrow IPC frames peer-to-peer across the cluster fabric (and spills cold objects to local NVMe SSDs if
/dev/shmfills up).
Figure 3: Contrasting cross-pod Python pickle/HTTP serialization against Ray’s Plasma /dev/shm shared-memory store with Apache Arrow zero-copy memory mapping. Source: Ray Core & Apache Arrow Documentation.
Placement Groups: Packing for NVLink vs. Spreading for Fault Tolerance
Plasma zero-copy reads and intra-node NVLink collectives only deliver their full hardware potential if cooperating actors actually land on the same physical node. Conversely, if you are serving a production LLM API with four vLLM replicas, landing all four replicas on a single host creates a catastrophic single point of failure.
Ray gives developers fine-grained, gang-scheduled topology control directly in Python via Placement Groups. A Placement Group reserves an atomic set of resource “bundles” (for example, four bundles of {"GPU": 1, "CPU": 8}) across the cluster using one of four scheduling strategies:
Figure 4: Ray Placement Group strategies illustrating the fundamental trade-off between strict NVLink/Plasma locality (STRICT_PACK) and strict fault-domain isolation (STRICT_SPREAD). Source: Ray Core Scheduling Documentation.
Notice how real-world GenAI pipelines deliberately combine these strategies inside a single cluster:
- Inside a Tensor-Parallel vLLM Engine or RLHF Trainer (
STRICT_PACK): A 70B+ parameter model split across 4 or 8 GPUs performs frequent All-Reduce synchronizations at every transformer layer. UsingSTRICT_PACKguarantees all 4 or 8 GPU actors share one physical NVLink/NVSwitch domain (900 GB/s bidirectional on Hopper/Blackwell nodes) rather than silently spilling across a 50 GB/s inter-node NIC. - Across Independent
RayServiceInference Replicas (STRICT_SPREAD): While each individual TP=4 replica packs its 4 GPUs onto one host, the outerRayServicespreads multiple replicas across distinct physical nodes and availability zones so a single host failure or kernel panic leaves 75%+ of serving capacity untouched.
4. Master Orchestration Showdown Matrix: Slurm vs. Kubernetes + Volcano/Kueue vs. KubeRay
Across Parts 22, 23, and 24, we have examined the three dominant pillars of modern AI cluster orchestration. Rather than viewing them as mutually exclusive rivals, frontier AI labs increasingly layer them together according to workload physics.
| Dimension | Slurm (Part 22) | Kubernetes + Volcano / Kueue (Part 23) | KubeRay / Ray on Kubernetes (Part 24) |
|---|---|---|---|
| Core Abstraction | Bare-metal jobs, MPI ranks, static node allocations | Containers, Pods, CRDs, multi-tenant queues | Distributed Python tasks, stateful Actors, ObjectRefs |
| Primary Superpower | Ultra-low-overhead, deterministic 10,000+ GPU gang scheduling | Enterprise cloud-native isolation, self-healing, multi-tenant quota sharing | Heterogeneous CPU+GPU pipelines, dynamic Python workflows, fractional GPUs |
| Data Passing Mechanism | Shared POSIX/Lustre parallel filesystem + NCCL collectives | Network RPC/gRPC, object storage (S3), or pod-local volumes | Plasma /dev/shm zero-copy Arrow + peer-to-peer Object Manager + NCCL |
| Topology & Locality Control | Native tree/block topology (--switches, NVLink/IB aware) | Topology-aware scheduling via Volcano plugins & DRA | Placement Groups (STRICT_PACK, PACK, SPREAD, STRICT_SPREAD) |
| Autoscaling & Elasticity | Mostly static per-job allocations; slower cloud bursting | HPA/VPA + Karpenter/Cluster Autoscaler at pod/node level | Native workload-aware Ray Autoscaler + KubeRay worker group scaling |
| Online Serving Support | Minimal (batch-first HPC design) | Strong (Deployments, Ingress, Gateway API, llm-d) | Native (RayService blue/green upgrades, Ray Serve multi-model graphs) |
| Best-Fit GenAI Workloads | Massive synchronous LLM pre-training (1,024–32,768+ GPUs) | Multi-tenant ML platforms, CI/CD, mixed enterprise training + inference | RLHF/PPO/GRPO post-training, Ray Data curation, agentic multi-engine serving |
How Frontier Labs Layer Them Together
In production AI factories, you rarely pick just one box from the table above:
- Pattern A — Kubernetes + Kueue + KubeRay (The Cloud-Native AI Standard): Kubernetes owns hardware lifecycle, NVIDIA GPU Operator drivers, network CNI, and security. Kueue sits at the cluster front door enforcing fair-share multi-tenant GPU quotas across teams and admitting entire
RayJobs atomically. Inside each admittedRayJob, KubeRay and Ray orchestrate the heterogeneous RLHF/GRPO Python actors, Plasma zero-copy memory, andSTRICT_PACKNVLink bundles. - Pattern B — Ray Inside Slurm Allocations (The HPC-to-Post-Training Bridge): Labs operating massive bare-metal Slurm superclusters for pre-training often repurpose a slice of their Slurm partition for post-training or synthetic data generation by launching an ephemeral Ray head and worker cluster directly inside a multi-node
sbatchallocation—gaining Ray’s dynamic Python actor model without migrating bare-metal clusters to Kubernetes.
5. Hands-On Simulation: Placement Group Locality & Plasma Zero-Copy Benchmarks
To quantify exactly how much Placement Group co-location and Plasma zero-copy Arrow memory matter in practice, we built a zero-dependency Python 3 analytical simulator (scripts/kuberay_placement_plasma_sim.py).
It models a 4-node × 8-GPU cluster (900 GB/s intra-node NVLink, 64 GB/s host /dev/shm Plasma bandwidth, 50 GB/s inter-node NIC bandwidth, and 1.8 GB/s Python CPU pickle serialization) executing a 4,096-trajectory GRPO post-training iteration (256 prompts × 16 rollouts, handing off 512 MB Arrow batches across two stage boundaries: Rollout -> Reward Verifier -> TP=4 Policy Trainer, with 12 tensor-parallel All-Reduce syncs per update and 145 ms of fixed GPU kernel compute).
Running /usr/bin/python3 contents/blog/0192-ai-job-orchestration-kuberay-distributed-python-workloads/scripts/kuberay_placement_plasma_sim.py produces the exact verified results below:
| Orchestration Strategy | NVLink Locality | Plasma Zero-Copy | Stage Handoff Latency | TP All-Reduce Sync | Total Step Time | Effective Throughput | Speedup |
|---|---|---|---|---|---|---|---|
Unconstrained SPREAD + Pickle/HTTP | 25% | 0% | 1,130.26 ms | 104.57 ms | 1,379.82 ms | 2,968.5 traj/sec | 1.00× |
Ray PACK + Plasma Arrow (Partial) | 75% | 75% | 25.67 ms | 40.81 ms | 211.49 ms | 19,367.7 traj/sec | 6.52× |
Ray STRICT_PACK + Plasma Zero-Copy | 100% | 100% | 16.53 ms | 7.50 ms | 169.03 ms | 24,233.1 traj/sec | 8.16× |
And for the complementary RayService Inference Availability Check (4 replicas across 4 physical nodes when 1 node suffers a hardware failure):
| RayService Replica Strategy | Surviving Replicas (1 Node Down) | Retained Serving Capacity |
|---|---|---|
STRICT_PACK (All 4 replicas on 1 node) | 0 / 4 | 0% (Complete outage) |
STRICT_SPREAD (1 replica per node) | 3 / 4 | 75% (Graceful degradation) |
Two engineering takeaways jump straight out of these numbers:
- CPU Serialization Is the Silent GPU Killer: In the unconstrained baseline, two 512 MB Python pickle/HTTP stage handoffs consume 1,130.26 ms—nearly 8× longer than the actual 145 ms of GPU compute. Switching to Plasma
/dev/shmwith Apache Arrow zero-copymmapslashes handoff time by ~68× (down to 16.53 ms). - Co-Location vs. Anti-Affinity Depends Strictly on Workload Coupling: Enforcing
STRICT_PACKcuts tensor-parallel All-Reduce time from 104.57 ms down to 7.50 ms (unlocking an 8.16× total pipeline speedup), whereas productionRayServiceinference replicas must use the exact opposite strategy (STRICT_SPREAD) to preserve 75% serving capacity during a host failure.
Click to expand runnable code script
#!/usr/bin/env python3
"""
KubeRay Placement Group & Plasma Zero-Copy Object Store Simulator.
File: scripts/kuberay_placement_plasma_sim.py
Run: python3 scripts/kuberay_placement_plasma_sim.py
Models a heterogeneous RLHF/GRPO post-training pipeline (Rollout Generation ->
Reward Verification -> Tensor-Parallel Policy Update) across a 4-node GPU cluster,
comparing:
1. Unconstrained SPREAD + Cross-Node Pickle/HTTP Serialization
2. Ray PACK + Plasma Shared Memory (Partial Locality)
3. Ray STRICT_PACK Placement Group + Plasma Zero-Copy Apache Arrow (NVLink Domain)
Also validates RayService STRICT_SPREAD vs. STRICT_PACK availability under single-node failure.
Zero external dependencies (Python 3 standard library only).
"""
from dataclasses import dataclass
from typing import Dict, List
@dataclass(frozen=True)
class ClusterSpec:
num_nodes: int = 4
gpus_per_node: int = 8
nvlink_bw_gbps: float = 900.0 # Intra-node NVLink aggregate BW (GB/s)
inter_node_bw_gbps: float = 50.0 # Inter-node InfiniBand/RoCEv2 per-NIC BW (GB/s)
plasma_shm_bw_gbps: float = 64.0 # Host /dev/shm memory copy BW (GB/s)
pickle_ser_bw_gbps: float = 1.8 # Python CPU pickle serialize/deserialize rate (GB/s)
arrow_mmap_latency_ms: float = 0.45 # Constant zero-copy mmap pointer handoff overhead (ms)
network_rtt_ms: float = 0.12 # Base inter-node RPC RTT (ms)
@dataclass(frozen=True)
class WorkloadSpec:
prompts_per_iter: int = 256
rollouts_per_prompt: int = 16 # GRPO group size = 16 -> 4,096 trajectories/iter
payload_mb_per_stage: float = 512.0 # Arrow trajectory batch handed off between stages (MB)
handoff_stages: int = 2 # Rollout -> Reward Verifier -> Policy Trainer
tp_allreduce_mb: float = 384.0 # Tensor-parallel activation sync per micro-step (MB)
tp_collectives_per_iter: int = 12 # Number of TP syncs per policy update step
compute_time_ms: float = 145.0 # Fixed GPU kernel compute time per iteration (ms)
iterations: int = 10
@dataclass
class SimulationResult:
strategy_name: str
nvlink_locality_pct: float
plasma_zero_copy_pct: float
handoff_latency_ms: float
tp_collective_ms: float
total_step_ms: float
throughput_traj_per_sec: float
speedup_vs_baseline: float = 1.0
def simulate_pipeline(
cluster: ClusterSpec,
workload: WorkloadSpec,
strategy_name: str,
local_handoff_ratio: float,
use_plasma_arrow: bool,
nvlink_tp_ratio: float,
) -> SimulationResult:
"""Deterministic analytical simulation of one RLHF/GRPO orchestration configuration."""
payload_gb = workload.payload_mb_per_stage / 1024.0
allreduce_gb = workload.tp_allreduce_mb / 1024.0
total_trajectories = workload.prompts_per_iter * workload.rollouts_per_prompt
total_handoff_ms = 0.0
total_tp_ms = 0.0
for _ in range(workload.iterations):
# 1. Stage-to-stage trajectory batch handoffs (Rollout -> Reward -> Trainer)
iter_handoff_ms = 0.0
for _stage in range(workload.handoff_stages):
local_gb = payload_gb * local_handoff_ratio
remote_gb = payload_gb * (1.0 - local_handoff_ratio)
if use_plasma_arrow:
# Local actor reads via zero-copy mmap from /dev/shm Plasma store
if local_gb > 0:
write_ms = (local_gb / cluster.plasma_shm_bw_gbps) * 1000.0
iter_handoff_ms += write_ms + cluster.arrow_mmap_latency_ms
# Remote overflow uses Ray Object Manager over RDMA/TCP (Arrow IPC framing)
if remote_gb > 0:
ipc_ms = (remote_gb / (cluster.plasma_shm_bw_gbps * 0.5)) * 1000.0
net_ms = (remote_gb / cluster.inter_node_bw_gbps) * 1000.0 + cluster.network_rtt_ms
iter_handoff_ms += ipc_ms + net_ms
else:
# Traditional Python pickle serialize -> network/socket transfer -> deserialize
ser_deser_ms = 2.0 * (payload_gb / cluster.pickle_ser_bw_gbps) * 1000.0
net_ms = (remote_gb / cluster.inter_node_bw_gbps) * 1000.0 + cluster.network_rtt_ms
local_copy_ms = (local_gb / cluster.plasma_shm_bw_gbps) * 1000.0
iter_handoff_ms += ser_deser_ms + net_ms + local_copy_ms
total_handoff_ms += iter_handoff_ms
# 2. Tensor-Parallel All-Reduce collectives inside Policy Trainer
ring_factor = 1.5 # 2*(TP-1)/TP for TP=4
effective_gb = allreduce_gb * ring_factor * workload.tp_collectives_per_iter
nvlink_gb = effective_gb * nvlink_tp_ratio
fabric_gb = effective_gb * (1.0 - nvlink_tp_ratio)
iter_tp_ms = (
(nvlink_gb / cluster.nvlink_bw_gbps) * 1000.0
+ (fabric_gb / cluster.inter_node_bw_gbps) * 1000.0
+ (workload.tp_collectives_per_iter * cluster.network_rtt_ms if fabric_gb > 0 else 0.0)
)
total_tp_ms += iter_tp_ms
avg_handoff_ms = total_handoff_ms / workload.iterations
avg_tp_ms = total_tp_ms / workload.iterations
avg_step_ms = workload.compute_time_ms + avg_handoff_ms + avg_tp_ms
throughput = total_trajectories / (avg_step_ms / 1000.0)
return SimulationResult(
strategy_name=strategy_name,
nvlink_locality_pct=nvlink_tp_ratio * 100.0,
plasma_zero_copy_pct=(local_handoff_ratio * 100.0) if use_plasma_arrow else 0.0,
handoff_latency_ms=avg_handoff_ms,
tp_collective_ms=avg_tp_ms,
total_step_ms=avg_step_ms,
throughput_traj_per_sec=throughput,
)
def simulate_inference_availability(num_nodes: int = 4, num_replicas: int = 4) -> Dict[str, Dict[str, float]]:
"""Compares RayService replica survival when 1 physical Kubernetes node fails."""
pack_surviving = 0
spread_surviving = num_replicas - (num_replicas // num_nodes)
return {
"STRICT_PACK (1 node)": {
"replicas_surviving": pack_surviving,
"capacity_retained_pct": (pack_surviving / num_replicas) * 100.0,
},
"STRICT_SPREAD (4 nodes)": {
"replicas_surviving": spread_surviving,
"capacity_retained_pct": (spread_surviving / num_replicas) * 100.0,
},
}
def main() -> None:
cluster = ClusterSpec()
workload = WorkloadSpec()
scenarios: List[SimulationResult] = [
simulate_pipeline(
cluster=cluster,
workload=workload,
strategy_name="Unconstrained SPREAD + Pickle/HTTP",
local_handoff_ratio=0.25,
use_plasma_arrow=False,
nvlink_tp_ratio=0.25,
),
simulate_pipeline(
cluster=cluster,
workload=workload,
strategy_name="Ray PACK + Plasma Arrow (Partial)",
local_handoff_ratio=0.75,
use_plasma_arrow=True,
nvlink_tp_ratio=0.75,
),
simulate_pipeline(
cluster=cluster,
workload=workload,
strategy_name="Ray STRICT_PACK + Plasma Zero-Copy",
local_handoff_ratio=1.00,
use_plasma_arrow=True,
nvlink_tp_ratio=1.00,
),
]
baseline_step = scenarios[0].total_step_ms
for res in scenarios:
res.speedup_vs_baseline = baseline_step / res.total_step_ms
print("=== KubeRay RLHF/GRPO Placement Group & Plasma Object Store Simulation ===")
print(f"Cluster: {cluster.num_nodes} nodes x {cluster.gpus_per_node} GPUs | "
f"NVLink: {cluster.nvlink_bw_gbps:.0f} GB/s | Inter-Node: {cluster.inter_node_bw_gbps:.0f} GB/s")
print(f"Workload: {workload.prompts_per_iter * workload.rollouts_per_prompt:,} GRPO trajectories/iter | "
f"{workload.payload_mb_per_stage:.0f} MB/stage handoff x {workload.handoff_stages} stages\n")
header = (
f"{'Orchestration Strategy':<38} | {'NVLink':>7} | {'ZeroCopy':>8} | "
f"{'Handoff':>9} | {'TP Sync':>9} | {'Step Time':>10} | {'Traj/sec':>9} | {'Speedup':>7}"
)
print(header)
print("-" * len(header))
for r in scenarios:
print(
f"{r.strategy_name:<38} | {r.nvlink_locality_pct:>6.0f}% | {r.plasma_zero_copy_pct:>7.0f}% | "
f"{r.handoff_latency_ms:>7.2f}ms | {r.tp_collective_ms:>7.2f}ms | "
f"{r.total_step_ms:>8.2f}ms | {r.throughput_traj_per_sec:>9,.1f} | {r.speedup_vs_baseline:>6.2f}x"
)
print("\n=== RayService Inference Availability Under Single-Node Failure (4 Replicas / 4 Nodes) ===")
avail = simulate_inference_availability(num_nodes=4, num_replicas=4)
for strat, metrics in avail.items():
print(
f" {strat:<26} -> Surviving Replicas: {metrics['replicas_surviving']}/4 "
f"({metrics['capacity_retained_pct']:.0f}% serving capacity retained)"
)
if __name__ == "__main__":
main()
6. What’s Next in the Series
We have now traced the complete hardware and orchestration stack of a modern AI factory—from transistors and Tensor Cores, up through HBM memory hierarchies, NVLink/NVSwitch domains, InfiniBand and Ethernet scale-out fabrics, megawatt liquid-cooled datacenters, and finally Slurm, Kubernetes, and KubeRay orchestration.
In Part 25: AI Job Orchestration IV: Enterprise Schedulers, Multi-Cloud Brokering & MLOps (NVIDIA Run:ai / KAI, Kubeflow, SkyPilot, and MLflow), we zoom up one layer to the enterprise and multi-cloud control plane—unpacking fractional GPU slicing and hierarchical quotas with NVIDIA Run:ai (KAI Scheduler), structured PyTorchJob pipelines with Kubeflow, multi-cloud GPU brokering and spot recovery with SkyPilot, and experiment/model lineage with MLflow before wrapping up the series in Part 26: Supercluster Reliability & Telemetry.
7. Frequently Asked Questions (FAQs)
1. Does KubeRay replace Kubernetes schedulers like Kueue or Volcano?
Answer
No—KubeRay operates one layer above them and is designed to compose directly with both. Kueue handles cluster-wide multi-tenant admission, priority preemption, and quota borrowing by holding a `RayJob` suspended until the full cluster capacity is free. Once admitted, KubeRay reconciles the `RayCluster` pods, and Ray's internal scheduler orchestrates fine-grained Python tasks, actors, fractional GPUs, and Placement Groups inside those pods.2. Why is mounting a large /dev/shm volume critical for GPU pods in KubeRay?
Answer
By default, Docker and Kubernetes cap a container's `/dev/shm` shared-memory filesystem at just 64 MB. Because Ray's Plasma Object Store places immutable Apache Arrow and NumPy buffers directly in `/dev/shm` for zero-copy `mmap` reads—and NCCL also uses `/dev/shm` for intra-node shared-memory communication—leaving `/dev/shm` at 64 MB forces immediate disk spilling or crashes. Production KubeRay GPU pods should explicitly mount an `emptyDir` volume with `medium: Memory` sized to 30%–50% of pod RAM.3. When should I use STRICT_PACK versus STRICT_SPREAD in Ray Placement Groups?
Answer
Use `STRICT_PACK` whenever actors communicate at high frequency over GPU or host memory—such as tensor-parallel (TP=4 or TP=8) model shards that must stay on the same NVLink/NVSwitch host, or co-located RLHF rollout and trainer workers sharing Plasma zero-copy buffers. Use `STRICT_SPREAD` for independent production serving replicas in a `RayService` so that losing any single physical node never takes down your entire endpoint.4. What happens to live LLM inference traffic if a RayService head pod crashes?
