Training an LLM with Ray: Who Allocates GPUs, Splits the Model, and Synchronizes Gradients?

July 14, 2025

After studying how a neural network is partitioned and how computation across stages is scheduled, I thought back to Kubernetes (K8s), familiar from my backend work. To deploy a service, I specified the replica count and resources per replica in YAML, and K8s placed the replicas on the cluster. To extend the analogy: say a training compiler has planned for one group of GPUs to compute the first few layers and hand its results to another. Who finds available GPUs and starts both groups of processes according to plan?

That question led me to look into resource management and scheduling for training. It turns out people have already connected the two layers. Alpa generates a parallel execution plan for a network, then uses Ray to call workers on different machines so that each GPU group executes its assigned computation.12

What is Ray? Ray is an open-source computing framework that lets a program distribute work across machines. It began around 2016, and the Berkeley team released version 0.1 in May 2017. The early problem was scheduling reinforcement learning: multiple machines simulate games of varying lengths, and whichever finishes first can take the next task. LLMs later put the same capability to work coordinating groups of GPUs during training and routing inference requests to processes that already hold the model.3425

Who allocates machines to jobs and starts workers on them?

Suppose several groups share a ten-machine lab. You need two machines, each with one GPU, to train a model. On a shared high-performance computing (HPC) cluster, you might submit a job to Slurm, specifying how much hardware you need and for how long. When your turn comes, the job receives two machines. Your Python program still needs to start workers on each and give them work. Ray's Slurm example follows this sequence: get the allocated host list from Slurm, start Ray on the first host, then join the others.6

A Ray program working with a language model commonly uses two constructs. A task fits a function that runs once, such as “tokenize these texts and send back the result.” A stateful worker called an actor fits “load a model onto the GPU, then handle successive batches of inputs.” The actor can retain the loaded model. Ray places it according to the resources the program requests.4

Inference on Kubernetes illustrates both responsibilities, too. Xing Yunyang's deployment course uses two A100s to run a pretrained DeepSeek-R1-Distill-Llama-70B. You describe the desired Ray cluster in the configuration, and KubeRay creates and maintains it on Kubernetes. With those resources available, the application can request GPUs from Ray and start workers to handle inputs.7

📓 Note Does DeepSeek itself use Ray? Developers can follow vLLM 0.8.5's example to accept requests with Ray Serve and use vLLM to load DeepSeek-R1 weights and generate answers. DeepSeek's own V3 technical report gives two details: its production inference system runs prompt ingestion and token-by-token generation separately, and it trains with its in-house HAI-LLM framework. The report does not identify whether its production serving stack uses Ray or which scheduler allocates machines to training jobs.89

If each GPU reads two texts, how do they learn the same weights?

Start with a small model that fits on one GPU. Give it half a sentence, ask it to predict the next word, and check its guess against the actual word. Training repeatedly uses the error to adjust numbers inside the model called weights. Now suppose we have four training texts of equal length, A, B, C, and D, and want two GPUs to complete a step together. Data parallelism gives each GPU the same model and different samples.10

Ray's introductory PyTorch tutorial classifies clothing images. Imagine those images are our four texts and the division of labor still applies. Read the code in three steps.11

  1. Find two GPUs and start two processes. In Ray Train, ScalingConfig(num_workers=2, use_gpu=True) requests two training processes with one GPU each by default. TorchTrainer.fit() starts the job and runs the same training function on each. A worker here is the process executing the function.
  2. Give each model different data. The tutorial uses prepare_data_loader to configure sampling per process. Say the first GPU reads A and B, the second C and D. Both start with the same weights, make predictions, calculate errors, and run backpropagation, working backward from the error to determine how much changing each weight slightly would affect it. That quantity is the gradient.12
  3. Synchronize gradients, then update each model. The tutorial passes the model to PyTorch's DistributedDataParallel (DDP) mechanism using prepare_model. Suppose the two GPUs compute mean gradients of 2 and 6 for a particular weight. DDP arranges communication during backpropagation so both processes receive the average, 4. If the initial weight is 1 and both subtract 0.1 times the gradient, both obtain 0.6. The component that updates weights according to that rule is the optimizer.1110

There is an easy distinction to miss. Starting two copies of a single-GPU script can duplicate data or produce two differently updated models. To combine the work into one training step, sampling determines what each GPU reads, while DDP determines how the models share what they learned in this step. Look for those two places in the tutorial and it becomes clear why configuring the number of GPUs still requires changing the training function.1110

If one GPU cannot even hold the model, will Ray split it automatically?

Keep the two GPUs, but suppose each has 24 GB and the new model's weights require 30 GB. Data parallelism requires loading 30 GB on each, so it fails at the first step. We need to change how the model itself is placed. Put the first few layers on the first GPU and the rest on the second, for example. The first sends the batch's intermediate results to the second. During training, the later layers send gradients back in the opposite direction. A sequence of consecutive layers constitutes one pipeline stage. Whether it all fits also depends on the space for intermediate results and weight updates.1

Alpa's pipeline training tutorial first connects to the Ray cluster. Its code makes it possible to match planning to execution.13 Alpa chooses a partition based on computation, memory, and transfer costs: which layers form a stage and which devices get each stage. Ray lets Alpa start and call workers on the chosen machines. In 2023 the NVIDIA technical blog published experiments measuring OPT-175B training throughput with this combination, comparing configurations from 128 to 1,024 GPUs. At a cross-machine handoff, Alpa's plan specifies after which layer to transmit data, and Ray's process and resource management lets the next stage run on another machine. For comparisons of partitioning strategies, see the tensor-parallelism article's Alpa worked example and paper experiments.12

How can one group of GPUs write answers and another score them in one training run?

Consider a different objective: one model writes an answer and another scores it. How do we coordinate the two so that the writer learns what kinds of answers people prefer? One form of reinforcement learning from human feedback (RLHF) first uses human preferences to train a scoring model, then uses the scores it gives new answers to improve the model that generates them.14

Take the prompt “Explain a lunar eclipse in words an elementary school student can understand.” In the PPO (proximal policy optimization) setup described by the OpenRLHF paper, we can follow a single answer through four roles.14

RoleWhat it does with the question or answer
Policy modelWrites the answer. Training changes its future propensity to choose those words.
Reward modelReads the question and complete answer and scores the answer according to learned human preferences.
Reference modelRetains a fixed copy of the original policy and computes how likely it was to choose those words. Training uses this to constrain how far the policy moves.
Value modelEstimates the future return expected at a point in generation, helping determine how much better the outcome was than expected.

OpenRLHF's code contains two meanings of actor. PPO's Actor is the policy model in the table. A Ray actor is a process that retains state. A reward model, for example, can live in a Ray actor and continue doing the scoring.15

How many GPUs do the roles occupy? Mengyuan's illustrated guide assumes three machines with eight GPUs each. The first two host the four model types in the table, and the third generates answers. vLLM starts four inference instances, each using two GPUs to run a copy of the policy model. They can handle different batches of questions concurrently. The developer chooses these groups, Ray places processes accordingly, and vLLM manages inference cooperation between the two GPUs in each instance. With enough memory the policy and reference models can also share a GPU.15

Let's take the eclipse question through one round. The diagram simplifies section 4.5 of the original guide and follows the training side and one generation instance. Training sends the question, generation sends back an answer under the current policy, and training updates the policy using the score, reference probabilities, and value estimate. It then sends the updated weights to the generator for the next batch.15

sequenceDiagram
    participant T as 训练端
    participant G as vLLM 生成端
    T->>G: 发来问题「怎样向小学生解释月食?」
    G-->>T: 返回按当前策略生成的回答
    Note over T: 结合评分、参考概率和价值估计更新策略
    T->>G: 发送更新后的策略权重
    Note over G: 用新权重回答下一批问题

Why send weights one more time? The trainer changes its local policy model, while all four generation instances still hold last round's copies. In the OpenRLHF version in the guide, the trainer notifies each instance via Ray to prepare to receive, then uses PyTorch broadcast to send the same update. If the trainer uses DeepSpeed ZeRO-3 to shard weights across GPUs, it handles one parameter at a time. GPUs gather the current parameter, one training process broadcasts it, and then they move to the next. The earlier two-GPU training example exchanged gradients used to update weights. The generation side here receives weights that have already been updated.1516

If workers already exist, do I need Ray to call another model?

Suppose we want a small model to imitate a larger model's answers. The large model is a teacher and supplies the predicted probability of each candidate word. The smaller student adjusts its predictions to approximate the teacher's. This is distillation. In “Programming Foundations of Distributed Training Frameworks,” Zhenzhong Hehuan models the step with two processes. The startup script designates teacher and student. Through PyTorch remote procedure calls (RPC), the student uses rpc_async to ask the teacher to process the same input. The student can compute its own prediction and use wait() to retrieve the teacher's result once it is ready to compare them.17

If two GPUs each run a student model, those two student processes enter the same process group to synchronize gradients before updating. Each member's identifier in the group is its rank, here 0 and 1. The member count, world_size, is 2. The teacher only supplies predictions and stays outside the group. That answers three separate questions: the startup script assigns the teacher, RPC retrieves the teacher's output, and the process group determines who updates together. When machines and roles are predetermined, PyTorch itself supports the entire flow. When multiple model groups need GPUs according to configuration, with persistent instances and repeated calls as in OpenRLHF above, Ray can take over process placement and management.1715

Which waits are worth optimizing once Ray is in place?

How large are your training-data preparation tasks? Suppose 10,000 short texts need tokenizing. One Ray task per text means submitting, scheduling, and retrieving results 10,000 times. Try batching a hundred texts per call and compare the elapsed time for the whole dataset against one-at-a-time submission. With batches that are too large, there is less work to hand to different processes concurrently. You can measure this before loading the model or occupying any GPUs.18

During inference, how long before an idle GPU can answer? If its machine still needs to download the model, the job must wait for the weights after it gets the GPU. This wait is the cold start. ServerlessLLM specifically optimizes it by estimating each host's time to get weights ready, accounting for copies already stored locally. In a 2024 paper using OPT-6.7B and requests based on GSM8K math problems, Ray Serve 2.7.0 modified by the authors for on-demand startup took 12.1 seconds on average to start the model. Adding a local SSD cache cut that to 8.2 seconds. ServerlessLLM took 0.8 seconds. These measurements describe time before inference could begin in that deployment. The Alpa experiment above measured work per second after GPUs had started training.19

📓 Note Searching for these frameworks may also turn up ray-project/ray-llm. The repository was archived in March 2025, and its README points to deployment and batch-processing APIs in the main Ray project. For PyTorch code that updates model weights, the appropriate entry point is Ray Train, discussed above.511

References

Footnotes

  1. Zheng, L., et al. (2022). Alpa: Automating inter- and intra-operator parallelism for distributed deep learning. OSDI. Figure 1 and sections 3–5 on partitioning computation, device groups, and pipelines. ↩ ↩2 ↩3

  2. Dong, J., Zheng, H., Zheng, L., & Nguyen, P. (2023, May 15). Efficiently Scale LLM Training Across a Large GPU Cluster with Alpa and Ray. NVIDIA Technical Blog. Combined architecture and 175-billion-parameter training experiments. ↩ ↩2 ↩3

  3. Hellerstein, J. (2017, May 30). RISELab announces 3 open source releases. UC Berkeley RISELab. The v0.1 release announcement and item 3 on Ray, reinforcement-learning simulations, and dynamic tasks. ↩

  4. Moritz, P., et al. (2018). Ray: A distributed framework for emerging AI applications. OSDI. The abstract describes tasks and actors as “both task-parallel and actor-based computations.” Section 7 on the early Spark prototype, varying simulation times, and the origin of actors. ↩ ↩2

  5. Ray contributors. (2025). Ray LLM APIs are now upstreamed and moved to Ray repo. GitHub. Archived repository README. ↩ ↩2

  6. Ray contributors. (2025). Deploying on Slurm (Ray 2.47.1). GitHub. Official script obtaining nodes from Slurm, starting Ray, and joining the cluster. ↩

  7. Xing Yunyang. (n.d.). 07 | Advanced Deployment III: Distributed Deployment of an Unquantized DeepSeek Model. Geek Time, Practical DeepSeek Application Development. The introduction's two-A100 target and the KubeRay explanation under “What Is Ray?”. ↩

  8. vLLM contributors. (2025). Ray Serve Deepseek (v0.8.5). vLLM documentation. Model source, parallel configuration, and service entry point in the example. ↩

  9. DeepSeek-AI. (2024, December 27). DeepSeek-V3 technical report (v1). arXiv. Sections 3.1–3.2, training cluster and HAI-LLM; section 3.4, the team's inference deployment. ↩

  10. PyTorch contributors. (2025). DistributedDataParallel (PyTorch 2.7). PyTorch documentation. Opening class description and note on gradient averaging. ↩ ↩2 ↩3

  11. Ray contributors. (2025). Get started with distributed training using PyTorch (Ray 2.47.1). GitHub. Tutorial, two-worker configuration, and training function. ↩ ↩2 ↩3 ↩4

  12. Zhang, A., Lipton, Z. C., Li, M., & Smola, A. J. (n.d.). Dive into Deep Learning (2nd ed.). Section 4.7, forward propagation, backward propagation, and computational graphs. ↩

  13. Alpa contributors. (n.d.). Distributed training with both shard and pipeline parallelism. Alpa 0.2.3.dev17. Official example of initializing the cluster and training in stages. ↩

  14. Hu, J., et al. (2024, May 20). OpenRLHF: An easy-to-use, scalable and high-performance RLHF framework (v1). arXiv. Sections 2.1–2.2 on scheduling four models, generation, and training. ↩ ↩2

  15. Mengyuan. (2024, December 22, last edited). An Illustrated Guide to Distributed Training with Ray in OpenRLHF. Zhihu. Sections 2.1–2.2 on device assignments, 4.1 on two meanings of Actor, and 4.4–4.5 on transferring weights and training. The author limits the device grouping to a teaching example: “This does not mean they are necessarily the optimal configurations for training” (opening of section 2). ↩ ↩2 ↩3 ↩4 ↩5

  16. OpenRLHF contributors. (n.d.). ActorPPOTrainer._broadcast_to_vllm (commit bb46342). GitHub. Implementation notifying vLLM, gathering ZeRO-3 shards, and broadcasting each parameter. ↩

  17. Zhenzhong Hehuan. (2025, February 4, last edited). LLM Practice — A Detour: Programming Foundations of Distributed Training Frameworks. Zhihu. Student process group in the distributed demo and the later teacher call using rpc_async. ↩ ↩2

  18. Ray contributors. (n.d.). Anti-pattern: Over-parallelizing with too fine-grained tasks harms speedup. Ray documentation. Example comparing individual and batched dispatch. ↩

  19. Fu, Y., et al. (2024, July). ServerlessLLM: Low-latency serverless inference for large language models. OSDI. Section 7.4, Figure 10, on-demand Ray Serve baseline, cached variant, and model startup times. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-07-14). Training an LLM with Ray: Who Allocates GPUs, Splits the Model, and Synchronizes Gradients?. https://caiborui.com/blog/2025-07-14-zh-ray-llm-distributed-training-entrans

@misc{borui2025-e792c271,
  author = {borui},
  title = {{Training an LLM with Ray: Who Allocates GPUs, Splits the Model, and Synchronizes Gradients?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-07-14-zh-ray-llm-distributed-training-entrans}
}