Reinforcement learning with Ray¶
Prerequisites: Sharding, meshes and collectives, FSDP and TorchTitan on TPU
Pre-training and supervised fine-tuning run one program over and over: forward, backward, optimizer step. Reinforcement learning post-training runs three. A generation engine samples completions, a reward function scores them, and a trainer updates the policy; then the new weights must reach the engine before the next round of sampling. Each piece has different hardware needs, and the loop is only as fast as its slowest piece and the weight transfer between them. This chapter applies chapter 14's trainer inside that loop. You will compute GRPO's group-relative advantages, run a GRPO loop with a rollout worker and a trainer as Ray actors that each own one TPU device, see how TorchTitan's Ray experiment lays the loop out across TPU slices on GKE, and learn the three checks that tell you an RL run is working: a rising reward, a measured split of where the time goes, and proof that the engine samples with the weights you think it has.
What this chapter covers¶
- GRPO and Dr.GRPO advantages for a group of rewards, the groups that carry no signal, and the effect of the epsilon in the denominator.
- A GRPO loop whose rollout worker and trainer run as Ray actors, each requesting one TPU device with
resources={"TPU": 1}, with weights travelling through Ray's object store. - Ray on TPU for training: one worker per device, the
"tpu_dist"backend, and aScalingConfigthat reserves a slice forTorchTrainer. - TorchTitan's non-colocated Ray experiment on a KubeRay cluster on GKE, and what runs on the head node, the rollout slice and the trainer slice.
- Three checks for an RL run: a reward curve that rises on a task you can verify, a measured split of rollout, training and weight-sync time, and a weights version check after every sync.
Why RL post-training has a different shape¶
A GRPO step has five stages, and they do not want the same machine.
Rollout is serving. The engine (vLLM-TorchTPU or SGLang-TorchTPU) holds the policy's weights plus a paged KV cache, and generates many completions of different lengths. It is decode-heavy, memory-bandwidth-bound, and compiled per token-count bucket, as chapter 7 explained and Part V covers in depth.
Reward and advantage are host work. A reward function checks an answer, runs a verifier or calls another model; the advantage is arithmetic over a handful of numbers per prompt. In TorchTitan's RL experiment both run in the controller process, not on a TPU.
The update is training. Weights, gradients, optimizer state and activations: everything chapter 14 sized. The batch is the completions just generated, with their advantages and the log-probabilities the engine sampled them with.
Weight sync closes the loop. After every update, or every few, the trainer's new weights must reach the engine. Until they do, the engine samples from an older policy, and the training data is off-policy by that many versions.
Put the engine and the trainer on the same chips and they compete for HBM: the KV cache wants every spare byte, and so do the optimizer state and activations. The README of TorchTitan's Ray experiment, torchtitan/experiments/tpu/rl_nc_ray, states its design choice in one sentence: in a non-colocated setup the policy trainer (PyTorch FSDP) and the rollout generator (vLLM) run on entirely separate slices of TPU hardware, so "the training weights/gradients and the KV cache do not compete for the same HBM." RadixArk's Miles framework makes the same split at a smaller scale: in its TorchTPU run, one v7x host with 4 chips gives 2 to SGLang-TorchTPU for rollouts and 2 to a TorchTitan trainer.
Splitting the hardware moves the problem into orchestration: which process owns which device, how a multi-host slice is reserved as a unit, and how the weights get from one side to the other. That is the job Ray does.
GRPO in brief¶
Group Relative Policy Optimization drops the learned value function of PPO and uses the samples themselves as the baseline. For each prompt, sample a group of \(G\) completions, score each with reward \(r_i\), and give each completion the advantage
where the standard deviation is the population one. Every token of completion \(i\) gets the same \(A_i\). A completion better than its siblings is pushed up, a worse one down, and the scale of the reward does not matter because the group normalizes it. TorchTitan's estimator (AdvantageEstimator in torchtitan/experiments/rl/rollout/advantage.py) is exactly this, with statistics.pstdev(rewards) + 1e-6 as the denominator. It also offers the Dr.GRPO variant, which keeps the mean baseline and skips the division: \(A_i = r_i - \operatorname{mean}(r)\). Watch the default: should_std_normalize=False, so TorchTitan uses Dr.GRPO unless you ask for the standard-deviation normalization.
The policy loss is PPO's clipped surrogate, per token, averaged over the response tokens:
where \(\pi_\text{old}\) is the policy that sampled the token, so its log-probability comes from the engine. In TorchTitan, GRPOLoss is DAPOLoss with one symmetric clip, clip_eps = 0.2, so the ratio is kept in \([0.8, 1.2]\); DAPO's "clip-higher" sets a larger upper bound (its docstring suggests 0.28) to keep more probability mass on up-weighted tokens. Two guards in DAPOLoss are worth copying: it clamps the log-ratio to \(\pm 10\) before exp so that a large mismatch between engine and trainer cannot overflow to inf, and it drops from the loss any token whose engine log-probability is not finite, instead of training it as if it were on-policy. The loss is divided by the number of valid response tokens across all microbatches and data-parallel ranks, so gradient accumulation matches one large batch.
Working the formula¶
The companion function is grpo_advantages(rewards: list[list[float]]) -> list[list[float]] in code/ch15_rl/advantages.py: one inner list per prompt, normalized group by group.
| Rewards in the group | GRPO advantages | Dr.GRPO advantages |
|---|---|---|
[1, 0, 0, 1] |
[1.0, -1.0, -1.0, 1.0] |
[0.5, -0.5, -0.5, 0.5] |
[0, 0, 0, 0] |
[0, 0, 0, 0] |
[0, 0, 0, 0] |
[1, 1, 1, 0] |
[0.577, 0.577, 0.577, -1.732] |
[0.25, 0.25, 0.25, -0.75] |
[1, 0, 0, 0, 0, 0, 0, 0] |
[2.646, -0.378 × 7] |
[0.875, -0.125 × 7] |
Two lessons are in the table. Rare outcomes carry the strongest signal: the one failure among four gets \(-1.732\), the one success among eight gets \(+2.646\) (\(\sqrt{7}\)). And a group in which every sample scores the same contributes nothing: no gradient, whatever it cost to generate. A group of eight wrong answers is eight wasted rollouts, which is why group size and task difficulty matter as much as the learning rate.
Follow the version boxes at the bottom: they diverge at the update and agree again only after the sync. Then look at prompt B: eight rollouts, zero advantages.
Where epsilon matters¶
The \(\epsilon\) is not decoration, and where it goes changes the result. TorchTitan adds it to the standard deviation, outside the square root, and the companion function does the same. Three cases:
- All rewards equal. The centered rewards are zero, so the advantages are zero for any \(\epsilon\).
grpo_advantageschecks for an exactly constant group first and returns exact zeros, because a floating-point mean can leave a residue: the mean of[0.1, 0.1, 0.1]is 0.10000000000000002, and without the check that residue divided by \(\epsilon\) would be a small non-zero advantage made of rounding error. - Rewards that differ by float noise. For
[1, 1, 1, 1 + 1e-9]the standard deviation is about \(4 \times 10^{-10}\). With \(\epsilon = 10^{-6}\) the advantages stay below \(10^{-3}\); with \(\epsilon = 0\) they become \(\pm\sqrt{3}\) and \(\pm 1/\sqrt{3}\), full-size updates driven by noise. A reward model that returns floats needs the epsilon. - Ordinary groups. With rewards that differ by much more than \(10^{-6}\), the epsilon changes the advantages in about the sixth significant figure:
[1, 0, 0, 1]gives \(\pm 0.5 / (0.5 + 10^{-6}) = \pm 0.999998\).
With Dr.GRPO the epsilon is unused. The function rejects an empty group, a non-finite reward and a negative or non-finite epsilon with ValueError; the tests in tests/ch15/test_advantages.py check it against TorchTitan's formula and against an independent PyTorch tensor implementation.
Ray on TPU¶
Ray's TPU support used to follow JAX's execution model: one Ray worker process per host VM, managing all the chips attached to it. Anyscale and Google's announcement of Ray support for PyTorch on TPUs changes that to one worker per TPU device, the model PyTorch users have on GPUs, built on TorchTPU and on KubeRay on GKE. Three mechanisms carry it:
- One device per worker. A task or actor requests
resources={"TPU": 1}, as a GPU worker requestsnum_gpus=1. Ray isolates the assigned device by settingTPU_VISIBLE_CHIPS, as it setsCUDA_VISIBLE_DEVICESfor GPU workers. - Native device and collectives. Inside the actor the code is ordinary TorchTPU:
torch.device("tpu")instead of"cuda", anddist.init_process_group(backend="tpu_dist")instead of"nccl"(chapter 13). - Topology-aware gang scheduling. GKE provisions a multi-host slice as a node pool joined by ICI. Ray's
SlicePlacementGroupplaces a set of actors together on the same slice, so a training group never ends up split across slices.
import os
import ray
import torch
import torch.distributed as dist
@ray.remote(resources={"TPU": 1})
class TorchWorker:
def __init__(self, rank: int, world_size: int):
self.rank, self.world_size = rank, world_size
self.local_rank = os.environ["TPU_VISIBLE_CHIPS"] # set by Ray
def run_all_reduce(self, master_addr: str, master_port: int):
os.environ.update(MASTER_ADDR=master_addr, MASTER_PORT=str(master_port),
WORLD_SIZE=str(self.world_size), RANK=str(self.rank),
LOCAL_RANK=self.local_rank)
dist.init_process_group(backend="tpu_dist")
t = torch.ones(2, 2, device=torch.device("tpu")) * self.rank
dist.all_reduce(t, op=dist.ReduceOp.SUM)
return t.cpu().numpy()
@ray.remote(num_gpus=1)
class TorchWorker:
...
dist.init_process_group(backend="nccl")
t = torch.ones(2, 2, device=torch.device("cuda")) * self.rank
The example follows the Anyscale announcement. Everything but the resource request and the two strings is the same as on GPU.
Reserving a slice for training¶
For a plain training loop you do not start actors by hand. Ray Train's TorchTrainer takes a ScalingConfig, and with use_tpu=True it does the TPU orchestration itself: it reserves a SlicePlacementGroup for the requested topology and accelerator_type, starts one worker per TPU device, sets RANK, WORLD_SIZE, LOCAL_RANK, MASTER_ADDR and MASTER_PORT together with TorchTPU's slice-builder addresses and mesh topology, and initializes the tpu_dist process group. Inside the loop, ray.train.torch.get_device() returns the tpu device and ray.train.torch.prepare_model() moves the model there and wraps it in DistributedDataParallel. The announcement's example for a 16-chip Trillium slice:
from ray.train import ScalingConfig
from ray.train.torch import TorchTrainer
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()
This chapter uses SlicePlacementGroup only through ScalingConfig; its constructor is documented in the Ray API reference linked from the announcement. prepare_model gives you DDP; for a model that needs FSDP, the training function sets up SimpleFSDP itself, as in chapter 14.
Ray Serve LLM uses the same reservation for inference: an LLMConfig with accelerator_type="TPU-V6E", accelerator_config={"kind": "tpu", "topology": "4x4"} and placement_group_config={"bundle_per_worker": {"TPU": 1}} reserves a slice per replica and starts vLLM-TorchTPU workers across it. Chapter 18 covers the engine.
A GRPO loop is not a plain training loop: the rollout and the update are different programs with different device counts, and the driver must move data and weights between them. That is why RL frameworks on Ray start actors directly, with resources={"TPU": 1} per device, rather than through TorchTrainer.
Architecture of a Ray GRPO loop on TPU¶
The KV cache lives only on the rollout slice and the optimizer state only on the trainer slice. Of the five arrows, one carries weights; it is the one to measure.
TorchTitan's rl_nc_ray experiment is the reference layout. Its orchestrator, grpo.py, runs on the Ray head node. RayController subclasses TorchTitan's GPU RL Controller and overrides only its setup: instead of Monarch processes it launches Ray actors and wraps them in proxies that translate the controller's calls into .remote() calls and futures. It starts:
- One
RayTPUPolicyTraineractor per trainer rank, each withresources={"TPU": 1}when the trainer runs on TPU and pinned to its host, with per-rank environment variables that describe the trainer's slice to TorchTPU (process addresses, topology, host bounds). The trainers form their own process group; the update is chapter 14's sharded training step. - One
RayVLLMGeneratoractor on the rollout slice, scheduled onto the sampler node with a node-affinity strategy, which starts the vLLM engine and its tensor-parallel workers across that slice's devices.
The controller pushes the trainer's weights, starts the engine loop, and has the generator pull the first policy version before any rollout. After that, rollouts, scoring, batching and training run as concurrent loops.
Weight broadcast¶
The trainer's state dict reaches the generator through Ray's object store: the trainers put their weights in the store, and the generator's load_model_state_dict receives a reference to them with the policy version. One line in grpo.py is worth knowing before you write your own. Passed directly as an argument, a Ray ObjectRef is resolved by Ray before the method runs, which here deserializes the full state dict on the generator's driver process; the comment in the source calls the result "massive CPU/memory bottlenecks". Wrapping the reference in a list, [ref], passes the raw reference through, and the generator fetches the weights where it needs them.
The generator side has a memory problem of its own. weight_transfer_utils.py notes that after vLLM allocates its KV cache, free HBM on the rollout devices is "extremely tight (~455MB)", so the experiment syncs layer by layer (SYNC_LAYER_BY_LAYER = True) and copies to the TPU in chunks of 30 parameters, keeping the temporary footprint small. Copying a whole new state dict next to the old one would not fit.
Miles names three transports for the same handoff, and its numbers are a useful scale:
| Path | Works when | Status in Miles's TorchTPU run |
|---|---|---|
| Host shared memory | trainer and engine on one host | what the runs use today |
| Disk: write a full checkpoint, engine reloads it | across hosts | works; the slowest |
| ICI, device to device | within the TPU interconnect | planned; "about 50x faster than shared memory" in their test |
Concurrency and staleness¶
A synchronous loop (rollout, then update, then sync) leaves the trainer idle while the engine generates and the engine idle while the trainer steps. TorchTitan's RL controller runs them concurrently and bounds how stale the data may get. Rollout groups go into a work buffer with \(B = (S + 1) \cdot P\) active slots, where \(P\) is num_prompts_per_train_step (8 by default) and \(S\) is target_offpolicy_steps (3 by default); num_samples_per_prompt (8) is the GRPO group size. A FIFO look-ahead window of window_fraction (0.3) of the buffer lets the batcher skip an unfinished group at the head of the queue. The worst case age of a sample when it is trained on is
WeightSyncManager overlaps the weight push and pull with the next training step and releases buffer slots only after the pull, so, in its words, "no sample will be born stale". The controller computes each batch's policy age when the batch is consumed, against the live trainer version. And when rollout is the bottleneck the buffer never fills, so the observed staleness falls below the target: the off-policy bound is also a measurement of balance.
The companion loop¶
code/ch15_rl/grpo_loop.py is a GRPO loop small enough to read in one sitting, on a task whose answer you can check: a prompt is two digits \((a, b)\), the policy picks one of 19 answers, and the reward is 1 when it picks \(a + b\). A random policy scores 1/19. RolloutWorker samples a group per prompt and records the log-probabilities and its policy version; the driver scores the answers and calls grpo_advantages; TrainerWorker takes two AdamW steps on the clipped loss and bumps its version; then the driver syncs.
def sync_weights(self) -> dict:
exported = self._call(self.trainer, "export_weights") # {"version", "state", "fingerprint"}
payload = [self._ray.put(exported["state"])] if self._ray else [exported["state"]] # [ref], as rl_nc_ray
loaded = self._call(self.rollout, "load_weights", exported["version"], payload)
... # record both versions and both SHA-256 fingerprints, and the wall time
With use_ray=True the same two classes become actors: {"num_cpus": 1} each on a laptop, {"resources": {"TPU": 1}} each on a TPU VM, where each actor reports the TPU_VISIBLE_CHIPS Ray gave it. Without Ray installed the CPU smoke runs the loop in one process and prints a skip line for the Ray step:
$ python code/ch15_rl/grpo_loop.py --cpu-smoke
== 2. GRPO loop in one process (no Ray), 40 iterations, sync every step
mean reward, first 5 iterations 0.069, last 5 0.264
groups with signal (mean over iterations) 0.39
time split: rollout 9% update 65% sync 13% driver 13% (0.7 ms/iter)
ok: 41 syncs, versions and weight fingerprints matched every time (last v40 ad2e11db4ce00049)
ok: every rollout used the expected policy version; max staleness 0 (sync_every=1)
ok: in-process reward rose by 0.195 (needed 0.1)
== 3. the same loop, sync every 4 updates (rollouts up to 3 versions stale)
ok: every rollout used the expected policy version; max staleness 3 (sync_every=4)
== 4. the same loop with Ray actors (local Ray instance, CPU actors)
rollout actor pid 60314, trainer actor pid 60313, driver pid 60280
time split: rollout 19% update 31% sync 46% driver 4% (3.3 ms/iter)
ok: 11 syncs, versions and weight fingerprints matched every time (last v10 9629cb3768ea7bf3)
ok: v10 weights through Ray match the in-process run bit for bit (9629cb3768ea7bf3)
cpu-smoke: OK
(Lines trimmed; step 4 appears only when Ray is installed, here Ray 2.60.1.) Three things to read in it. The reward rises from the random policy's level, which on a task this simple is the evidence that the signs and the plumbing are right. The rollout used exactly the version the schedule implies, and the bytes the rollout holds hash to the same value as the trainer's. And the time split moves when the workers become separate processes: with a model this small, the trip of the weights through the object store takes almost half of every iteration. On a real model the proportions are different, but the method is the same: measure, do not assume.
Two decisions follow from this section. Where the engine and the trainer run sets the transport for the weights. How often to sync comes from the measured time split: while the sync is a small share of an iteration, sync every step and stay on-policy; when it is not, overlap it with the next training step, as WeightSyncManager does, or sync every few steps, and bound and log the staleness.
Placement decides the transport, and the measured time split decides how often to sync. Neither layout puts the engine and the trainer on the same chips, where the KV cache and the optimizer state would compete for HBM.
KubeRay on GKE¶
On GKE, Ray runs as a KubeRay RayCluster. The announcement's end-to-end tutorials, Train models on multi-host TPUs with Ray and TorchTPU and Serve LLMs on multi-host TPUs with Ray and TorchTPU, walk through the cluster setup. TorchTPU's own GKE guide, which chapter 8 follows, covers Job and JobSet and does not cover Ray. The concrete RL recipe is the walkthrough in the rl_nc_ray README, written for v6e-8:
- Build the image from
scripts/Dockerfile.ray.vllm, which contains Torch-TPU, 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 on the cluster 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.yamlThe manifest's worker group asks for two replicas (two slices), each of two hosts (
numOfHosts: 2), withgoogle.com/tpu: "4"per worker pod and node selectorscloud.google.com/gke-tpu-accelerator: tpu-v6e-sliceandcloud.google.com/gke-tpu-topology: 2x4: one v6e-8 slice for the trainer and one for the generator. 4. Port-forward the head service (kubectl port-forward svc/ray-tpu-v6e-cluster-head-svc 8265:8265 10001:10001) and submit withbash torchtitan/experiments/tpu/rl_nc_ray/scripts/e2e_recipe_gke.sh 0.6b(or1.7b,4bfor the Qwen3 sizes). 5. Follow the job withray job logs <raysubmit_id> --address="http://127.0.0.1:8265", and plot reward, loss, generation time and training time withscripts/plot_metrics_from_log.py.
The script runs ray job submit ... -- python3 -m torchtitan.experiments.tpu.rl_nc_ray.grpo --module alphabet_sort --config rl_grpo_qwen3_0_6b_varlen with 8-way tensor parallelism on both the generator and the trainer, --trainer.parallelism.data_parallel_shard_degree 1, --compile.no-enable and --async_loop.num_training_steps 10, and passes PYTHONPATH to the workers through Ray's runtime_env. The README describes the trainer's sharding as "2D sharding (FSDP x DP)"; the script as checked in sets tensor parallelism instead, so read the flags rather than the 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.
Failure modes¶
| Symptom | Likely cause | What to do |
|---|---|---|
| Generator host CPU and memory spike at every sync; the sync takes far longer than the bytes justify | 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, not during generation | The 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 |
| Sync time grows with model size and dominates the step | Disk or cross-host transport; sync every step | Overlap the sync with the next step, sync every few steps and log staleness, or keep both sides on one host and use shared memory |
| Trainer idle most of the step; observed staleness below the target | Rollout is the bottleneck: generation is slower than training | Measure generation and training time; move devices to the rollout side, lower the group size, or cap response length |
| Rollout engine waits on the trainer; staleness at its bound | Training is the bottleneck | Move devices to the trainer, or accept more off-policy steps within the bound |
| Every few steps one takes minutes; step time never settles | 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, as padding_packing_utils.py does; bucket (chapter 7) |
| Reward flat although the loss moves; few groups have signal | Groups all right or all wrong: zero advantages | Raise the group size, pick easier or harder prompts, drop untrainable groups before batching |
Loss inf or NaN after a sync |
Engine and trainer log-probabilities disagree badly, or the engine returned non-finite log-probabilities | Clamp the log-ratio and drop non-finite tokens (DAPOLoss); check that the engine holds the version you think |
The recompile row deserves a closer look, because RL makes it worse than pre-training does. Responses have different lengths, so the packed training batch changes shape from step to step. The module docstring of padding_packing_utils.py puts it bluntly: on TPU, any change in batch size, sequence count or total tokens triggers a new compilation, "taking up to 10+ minutes and causing compilation memory spikes." Its fix is chapter 7's: pad every training batch to a fixed bound (its example is exactly 4,096 tokens across 64 sequences), pad the variable-length attention metadata to a fixed sequence count, and give padding sequences an advantage of 0, so they add nothing to the loss. The configs the GKE script runs are the _varlen variants for this reason.
Verifying the result¶
1. The reward rises on a task you can verify. Before a real model, run the loop on a toy task whose reward is unambiguous and whose random-policy score you know. The companion loop starts at 0.069 (a random policy's 1/19 is 0.053) and reaches 0.264 after 40 iterations at the default group size of 8 (the smoke run above; the chart below is a separate 100-iteration sweep, where group size 8 ends at 0.44); tests/ch15 asserts the rise. A flat curve there points at the plumbing: sign of the advantage, mask, which policy produced old_logprobs. On a real run, log the mean reward per step (rollout_reward/_mean in TorchTitan's logs, which plot_metrics_from_log.py plots) and the fraction of groups with signal. Run more than one seed before you call two curves different: the Miles team ran two seeds on TPU and two on GPU and judged the TPU reward and response-length curves equal "within seed-to-seed variation".
This is a toy computation on a CPU, run by code/ch15_rl/grpo_loop.py; it is not a TPU measurement. Read the two panels together. The reward flattens as the fraction of groups with signal falls: the policy has learned some prompts completely and given up on others, and both kinds of group return zero advantages. Larger groups keep signal longer but cost proportionally more rollouts per step; this is one seed on a toy task, a picture of the mechanism, not a benchmark.
2. You know where the time goes. Time the rollout, the update and the sync separately, per step, after warm-up, and keep them in the log. The companion loop prints the split; TorchTitan's Ray experiment logs generation time, training time and weight-sync time, and its plotting script charts them per step. The numbers tell you which side to give more devices and whether the sync deserves engineering. They also catch compilation: a step whose training time is far above its neighbours is a recompile until proved otherwise.
3. The engine samples with the weights you think. Version numbers are necessary but not sufficient: a sync can report success and leave stale or partially copied weights behind. Check three things.
- After every sync, the version the engine reports equals the trainer's, and a hash of the weights on each side matches. The companion
check_versionsdoes both with a SHA-256 fingerprint; its tests show that a skipped sync and a corrupted copy are each caught. - The staleness of every batch stays inside the bound you configured: below
sync_everyin the companion loop, belowmax_offpolicy_stepsin TorchTitan's controller, which reports policy age per batch. - Right after a sync, the trainer's log-probabilities for the tokens the engine just sampled should match the engine's.
DAPOLosslogs this asbit_wise/logprob_diff/mean(the mean of \(\log p_\text{trainer} - \log q_\text{engine}\) over response tokens) andloss/ratio_mean, which should sit near 1 on on-policy data. A persistent gap means the two sides are not computing the same function: different weights, a different dtype, or different kernels. Bitwise-identical log-probabilities between engine and trainer are on Miles's list of next steps, so expect a small gap, and alert on a growing one.
Worked problems¶
Problem 1. A group of four completions scores [1, 1, 0, 0] and another [0.9, 0.8, 0.9, 0.8]. Compute GRPO and Dr.GRPO advantages for both and say what the comparison teaches.
Answer
First group: mean 0.5, population standard deviation 0.5. GRPO: \(\pm 0.5 / (0.5 + 10^{-6}) \approx [1, 1, -1, -1]\). Dr.GRPO: \([0.5, 0.5, -0.5, -0.5]\). Second group: mean 0.85, standard deviation 0.05. GRPO: \(\pm 0.05 / 0.050001 \approx [1, -1, 1, -1]\). Dr.GRPO: \([0.05, -0.05, 0.05, -0.05]\). GRPO gives both groups the same unit-size advantages, although the second group's samples differ by a tenth of the first's: normalization amplifies small reward differences. Dr.GRPO keeps the reward's scale, so the nearly tied group barely moves the policy. That is the trade-off behind TorchTitan's default of should_std_normalize=False.
Problem 2. A reward model returns [0.7, 0.7, 0.7, 0.7000001] for a group because of float noise. What does grpo_advantages return with the default epsilon, and with eps=0?
Answer
The rewards are not all exactly equal, so the constant-group shortcut does not apply. The centered rewards are \([-2.5, -2.5, -2.5, 7.5] \times 10^{-8}\) and the population standard deviation is about \(4.3 \times 10^{-8}\). With \(\epsilon = 10^{-6}\) the denominator is about \(1.04 \times 10^{-6}\), so the advantages are about \([-0.024, -0.024, -0.024, 0.072]\): small. With \(\epsilon = 0\) they are \([-0.577, -0.577, -0.577, 1.732]\), the same as a group with one real success, built from a difference of \(10^{-7}\). Keep the epsilon, or round rewards that are meant to be discrete.
Problem 3. With TorchTitan's defaults, num_prompts_per_train_step=8, target_offpolicy_steps=3 and window_fraction=0.3, how many rollout groups are active at once, how many completions is that, and what is the worst-case policy age of a trained sample? What changes with window_fraction=None (strict FIFO)?
Answer
\(B = (3 + 1) \times 8 = 32\) active groups; with 8 samples per prompt, 256 completions in flight. \(W = \lfloor 0.3 \times 32 \rfloor = 9\), so the bound is \(\lfloor (32 + 9 - 2) / 8 \rfloor = \lfloor 39/8 \rfloor = 4\) steps. With strict FIFO \(W = 1\) and the bound is \(\lfloor 31/8 \rfloor = 3\), the target itself. The window buys throughput (finished groups need not wait behind a slow one) at the price of one extra step of worst-case staleness.
Problem 4. You move the announcement's TorchTrainer example from a 4x4 v6e slice to the 2x4 v6e-8 slice that the rl_nc_ray manifest uses. Which ScalingConfig fields change, and what stays the same in the training function?
Answer
num_workers=8 (one worker per chip) and topology="2x4"; use_tpu=True, accelerator_type="TPU-V6E" and resources_per_worker={"TPU": 1} stay. The training function does not change: get_device() still returns the worker's tpu device and prepare_model() still wraps the model in DDP over tpu_dist, now with a world size of 8. Ray Train reserves the slice as one SlicePlacementGroup, so the eight workers land on the same ICI-connected slice.
Problem 5. A GRPO run on two v6e-8 slices logs, per step after warm-up: generation 40 s, training 10 s, weight sync 6 s, in a synchronous loop. Where does the time go, and what two changes would you try first?
Answer
The step is 56 s: 71% generation, 18% training, 11% sync, and the trainer slice is idle about 82% of the time. Rollout is the bottleneck, so first make generation and training overlap (an asynchronous loop with a bounded off-policy target, as TorchTitan's controller runs), which hides the 10 s of training behind the next generation. Second, reduce or rebalance generation: shorter maximum response length, a smaller group size if most groups already have signal, or more devices on the rollout side if the layout allows it. The 6 s sync is worth overlapping too, but it is not the first lever.
Problem 6. In the companion loop with sync_every=4, what policy version does the rollout use at iterations 0 to 11, how stale is each batch, and how would check_versions react if the sync after iteration 7 silently failed?
Answer
Versions 0, 0, 0, 0, 4, 4, 4, 4, 8, 8, 8, 8, with staleness 0, 1, 2, 3 repeating: the trainer has made that many updates beyond the weights that produced the batch. If the sync after iteration 7 failed, iterations 8 to 11 would sample with version 4, and check_versions would report each of them (expected v8, used v4) and their staleness of 4 to 7, outside \([0, 4)\). If the sync reported version 8 but copied the wrong bytes, the version check would pass and the fingerprint check would fail: that is why both exist.
Quick questions¶
- Name the five stages of a GRPO step and which ones run on TPU devices.
- Why does TorchTitan's Ray experiment put the generator and the trainer on separate slices, and what does that cost?
- Write the GRPO advantage. What does a group with identical rewards contribute, and why does that make group size matter?
- Where does epsilon go in TorchTitan's estimator, and what does it protect against?
- How does a Ray actor get exactly one TPU device, and how does it know which one?
- What does
ScalingConfig(use_tpu=True, ...)do that a set of hand-started actors does not? - Why does
rl_nc_raywrap the weights'ObjectRefin a list? - What bounds how stale a trained sample can be in TorchTitan's controller, and what does an observed staleness below the target tell you?
- Why do variable response lengths cause recompiles on the trainer, and how is it fixed?
- Name the three checks that an RL run is working.
Key takeaways¶
- RL post-training alternates serving (rollout), host work (reward and advantage) and training (update), and must move the weights back after each update. The loop is limited by its slowest stage and the sync.
- GRPO uses the group as its baseline: \(A_i = (r_i - \text{mean}) / (\text{pstdev} + 10^{-6})\), or Dr.GRPO's \(r_i - \text{mean}\), TorchTitan's default. Groups with identical rewards give zero advantage, so a large share of them is wasted rollout compute.
- Ray on TPU gives each worker one device:
resources={"TPU": 1}, isolated throughTPU_VISIBLE_CHIPS,torch.device("tpu")and"tpu_dist"inside.ScalingConfig(use_tpu=True, topology=..., accelerator_type=...)reserves a whole slice forTorchTrainer; RL loops start actors directly. - TorchTitan's
rl_nc_rayruns the trainer and the vLLM generator on separate slices so that training state and the KV cache never share HBM, with the controller on the Ray head node and weights through the object store; it deploys on GKE as a KubeRayRayCluster. - Weight sync is the cost to engineer: pass references, not resolved state dicts; sync layer by layer when the KV cache leaves little HBM; overlap the sync with the next step and bound the staleness.
- Pad training batches to fixed shapes, or variable rollout lengths recompile the trainer; chapter 7's tools apply unchanged.
- Trust a run when its reward rises on a verifiable task, you can show where every second of a step goes, and the engine's weights match the trainer's by version, by hash and by log-probability.
References¶
- Announcing Ray support for PyTorch on Google TPUs: one worker per TPU device,
TPU_VISIBLE_CHIPS,SlicePlacementGroup,TorchTrainerwithScalingConfig(use_tpu=True)and Ray Serve LLM on TPU - Train models on multi-host TPUs with Ray and TorchTPU
- Serve LLMs on multi-host TPUs with Ray and TorchTPU
- TPU Non-Colocated RL with Ray: the non-colocated layout, the KubeRay walkthrough, the manifest and the job script
- TorchTitan
rl_nc_raysource:RayController, the[ref]wrapper, layer-by-layer weight transfer and static padding - TorchTitan RL experiment: the advantage estimator, the DAPO and GRPO losses, the asynchronous controller and
WeightSyncManager - SGLang-TorchTPU: PyTorch-Native Production Serving on TPUs: the Miles GRPO run on TPU, its weight-sync paths and its parity check against GPUs
- Get started with TorchTPU on GKE:
JobandJobSetworkloads - TorchTitan on Cloud TPU: SimpleFSDP, Graph Trainer, Ray and GRPO: RL as a heterogeneous-compute problem and a GRPO pipeline on Ray
- TorchTitan, SimpleFSDP and Ray GRPO sample: group-relative advantages, a GRPO policy loss and a Ray GRPO pipeline
- Companion code for this chapter



