Ray on TPU¶
Use this guide when your PyTorch workload is orchestrated by Ray (actors that each own a device, Ray Train's TorchTrainer, or a reinforcement learning loop with separate rollout and training workers) and you want it on Cloud TPU with TorchTPU. Ray now runs one worker per TPU device, the model PyTorch users have on GPUs: a worker requests resources={"TPU": 1} as it would request num_gpus=1. Chapter 15 explains the RL loop's architecture, weight sync and staleness; this page is the recipe.
Prerequisites¶
- TorchTPU installed on every TPU host (Install TorchTPU on a TPU VM), and Ray installed next to it (
pip install ray). - For multi-host slices: a GKE cluster with KubeRay, set up through Google's tutorials Train models on multi-host TPUs with Ray and TorchTPU or Serve LLMs on multi-host TPUs with Ray and TorchTPU.
- Optional: this book's
code/ch15_rl/(source).
Steps¶
1. Port a Ray actor from GPU¶
Three things change: the resource request, the device string and the collective backend. The example from Anyscale's Announcing Ray support for PyTorch on Google TPUs:
import os
import ray
import torch
import torch.distributed as dist
# On GPU: @ray.remote(num_gpus=1)
@ray.remote(resources={"TPU": 1})
class TorchWorker:
def __init__(self, rank: int, world_size: int):
self.rank = rank
self.world_size = world_size
# Ray automatically isolates the assigned device via TPU_VISIBLE_CHIPS
self.local_rank = os.environ["TPU_VISIBLE_CHIPS"]
def run_all_reduce(self, master_addr: str, master_port: int):
os.environ["MASTER_ADDR"] = master_addr
os.environ["MASTER_PORT"] = str(master_port)
os.environ["WORLD_SIZE"] = str(self.world_size)
os.environ["RANK"] = str(self.rank)
os.environ["LOCAL_RANK"] = self.local_rank
# On GPU: dist.init_process_group(backend="nccl")
dist.init_process_group(backend="tpu_dist")
# On GPU: device = torch.device("cuda")
device = torch.device("tpu")
tensor = torch.ones(2, 2, device=device) * self.rank
dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
return tensor.cpu().numpy()
Ray isolates each actor's device by setting TPU_VISIBLE_CHIPS, as it sets CUDA_VISIBLE_DEVICES on GPU.
Check: every actor returns the same tensor, filled with the sum of the ranks (for ranks 0 to 3, every element is 6).
2. Train with TorchTrainer on a slice¶
For an ordinary training loop, let Ray Train do the TPU orchestration. With use_tpu=True, a topology and an accelerator_type, it reserves a SlicePlacementGroup so all workers land on one ICI-connected slice, starts one worker per device, sets RANK, WORLD_SIZE, LOCAL_RANK, MASTER_ADDR, MASTER_PORT and TorchTPU's slice-builder addresses and topology, and initializes the tpu_dist process group:
import ray
from ray import train
from ray.train import ScalingConfig
from ray.train.torch import TorchTrainer
import torch
from torch import nn, optim
def train_fn_per_worker(config):
device = ray.train.torch.get_device() # torch.device("tpu") on TPU workers
model = nn.Sequential(nn.Linear(10, 32), nn.ReLU(), nn.Linear(32, 1)).to(device)
model = ray.train.torch.prepare_model(model) # DDP over "tpu_dist"
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.05)
inputs = torch.randn(128, 10, device=device)
targets = inputs.sum(dim=1, keepdim=True)
for epoch in range(10):
optimizer.zero_grad()
loss = criterion(model(inputs), targets)
loss.backward()
optimizer.step()
train.report({"loss": loss.item(), "epoch": epoch + 1})
scaling_config = ScalingConfig(
num_workers=16,
use_tpu=True,
topology="4x4",
accelerator_type="TPU-V6E", # or "TPU-V7X"
resources_per_worker={"TPU": 1},
)
trainer = TorchTrainer(train_loop_per_worker=train_fn_per_worker, scaling_config=scaling_config)
result = trainer.fit()
prepare_model gives you DDP. For a model that needs FSDP, set up SimpleFSDP inside the training function (FSDP on TorchTPU). The loop above calls loss.item() every epoch for reporting, which is a host sync; on a real model report every N steps.
Check: trainer.fit() returns a result whose reported metrics carry loss and epoch from the workers.
3. Serve with Ray Serve LLM¶
Ray Serve LLM reserves a slice per replica the same way and starts vLLM-TorchTPU workers across it:
from ray.serve.llm import (
LLMConfig,
LLMServingArgs,
ModelLoadingConfig,
build_openai_app,
)
llm_config = LLMConfig(
model_loading_config=ModelLoadingConfig(
model_id="google/gemma-4-26B-A4B-it",
),
accelerator_type="TPU-V6E",
accelerator_config={
"kind": "tpu",
"topology": "4x4",
},
placement_group_config={
"bundle_per_worker": {"TPU": 1},
},
engine_kwargs={
"tensor_parallel_size": 16,
"enable_expert_parallel": True,
"max_model_len": 8192,
},
)
app = build_openai_app(LLMServingArgs(llm_configs=[llm_config]))
Check: the app serves an OpenAI-compatible endpoint; follow Google's serving tutorial for deployment and a test request.
4. Run an RL loop: start with the companion¶
An RL loop starts rollout and trainer actors directly, each with resources={"TPU": 1}, because the two sides are different programs with different device counts. Rehearse the plumbing with this book's GRPO loop before a real model:
python code/ch15_rl/grpo_loop.py --cpu-smoke # in-process loop, then Ray actors if Ray is installed
python code/ch15_rl/grpo_loop.py --ray # the same loop as Ray actors on a local Ray instance
python code/ch15_rl/grpo_loop.py --tpu # TPU VM: one TPU device per actor
Check: the smoke run ends cpu-smoke: OK; the mean reward rises from about 0.07 to about 0.26 over 40 iterations; after every sync the rollout's version and SHA-256 weight fingerprint match the trainer's; with Ray, the weights through Ray match the in-process run bit for bit. On --tpu, each actor reports the TPU_VISIBLE_CHIPS Ray gave it.
5. Run TorchTitan's RL recipe on GKE¶
The rl_nc_ray experiment in TorchTitan's TPU lane is the reference layout, written for two v6e-8 slices (one for the trainer, one for the vLLM generator):
- Build the image from
scripts/Dockerfile.ray.vllm(TorchTPU, Ray and vLLM) and push it to Artifact Registry. - Mount a GCS bucket at
/datain every pod with the GCS Fuse CSI driver, and bind theray-ksaKubernetes service account to a Google service account through Workload Identity. -
Enable the Ray operator and create the cluster:
gcloud container clusters update $CLUSTER_NAME --location=$REGION --project=$PROJECT \ --update-addons=RayOperator=ENABLED kubectl apply -f torchtitan/experiments/tpu/rl_nc_ray/scripts/ray-v6e8-2.yaml -
Port-forward the head service and submit the recipe (
0.6b,1.7bor4bfor the Qwen3 sizes):kubectl port-forward svc/ray-tpu-v6e-cluster-head-svc 8265:8265 10001:10001 bash torchtitan/experiments/tpu/rl_nc_ray/scripts/e2e_recipe_gke.sh 0.6b -
Follow the job and plot its metrics:
ray job logs <raysubmit_id> --address="http://127.0.0.1:8265"scripts/plot_metrics_from_log.pyplots reward, loss, generation time and training time per step.
The script as checked in runs 8-way tensor parallelism on both sides with --compile.no-enable and 10 training steps; read its flags rather than the README's prose when you adapt it. For a quick start without GKE, smoke_test_vm_tp1.sh and smoke_test_vm_tp4.sh run the loop on one TPU VM with the trainer on CPU and the generator on TPU.
Check: the logged mean reward (rollout_reward/_mean) rises over the run, generation, training and weight-sync times are logged per step, and after a sync bit_wise/logprob_diff/mean stays small and loss/ratio_mean sits near 1.
Troubleshooting¶
| Symptom | Likely cause | What to do |
|---|---|---|
| Workers of one group land on different slices | Actors started without a slice reservation | TorchTrainer with use_tpu=True and a topology, which reserves a SlicePlacementGroup |
| Generator host CPU and memory spike at every weight sync | A Ray ObjectRef passed bare, so Ray deserializes the full state dict on the generator's driver |
Pass [ref] and fetch inside the actor, as rl_nc_ray does |
| Out of memory on the rollout devices during the sync | New weights arrive whole next to the old ones and the KV cache | Sync layer by layer in small chunks (SYNC_LAYER_BY_LAYER), or shrink the KV cache budget |
| Every few steps one takes minutes | Recompilation: each new batch size, sequence count or token total is a new program | Pad training batches to fixed bounds and pad the varlen metadata; use the _varlen configs |
| Reward flat although the loss moves | Groups all right or all wrong: zero advantages | Raise the group size, change prompt difficulty, drop untrainable groups |
Loss inf or NaN after a sync |
Engine and trainer log-probabilities disagree badly | Clamp the log-ratio and drop non-finite tokens; check the engine holds the version you think |