Ray turns Python functions and classes into tasks and actors scheduled across a cluster; their results are immutable objects kept in each node's shared-memory store, and every object has an owner, the worker that created it, which counts its references, knows where its copies are and decides whether it can be rebuilt after a failure.
Fig. 1, step by step: one call, y = f.remote(x), on the cluster every number on this page came from measured
src/data/README.md). The head offers 0 CPUs, so no task runs there; it holds the GCS (cluster metadata and node health checks) and your driver. Each worker, w1 and w2, offers 2 CPUs, an 80 MB object store and 2 fake_gpu (a custom resource Ray counts and hands out, not a device); every node runs a raylet. Idle memory from docker stats: head 692 MB of a 2,000 MB cap, workers 244 and 243 MB of 1,100 MB.y, becomes its owner and writes its table: 1 reference, no location yet, and the lineage, the task f(x), to re-run if every copy is lost.x, its object manager pulls one first.y is; w2's raylet pulls a copy into its own store, and that copy serves every reader on w2. Measured with a 16 MB object: the first read on w2 took 0.42 s, the second 5 ms.y: the owner tells both stores to free their copies and forgets the lineage.The owner's table in the driver is the only record of y's references, copies and lineage. Message order from the Ownership paper and Ray's architecture whitepaper; no timings are drawn per message because none were measured. Ray Train, Data, Serve and Tune are libraries built from these pieces; the machines underneath come from Kubernetes or Slurm. Positions are schematic.
Where it sits. Slurm and Kubernetes hand out machines to jobs (the root page's Scheduling lab compares them). Ray runs inside machines you already have, usually Kubernetes pods (KubeRay) or a Slurm allocation, and schedules the tasks of one program across them. It is not a rival to Slurm for "who gets the cluster"; it is the layer that makes one program distributed.
You need: DDP and torch.distributed for the Ray Train section (Distributed PyTorch); the root page's Slurm, Kubernetes and Ray comparison for the cluster layer below.
New terms
All runs: Ray 2.59.0 (PyPI 2026-10-02), torch 2.14.1 CPU, 2026-10-16, scripts in src/scripts/ (ry_core.py tasks, actors, objects, spilling, failures and a node loss; ry_data.py Ray Data; ry_train.py Ray Train with its checkpoint API), raw output scrubbed in src/runs/. Timings are measured on Apple M1 Pro, Docker Desktop VM, shared machine: rough, useful for ratios and orders of magnitude, not as cluster numbers. Placements, counts, error types, messages and event orders are deterministic and transfer to a real cluster. Ray source is quoted at tag ray-2.59.0 (commit dd83c3a), file and line, located by pattern in src/scripts/ry_quotes.py; Ray Serve defaults were read from the same tag on 2026-10-24. The head was given a 2,000 MB cap, 500 MB more than the shared setup's 1,500 MB (see Processes). Process sizes are resident memory (RSS) read from /proc, which double-counts shared pages. The containers share a Docker bridge network and a volume mounted at /shared on all three. Ray runs in Linux containers because it refuses a multi-node cluster on macOS ("Multi-node Ray clusters are not supported on Windows and OSX").
ray.get sits decides whether tasks overlap measured@ray.remote registers a function with the cluster. f.remote(x) does not run f: it sends a task description (function, arguments, resource request, by default 1 CPU) to Ray and returns an ObjectRef at once. ray.get(ref) blocks until the result exists; ray.wait(refs) returns the ones that are ready. Because .remote() returns immediately, you submit many tasks before waiting for any: that is where the parallelism comes from.
From src/scripts/ry_core.py (section tasks), run as the driver on the head:
@ray.remote
def noop():
return socket.gethostname()
# one at a time: submit, wait, repeat (100 times)
for _ in range(100):
ray.get(noop.remote())
# 1,000 at once: submit all, then wait for all
hosts = ray.get([noop.remote() for _ in range(1000)])
measured One tiny task round trip (submit, schedule, run, return) took about 3 ms on this laptop; 1,000 tasks submitted together cost well under 1 ms each, because Ray pipelines them across the 4 worker processes and reuses a leased worker for many tasks. The 1,000 results came from both workers (the split is in the card). The Ownership paper (NSDI 2021, the design Ray implements) reports about 1 ms per task on a real cluster published: the same order.
ray.get([nap.remote(i, 0.5) for i in range(8)]) take, and how long does [ray.get(nap.remote(i, 0.5)) for i in range(8)] take? Answer, then watch the replay.ray.get waits for its task before the next is even submitted, so the eight run one after another: the classic "ray.get in a loop" mistake.The replay, in stretches of the recorded run
.remote() returns at once; four tasks start within 12 ms, one on each worker process (two per worker node).ray.get returns all eight at 1.12 s: two waves of 4 on 4 CPUs.ray.get and has not submitted task 1.Each lane is one worker process (node and pid from the run); each bar is one task, placed where and when it really ran. Same eight tasks, same cluster.
Cost. A task is a scheduling decision, a message and a serialisation: milliseconds, not microseconds. Batch tiny work into fewer, larger tasks. The Ray docs' own example (anti-pattern: too fine-grained tasks published) runs 10,000 calls of a 10-microsecond function: about 0.17 s as plain calls, 1.6 s as one task each, 0.03 s as batches of 1,000 per task.
Check. ray status shows CPUs in use; ray timeline writes a Chrome trace with each task as a bar per worker, as drawn here. Serial bars that should overlap mean a ray.get between submissions.
Tasks forget everything between calls; a model on a GPU, a replay buffer or a simulator must live in one process. @ray.remote on a class makes an actor class: Counter.remote() starts a dedicated worker process, runs __init__ there and returns an actor handle. Calls from one caller run one at a time in submission order (unless you ask for max_concurrency or async methods), so two calls never touch the state at once.
@ray.remote
class Counter:
def __init__(self):
self.n = 0
def incr(self):
self.n += 1
return self.n
c = Counter.remote() # a new process on some node
vals = ray.get([c.incr.remote() for _ in range(1000)]) # 1,000 calls queued, run in order
Fig. 2, step by step: three Counters from ry_core.py measured
Counter.remote() starts a process. Ray placed a dedicated worker process for the actor on w1 in 0.16 s, ran __init__ there (n = 0) and returned a handle.incr calls submitted at once took 0.23 s and returned 101 to 1100: the 1,000 queued calls came back in order (the counter starts above 1 because the 100 single calls ran first).max_restarts=1. A second Counter, on w2 with n at 3, is killed. The call in flight fails with ActorUnavailableError; Ray starts a new process on w1 with a new pid, __init__ runs again, and the next call returns 1: the state is gone.max_restarts=0. A third Counter, on w1, is killed and stays dead: every later call raises ActorDiedError.| Task | Actor | |
|---|---|---|
| State between calls | none | kept in the actor's process |
| Where it runs | any node with free resources, chosen per call | one process, placed once at creation |
| Order of calls | none: tasks run as resources free up | one caller's calls run in submission order |
| Resources held | while running (1 CPU by default) | for its lifetime if it asks for any; by default 1 CPU to place it and 0 while it runs (Ray docs: resources) |
| On a crash | retried 3 times by default (system failures) | not restarted by default; with max_restarts, restarted with fresh state |
| Typical use | preprocessing, scoring, parallel map | model replicas, simulators, rollout workers, Ray Train workers (RayTrainWorker), vLLM engines in RL stacks |
Tasks pass data to each other. Sending every result back through the submitting program would make it the bottleneck, so every node runs an object store (historically Plasma): shared memory, managed by the node's raylet, that every worker on the node can map. A result is stored where its task ran, and:
max_direct_call_object_size = 100 KB (src/ray/common/ray_config_def.h line 274) goes back to the owner inside the reply and never enters a store.object_manager_default_chunk_size, line 432); that copy serves every reader on the node.DEFAULT_OBJECT_STORE_MEMORY_PROPORTION, python/ray/_private/ray_constants.py line 110), capped at 200 GB (line 106); this cluster sets 80 MB per node with --object-store-memory.The stepper: copies per node, read from ray.experimental.get_object_locations after each action measured
NodeAffinitySchedulingStrategy.ray.get on the 1 MB one. Now it has two copies, on w1 and on the head (the driver's node). The array the driver got is read-only (writeable False, owndata False), a view of shared memory: writing to it raised ValueError: assignment destination is read-only.ray.put on a 4 MB array. ray.put stores the value in the store of the caller's node, the head, and the driver owns it.Cost. A cross-node read pays the network once per node, then is free on that node: here the first 16 MB read on the other worker took about 0.4 s and the second about 5 ms (a Docker bridge on a laptop, far below a real 100 to 400 Gb/s fabric; the ratio is the lesson). Passing a big array by value to many tasks stores a fresh copy per call; ray.put it once and pass the ref. (Both were timed; at 4 calls of 8 MB the difference was within this laptop's noise, so no number is quoted.) Check: ray memory lists every reference with its size, owner and why it is alive; --stats-only prints store usage and spill counters.
Past object_spilling_threshold = 0.8 of capacity (ray_config_def.h line 827), the raylet writes objects that are referenced but not in use to local disk through IO worker processes (max_io_workers = 4 per node) and restores them when read. Unreferenced objects are deleted; objects in use cannot be spilled. Only if spilling cannot keep up does a put fail with ObjectStoreFullError (spilling is on by default, automatic_object_spilling_enabled, line 804).
When it matters. Spilling turns an out-of-memory crash into slower progress: right for data pipelines, wrong for a latency-sensitive actor. Its hidden cost showed up later here: the spill and restore IO workers stayed alive (two of each, about 400 MB of resident memory on a 1.1 GB node, src/runs/debug/ps_w1_after_spill.txt), and the next Ray Train run on that node was killed by Ray's memory monitor (Mistakes). ray memory --stats-only printed "Spilled 64 MiB, 8 objects, avg write throughput 212 MiB/s" and "Restored 64 MiB, 8 objects, avg read throughput 1591 MiB/s"; spill throughput that low on a real node means a slow disk: point object_spilling_config (in ray start --system-config) at local NVMe (Ray docs: object spilling).
Once refs are passed between tasks on many nodes, someone must know when an object can be freed, where its copies are and what to do if its node dies; a central table for every object would be a bottleneck at millions of tasks per second. Ray's answer, from the Ownership paper (Wang et al., NSDI 2021): the worker that creates an ObjectRef, by .remote() or ray.put, is its owner, and keeps in its own memory the reference count (borrowers report back to it), the locations of the copies and the lineage, the task that produced it, kept while the object is referenced (lineage_pinning_enabled, line 208) up to max_lineage_bytes = 1 GB per owner (line 224). Fig. 1, at the top of the page, follows one task while the owner's table changes (steps 2, 5 and 7).
Consequences. The driver owns everything it submits. A task that calls ray.put or submits tasks inside its body owns those objects, and they die with that worker even if the data sat on a healthy node. ray.put objects have no lineage (no task made them), so they cannot be rebuilt. Small inline objects live in the owner's memory, so they survive the loss of the node that computed them. Failures, below, shows all four on a real node loss.
Four kinds of process make the cluster in Fig. 1; knowing which holds what is how you read logs and failures.
The Global Control Service (older papers: Global Control Store), gcs_server: the node table, the actor table (where each actor lives, its restarts), placement groups, jobs, a key-value store. It health-checks every raylet and declares nodes dead. It does not hold objects or schedule ordinary tasks.
A scheduler that grants worker leases for this node's resources or points the request elsewhere (spillback), the object store and object manager, and the worker pool that starts and reuses Python workers.
Python processes running tasks and actors. Each embeds a core worker library, which is where ownership lives.
Your script after ray.init(): a worker that owns everything it submits. Here and for Ray Jobs it runs on the head, so the head needs memory for it.
When it matters. The head is a single point of failure and a memory hot spot. The root's Failure lab saw the head at 95% of its 1.5 GB cap during Ray Train runs, and Ray's memory monitor killed 13 non-training worker processes there. On a real cluster: no training on the head (--num-cpus 0, as here), memory for the driver, dashboard and Ray Train's controller, and GCS fault tolerance (Failures, below).
Ray's memory monitor kills workers when a node's memory use passes memory_usage_threshold = 0.95 (ray_config_def.h line 79), checked every 250 ms (line 83). The threshold in bytes is computed once, when the raylet starts (src/ray/common/monitors/threshold_memory_monitor.cc line 33 stores it; line 126 compares against it). After docker update --memory 2000m on the running head, a Ray Train run still died with "Memory usage 1539858432B exceeded threshold of 1494220800B (71.2% of 2097152000B limit)": 1,494,220,800 is 95% of the old 1,500 MiB limit. Raise memory before ray start, or restart Ray after resizing. (This page then ran its head with 2,000 MB from the start, on 2026-10-16.)
Resources are counters. A node advertises numbers (CPU, GPU, memory, any custom name such as fake_gpu); a task or actor asks for amounts (num_cpus=1, num_gpus=0.5, resources={"fake_gpu": 1}) and runs only where they are free. The numbers are for placement, not enforcement: Ray does not stop a task from using more (unlike Slurm with cgroups). On a real GPU node Ray sets CUDA_VISIBLE_DEVICES for the GPUs it assigned; for a custom resource it sets nothing.
Policies. The default hybrid policy prefers the local node until its critical resource passes scheduler_spread_threshold = 0.5 utilisation (ray_config_def.h line 252), then picks randomly among the least-loaded few (src/ray/raylet/scheduling/policy/hybrid_scheduling_policy.h lines 29 to 48: "Scheduling a task on a new node incurs a cold start penalty ... Past a certain utilization threshold, a big noisy neighbor problem occurs"). "SPREAD" spreads; NodeAffinitySchedulingStrategy(node_id, soft) pins to one node (soft: fall back if it is gone).
Placement groups reserve several bundles at once, all or nothing, so a multi-worker job never starts with half its GPUs: Ray's gang scheduling. The GCS reserves them with a two-phase commit across raylets ("The first phase of 2PC ... prepare resources", "The second phase of 2PC", src/ray/gcs/gcs_placement_group_scheduler.h lines 114 and 116). Ray Train puts its worker group in one (ScalingConfig(placement_strategy="PACK") by default).
Each bundle is 1 CPU + 1 fake_gpu, what one Ray Train worker asks for. Placements as recorded by the root's Scheduling lab (src/sched/runs/ray/ray_pg.jsonl in the root's folder, Ray 2.59.0, 2026-10-16). PACK prefers one node but settles for two; SPREAD spreads bundles over nodes, best effort; the STRICT_ variants wait rather than settle: STRICT_PACK needs one node with 4 and STRICT_SPREAD four nodes, so both stayed PENDING (with 2 bundles each, both were created) and the autoscaler printed "Error: No available node types can fulfill resource request ... {'CPU': 4.0, 'fake_gpu': 4.0}". A second group that needed 3 of 4 GPUs waited holding nothing, then got all 3 at once 0.68 s after the first was removed.
Ray handles tasks, actors, objects and nodes differently. Every row below was run on this cluster (ry_core.py fault and lineage); error names and messages are Ray's own.
| What failed | Default behaviour (source) | What happened here |
|---|
max_retries = 3 times when the worker process or node dies (DEFAULT_TASK_MAX_RETRIES = 3, ray_constants.py line 633; ray_option_utils.py line 182). An exception from your code is not retried unless retry_exceptions=True (line 207): a crash is the machine's fault, an exception yours. Retries re-run the function, so tasks should be idempotent.max_restarts = 0, line 254). With max_restarts=N a new process runs __init__ again: the state is gone (the counter went from 3 back to 1 here). Calls in flight fail unless max_task_retries is set (default 0, line 255).OwnerDiedError), and so are ray.put objects whose only copy was on the lost node.health_check_failure_threshold = 5 failed checks, sent every health_check_period_ms = 3,000 ms with a health_check_timeout_ms = 10,000 ms timeout (ray_config_def.h lines 1060 to 1064). Here the first check failed 11.7 s after the node was killed and the node was dead at 29.9 s; the root's Failure lab measured 30.0 s on its own run.Fig. 3 · one node lost, six fates
The node-loss run puts the ownership rule to work: on ray-w2, A an 8 MB task output (driver owns it, retryable), B the same with max_retries=0, C an 8 MB array a task on w2 ray.put itself and returned, D a 1 KB task output (inline), and two actors (max_restarts=1 and the default 0). Then docker kill mi-ray-w2, and the driver asked for each. Predict each fate, then follow Fig. 3.
Fig. 3, step by step: seconds after the kill measured
ray.get(A) is still waiting.max_retries 3): it re-ran the task on w1 at 31.4 s, and ray.get(A) returned after 31.0 s of waiting.ObjectReconstructionFailedError, the owner is alive but may not re-run a max_retries=0 task. C: OwnerDiedError at 41.7 s; its owner was the worker on w2 that called ray.put, and ray.put objects have no lineage anyway.max_restarts=1 the GCS restarted the Counter on w1; __init__ ran again, so the next call returned 1. With the default 0 it is dead: ActorDiedError.Times from the host's clock (kill), the GCS log (health checks, node death), the shared run log (re-executed task) and the driver (each ray.get). The driver asked in order D, A, B, C, then the actors, so B's and C's answers came after A's 31 s wait. The GCS timings are set by its health-check settings and transfer to real clusters. Positions are schematic.
| Thing on the dead node | Owner | Outcome | Why |
|---|
ray.put(big_array) and returns the ref to the driver. Node B dies. The array's only copy was on node C, which is healthy. Can the driver still ray.get it?ray.put; its count and location table died with it. Ray's docs: "Currently, Ray does not support recovery from owner failure", and "Ray will clean up any remaining copies of the object's value to prevent a memory leak" (object fault tolerance). The error reads "The object's owner has exited. This is the Python worker that first created the ObjectRef via .remote() or ray.put()"; measured here with the copy on the killed node itself (object C). Rule: let the driver or a long-lived actor own what you cannot lose; return values from tasks instead of ray.put inside them.The head is the exception: without GCS fault tolerance, losing it loses the cluster. With GCS fault tolerance the GCS writes its tables to an external Redis; when it restarts, raylets and workers reconnect (they wait up to gcs_rpc_server_reconnect_timeout_s = 60 s, line 549) and running tasks and actors continue (Ray docs: GCS fault tolerance; on KubeRay 1.3.0 and later, a gcsFaultToleranceOptions field in the RayCluster spec: KubeRay GCS fault tolerance). not run here: it needs a Redis and a head restart, which teaches little on a toy cluster beyond what the docs state.
Training reads and transforms data while GPUs wait. Inside each training process, preprocessing is tied to the trainer's CPUs; all up front, it needs storage for the whole result and a long wait. A Ray Data Dataset is a lazy plan (read_* or from_items, then map_batches(fn), then a consumer such as iter_batches or a Ray Train worker). Data moves as blocks in the object store, which Ray Data "attempts to bound ... between 1 MiB and 128 MiB" (Ray Data internals; DEFAULT_TARGET_MAX_BLOCK_SIZE, python/ray/data/context.py line 76). The streaming executor runs every operator at once: each "takes in and outputs a stream of blocks", each block is one Ray task (or an actor pool for stateful work such as a model), and the first batch arrives once the first block has passed every stage.
are_remote_args_compatible, python/ray/data/_internal/logical/rules/operator_fusion.py lines 886 to 899: different num_cpus means no fusion).From src/scripts/ry_data.py: the running example's text (TinyShakespeare) in 24 blocks, two pretend stages (0.3 s and 0.2 s per block), a pretend training loop (0.1 s per batch of 512):
ds = ray.data.from_items(items, override_num_blocks=24) ds = ds.map_batches(encode, batch_size=1) # characters to ids # staged: ds = ds.materialize() (finish stage 1 everywhere first) ds = ds.map_batches(window, batch_size=1) # pipelined: num_cpus=0.5 stops fusion for b in ds.iter_batches(batch_size=512, batch_format="numpy"): time.sleep(0.1) # a training step
Predict which plan feeds the training loop first and which finishes last, then watch the three runs.
The three runs, in stretches
FromItems cuts the text into 24 blocks; the first tasks start at 1.02 s.materialize() returns at 4.60 s (red line).measured Same 24 blocks, same 17,424 samples in 35 batches, three plans; lanes are worker processes, the bottom lane the training loop in the driver. Fused: each block is one task running both functions, and training starts as soon as the first blocks are done. Two operators: separate tasks interleave on the same 4 CPUs (window asks for 0.5 CPU) with a store hop between, which cost time here; on a real pipeline you unfuse on purpose when stages need different resources (CPU decode, GPU model). Staged: every encode finishes before any window starts, so training waits for the whole first stage: the bulk-synchronous plan streaming replaced. The shapes are the lesson, not the seconds.
ds.stats()| Mode | Operators reported by ds.stats() | Tasks | Wall time |
|---|
Published claim. The Ray Data paper (Luan et al., The Streaming Batch Model for Efficient and Fault-Tolerant Heterogeneous Execution, 2025-01-16; UC Berkeley and Anyscale, Ray's company) reports "2.5-12x" throughput on heterogeneous batch inference over batch and stream processing systems, and 31% higher training throughput for Stable Diffusion than single-node data loaders published, authors' own measurements. Not reproduced here.
When it matters. Heavy preprocessing, or preprocessing on a different machine type than training (CPU nodes decoding video for GPU trainers), and offline batch inference. For a text run already tokenized into shards, a plain loader is simpler (Storage and loading covers formats and loaders).
Distributed PyTorch needs N processes on the right machines, each told its rank, the world size and rank 0's address, a process group, and someone to restart from a checkpoint when one dies. torchrun does this per node and Slurm or Kubernetes supply machines; Ray Train does all of it inside a Ray cluster, from one call: TorchTrainer(train_loop, scaling_config=ScalingConfig(num_workers=4, ...), run_config=RunConfig(...)).fit().
Fig. 4, step by step: run 1 of the crash test measured
fit() starts a controller. A controller actor (Ray Train v2, the default: RAY_TRAIN_V2_ENABLED defaults to true, python/ray/train/v2/_internal/constants.py line 149) runs on the head and requests a placement group of N bundles ("Requesting resources: {'CPU': 1, 'fake_gpu': 1} * 4"), PACK by default.RayTrainWorker actors, one in each bundle (ranks 0 and 1 on w1, 2 and 3 on w2), and sets MASTER_ADDR, MASTER_PORT, RANK, WORLD_SIZE, LOCAL_RANK. In run 1 the group was running 9.0 s after fit().TorchConfig(backend=...) ("Setting up process group for: env:// [rank=0, world_size=4]"), gloo here, before your loop runs. Then every worker runs your train_loop, and DDP all-reduces the gradients every step. The root's Launch lab has the env dump.ray.train.report(metrics, checkpoint=Checkpoint.from_directory(d)) uploads the checkpoint to storage_path and queues a report. The controller polls the workers every DEFAULT_HEALTH_CHECK_INTERVAL_S = 2.0 s (line 35; controller.py line 436) and registered step 50 at 11.67 s, once it held the report of every worker.FailureConfig: a new worker group from the latest checkpoint, up to max_failures times (default 0: python/ray/air/config.py line 368), or raise. ray.train.get_checkpoint() returns the latest registered one after a restart, step 50: the new group started at 19.02 s and redid 70 steps.Positions are schematic; the times are seconds after fit() in run 1 (runs 2 and 3 below behaved the same).
src/scripts/ry_train.py (the running example on Ray Train's checkpoint API)ck = ray.train.get_checkpoint() # None on the first attempt if ck: with ck.as_directory() as d: st = torch.load(os.path.join(d, "state.pt")) model.load_state_dict(st["model"]); opt.load_state_dict(st["opt"]); start = st["step"] ddp = DistributedDataParallel(model) for step in range(start, steps): ... # forward, backward, AdamW, all-reduce of the loss if done % 50 == 0: with tempfile.TemporaryDirectory() as d: c = None if rank == 0: torch.save({...}, os.path.join(d, "state.pt")); c = Checkpoint.from_directory(d) ray.train.report({"step": done, "gloss": g.item()}, checkpoint=c) TorchTrainer(loop, torch_config=TorchConfig(backend="gloo"), scaling_config=ScalingConfig(num_workers=4, resources_per_worker={"CPU": 1, "fake_gpu": 1}, placement_strategy="PACK"), run_config=RunConfig(storage_path="/shared/results", failure_config=FailureConfig(max_failures=1), checkpoint_config=CheckpointConfig(num_to_keep=2))).fit()
Every rank calls report at step 100 (the second tick on each lane), but no green dot for 100 follows on the controller lane, so the restart begins at 50. 4 workers on 2 nodes; rank 3 exits with code 13 at step 120. Three runs; pick one above. The scrubber walks the run event by event.
max_failures=1. From which step does the second attempt start?report for step 100 and rank 0 had written the step-100 checkpoint half a second before the crash. A report reaches the controller only when it polls, and it registers a checkpoint only once it holds that report from every worker (report_handler.py lines 40 and 63: "Wait for all workers to report training results", if not all(self._training_report_queues): return). Rank 3's step-100 report died inside its process, so step 100 was never registered: 70 steps redone instead of 20, and the step-100 files stayed in storage as an orphan directory that num_to_keep=2 did not delete.measured The restarted group recomputed steps 50 to 120 and finished; its loss matched the uninterrupted running example at most logged steps and differed by one float32 rounding step (2.4e-7) at steps 70, 180 and 200, the DDP bucket-rebuild effect the root's Failure lab explains (a restarted process steps once with the initial bucket layout).
Directory under /shared/results/ry-t1 | Bytes | What it is |
|---|
| Step | This run (rank 0's global loss) | Uninterrupted running example | Difference |
|---|
The uninterrupted reference is the root's recorded Ray run (src/data/runs/ray, same image, seed and world size).
Cost. Launch: the root's Launch lab measured a median 10.0 s from submit to first step on Ray Train, against 7.5 s on Slurm and 5.8 s on Kubernetes (5 runs each, image preloaded, laptop), mostly starting workers and importing torch. Recovery: about 6 to 7 s from crash to the new group's first step here, plus the steps redone. Memory: the controller (about 0.21 GB) and the driver (about 0.23 GB) live on the head.
With train.py writing its own checkpoints, the Failure lab ran: max_failures=0 and a rank crash: fit() raised WorkerGroupError after 1.27 s; max_failures=2: a new worker group resumed from step 100 10.15 s after the crash; a killed worker node: Ray waited for 4 fake_gpu with only 2 alive and resumed only when the node came back (93.6 s), because Ray Train does not shrink the group unless you configure elastic scaling. The Launch lab found that the worker-group start timeout (60 s, RAY_TRAIN_WORKER_GROUP_START_TIMEOUT_S) is retried forever when capacity never comes.
Check. The driver log shows the controller's decisions ("[FailurePolicy] RETRY ... Error count: 1 (max allowed: 1)", "Started training worker group of size 4" with every rank's node and pid); result.checkpoint and result.best_checkpoints are what the controller registered. A newest checkpoint on disk that get_checkpoint() did not return is this race.
Ray Serve runs online inference on a Ray cluster. A deployment is a class decorated with @serve.deployment; each copy of it is a replica, an actor. A controller actor ("a global actor unique to each Serve instance that manages the control plane") creates and replaces replicas; an HTTP proxy actor (by default "one HTTP proxy actor on the head node", port 8000) receives requests and routes them to replicas through a DeploymentHandle. Deployments call each other through handles, so a pipeline of models is one Python program (Ray Serve architecture).
Batching and LLMs. @serve.batch gathers concurrent calls into one list (defaults max_batch_size = 10, batch_wait_timeout_s = 0.01, python/ray/serve/batching.py lines 803 and 804). For LLMs, Ray Serve LLM wraps an engine ("Engine-agnostic backends such as vLLM and SGLang") behind LLMConfig and build_openai_app, an OpenAI-compatible app, with prefill-decode disaggregation, multi-LoRA and prefix-aware routing (Ray Serve LLM). What those mechanisms are is the serving topic's: vLLM and LLM serving in production own batching, routing and autoscaling as ideas. not run here: a Serve app on this cluster would show actor placement already measured above; on Kubernetes it runs as a RayService.
max_ongoing_requestsfrom the source Defaults at tag ray-2.59.0 (python/ray/serve/_private/constants.py lines 283 and 284, python/ray/serve/config.py lines 695 and 704, read 2026-10-24): each replica takes up to max_ongoing_requests = 5 at once; with autoscaling on, the controller aims for target_ongoing_requests = 2 per replica between min_replicas and max_replicas (both 1 by default), adding replicas after upscale_delay_s = 30 s of load and removing them after downscale_delay_s = 600 s. "When replica Actors fail, the Controller Actor replaces them with new ones."
Tuner(trainable, param_space={...}, tune_config=TuneConfig(num_samples=N, scheduler=ASHAScheduler())) runs many trials, each an actor or a whole Ray Train run; a search algorithm proposes configurations (random, grid, Bayesian through Optuna and others) and a trial scheduler stops bad trials early (ASHA, successive halving) or mutates good ones (Population Based Training). Right for many small or medium trials on a shared cluster; one large pretraining run has nothing to tune in parallel (Ray Tune docs). not run here: a sweep would only repeat the task and actor mechanics above.
In production a Ray cluster usually lives on Kubernetes through the KubeRay operator (v1.7.1, released 2026-09-21), which adds three custom resources:
GPUs come from the Kubernetes device plugin as nvidia.com/gpu in the pod spec; Ray reads them as its GPU resource. Operators, device plugins and Kueue are taught on Kubernetes for ML; KubeRay docs. not run here: KubeRay plus a Ray cluster on the topic's kind cluster would add about 3 GB of containers to a laptop already near its budget; the root's Tool map lists KubeRay's status.
For training work (the root's Reading tab has the cluster-level comparison):
| Your job looks like | Good fit | Why |
|---|---|---|
| One big SPMD training run (every rank runs the same program): pretraining, large SFT | Slurm + torchrun, or Kubernetes + JobSet (launchers: Launching distributed training) | No dynamic tasks to schedule; Ray Train adds a controller and a head to run and size, for a launcher you already have. It still works (it ran the running example here), and is convenient if the rest of your stack is Ray. |
| Many cooperating programs of different shapes: RL post-training (policy trainer, rollout engines, reward and reference models), agents with environments | Ray, usually on Kubernetes via KubeRay | Each piece is an actor with its own resources; placement groups colocate or separate them; one Python driver orchestrates the loop. This is why the open RL stacks are built on it. |
| Heterogeneous data processing feeding training or batch inference | Ray Data | Streaming between CPU and GPU stages with backpressure, on one cluster. |
| Online inference made of several models or steps | Ray Serve (RayService on Kubernetes) | Replicas are actors with their own resources; handles compose deployments in Python. |
| Hyperparameter sweeps of small and medium runs | Ray Tune, or a scheduler's job arrays | Tune adds early stopping and search; Slurm arrays are simpler if every trial is independent. |
Who uses it. verl, the open version of ByteDance's HybridFlow (Sheng et al., arXiv 2409.19256, EuroSys 2025), uses Ray for its driver ("The centralized single controller is built on top of Ray", section 7) and argues for a "single controller" (one driver directing everything, Ray's model) over "multi-controller" SPMD inside each model's workers. OpenRLHF's README: "OpenRLHF leverages Ray for efficient distributed scheduling. It separates the Actor, Reward, Reference, and Critic models across different GPUs" (OpenRLHF on GitHub, read 2026-10-16). Ray joined the PyTorch Foundation on 2025-10-22. The RL algorithms are on RL for LLMs; DDP, FSDP2 and c10d on Distributed PyTorch.
Every message below was printed on this cluster on 2026-10-16 (addresses scrubbed); the run that produced it is named.
ry_core.py tasks, the animation in Tasks). Submit everything, then ray.get the list, or use ray.wait to process results as they finish.ValueError: assignment destination is read-onlyThe array is a zero-copy view of the object store (
ry_core.py objects). Copy it (a = a.copy()) if you need to modify it.OwnerDiedError: Failed to retrieve object 00d7b3a94be6e983ffffffffffffffffffffffff0500000002e1f505. ... The object's owner has exited. This is the Python worker that first created the ObjectRef via `.remote()` or `ray.put()`.(
ry_core.py lineage, object C.) Return values from tasks (the caller then owns them and lineage can rebuild them), or let a long-lived actor or the driver own data you cannot lose.ObjectReconstructionFailedError: ... [OBJECT_UNRECONSTRUCTABLE_RETRIES_DISABLED] The object cannot be reconstructed because the task was created with max_retries=0. Consider enabling retries using `@ray.remote(max_retries=N)`.(
ry_core.py lineage, object B.) Turning retries off is right for tasks with side effects; then do not depend on their outputs surviving.RayTaskError(ValueError): ray::raise_first() (pid=606, ip=<ip-1>)
File "/shared/ry/ry_core.py", line 204, in raise_first
raise ValueError("bad batch in shard 7")
ValueError: bad batch in shard 7One attempt only; with retry_exceptions=True the same task ran twice and succeeded. A crashed worker process, by contrast, is retried ("Task crash_first failed. There are 3 retries remaining, so the task will be retried.").max_retries=0.max_restarts=1, the counter at 3 came back as 1 after its process died, on another node, with a new pid. The in-flight call failed: ActorUnavailableError: The actor ... is unavailable: The actor is temporarily unavailable: RpcError: RPC error: Socket closed rpc_code: 14. The task may or may not have been executed on the actor.Without
max_restarts: ActorDiedError: The actor died unexpectedly before finishing this task.Checkpoint actor state yourself if it matters.
Training failed due to controller error: 1 worker(s) were killed due to the node running low on memory. Memory on the node (IP: <ip-1>, ...) was 1.03GB used / 1.07GB limit (0.961193) OOM kill reason: Memory usage 1104416768B exceeded threshold of 1095761920B (95.0% of 1153433600B limit)(A Ray Train run on a worker where the spill test's IO workers were still resident,
src/runs/core/train_oom.out.) Size nodes for the workers plus Ray's own processes; restart Ray after resizing a container (the threshold is fixed at raylet start, see Architecture).(autoscaler +3s) Error: No available node types can fulfill resource request defaultdict(<class 'float'>, {'CPU': 4.0, 'fake_gpu': 4.0}). Add suitable node types to this cluster to resolve this issue.(The root's Scheduling lab, a STRICT_PACK group of 4 on nodes of 2.) The group stays PENDING; nothing fails. Put a timeout on pg.wait() and check ray status for "Pending Demands".ray.train.get_checkpoint() returns, and treat other directories under the run's storage path as possibly incomplete or unregistered.Multi-node Ray clusters are not supported on Windows and OSX(The topic's setup.) Use Linux nodes or containers; a single-node Ray on a Mac is fine for development.
.remote() or ray.put). It holds the reference count, the copies' locations and the lineage. When it dies the object is lost (OwnerDiedError) even if copies exist; Ray cleans up the copies.ray.put objects with no other copy, outputs of max_retries=0 tasks, objects owned by workers on the dead node. Small inline objects were never on that node.ray_config_def.h lines 1060 to 1064). About 30 s here. A crashed worker process is noticed in under a second by its raylet.init_process_group with the TorchConfig backend (env://) before your loop runs. No torchrun.report but before the poll takes its report with it, so the latest checkpoint is never registered (measured: restart from 50 with 100 on disk, 3 of 3 runs). Shorter gap between checkpoints, or accept up to one interval more of lost work.--num-cpus 0 so no tasks land there, enough memory for the driver and controller, and GCS fault tolerance so its loss is survivable.read on CPU nodes, map_batches(decode) as CPU tasks, map_batches(Embedder, num_gpus=1, concurrency=N) as an actor pool on GPU nodes (different resources, so not fused), consumed by Ray Train workers with iter_torch_batches. Streaming keeps GPUs busy from the first blocks; backpressure bounds memory; size blocks (1 to 128 MiB) and pools so neither stage starves; spill to local NVMe.ray-2.59.0 (commit dd83c3a703a5422d0b47f142cb380c6330817608), every quoted line listed with file and line in src/inputs/source_quotes.json; Ray documentation pages linked in place (read 2026-10-16); the Ownership (NSDI 2021), HybridFlow (EuroSys 2025) and Ray Data (arXiv 2501.12407) papers. Measurements: this page's runs on 2026-10-16 (src/runs/) and the root page's Scheduling, Launch and Failure labs, all on Apple M1 Pro, Docker Desktop VM, shared machine. The fake GPUs are a custom resource; nothing ran on a real GPU.Slurm against Kubernetes and Ray, from zero, with the running example on all three. Its Scheduling lab (Ray placement groups), Launch lab (Ray Train's start-up by stage, its environment variables), Failure lab (Ray Train crash and node-loss runs, the head's memory) and Tool map (KubeRay, Ray status) are used throughout this page. 26 min, plus 10; each lab 8 to 32 min
Cluster anatomy: nodes, GPUs, networks and storage tiers · Slurm from zero: allocation, gang scheduling, fairshare and preemption · Kubernetes for ML: scheduling, device plugins, gang scheduling and operators (KubeRay's home) · Launching distributed training: torchrun, rendezvous, NCCL and hangs · Fault tolerance at scale: failures, checkpoint/restart and elastic training · Storage and data movement · Observability and cost · ML platforms and workflows.
c10d, DDP, FSDP2, DCP: what runs inside each Ray Train worker. 35 min
RLHF, GRPO, RLVR: the algorithms the Ray-based RL stacks run, and (section 12) the stacks themselves: verl, OpenRLHF, TRL, SkyRL, NeMo RL. 53 min
The post-training stages around the RL step: SFT, reward models, the DPO family, RLVR. 33 min
Data formats and loaders, the alternative to Ray Data for pre-tokenized shards. 34 min
cgroups v2: the memory limit Ray's memory monitor reads. 51 min
Replication, consistency, failure detection: the ideas behind the GCS and ownership. 46 min
Wang et al., NSDI 2021. The design of Ray's ownership, reference counting and lineage reconstruction. 60 min
Moritz et al., OSDI 2018. The original architecture (its centralised object table was later replaced by ownership). 45 min
Luan et al., 2025. Ray Data's execution model; claims 2.5 to 12x on heterogeneous batch inference (authors' measurements). 45 min
Sheng et al., EuroSys 2025 (verl). Single controller on Ray plus SPMD workers. 50 min
Tasks, actors, objects, placement groups. 15 min
Links the Ray 2.0 architecture whitepaper: leases, ownership, the GCS, the object manager. 90 min
Tasks, actors, objects, nodes, the GCS. 25 min
Where and how objects spill; configuring the spill directory. 10 min
Bundles, strategies, lifetimes. 15 min
ray.get in a loop, too fine-grained tasks, passing large arguments by value, and more. 30 min
Blocks, streaming execution, fusion, backpressure. 20 min
TorchTrainer, checkpoints, fault tolerance, Train v2. 30 min
Controller, proxies, replicas, the life of a request. 15 min
LLMConfig, build_openai_app, vLLM and SGLang backends. 20 min
RayCluster, RayJob, RayService, autoscaling, GCS fault tolerance. 30 min
Start with src/ray/common/ray_config_def.h (every tunable with its default). as long as you like