Agentic RL Infrastructure

One slow rollout can hold a whole batch of GPUs idle. Let the learner run a few updates ahead and the same hardware does several times the work, at the price of slightly stale data.

Drag the allowed lag from 0 to 8. Watch the teal bars fill the gaps and count the learner updates. Then we build, piece by piece, the system underneath: the step, the straggler math, the staleness fix, and the long tail of failures that decides whether a run survives.

You need a rough idea of how a language model writes text and a little Python. We build the reinforcement learning and the systems ideas from zero.

Grounded in the IMPALA, Asynchronous RLHF, AReaL, HybridFlow, OpenRLHF, Kimi k1.5, LlamaRL and Magistral papers; the sources are listed with their arXiv links in the last chapter. The rollout times in the instrument are illustrative and made up by us.

Let the learner run ahead

0 (synchronous)

Illustrative simulation, run live in your browser: 96 actor slots, a batch of 64 rollouts per update, 60 s per learner update, one simulated hour. Rollout times are made up: median 60 s, a long-tailed spread, and 1.5% that hang for 600 s. The chart shows the first 15 minutes of 12 slots; the numbers cover all 96 slots and the full hour.

Chapter 0

The Friday Run

See why one hung sandbox can idle a whole cluster, and why a reinforcement learning run is a factory with a long tail

It is Friday evening. You have a coding agent training run on 96 GPUs. Each training step starts 64 tasks. For each task, the model reads a bug report, opens files, edits code and runs the tests in a sandbox. A sandbox is a locked, throwaway computer where the agent can do things without hurting anything real.

Sixty-three of the 64 tasks finish in about a minute. The sixty-fourth runs a test suite that never ends. Nothing crashes and nothing logs an error. The run just waits, ten minutes, while 95 GPUs do nothing and the electricity meter keeps turning.

This is the problem of this lesson. Training an agent with reinforcement learning is not one clean loop on one machine. It is a factory with thousands of small jobs, and a few of those jobs are always slow, broken or strange.

The words we need first

An agent is a language model in a loop. It writes a step, calls a tool, reads the result and writes the next step. One full attempt at one task, from the first prompt to the final answer, is a rollout. The record of everything said and done in it is the trajectory.

Reinforcement learning (RL) trains a model by trial and score. The model attempts a task. A checker gives the attempt a number, the reward, such as 1 if the tests pass and 0 if not. The training step then makes the model a little more likely to repeat attempts that scored well. Chapter 1 shows this in detail.

A batch is the group of rollouts that one training step uses. The part of the system that makes rollouts is made of actors. The part that changes the model is the learner. Think of a restaurant: actors are cooks making dishes, the learner is the chef who tastes a tray of dishes and rewrites the recipe.

Feel the wait

Here are 64 made-up rollout times. Most cluster near a minute. The slider sets how many rollouts the training step waits for. Drag it slowly past 26 and watch the bar chart change.

Wait for the slowest

Each bar is one rollout, taller means slower. The dashed line is the slowest in the batch. The step cannot start until that line is reached. The teal area is work done, the empty area above it is waiting.

24

Illustrative: the durations are made-up numbers (median 60 s, a long-tailed spread, and rollout 26 is one of the 1.5% that hang for 600 s). The same numbers drive the instrument at the top of this page. Slot use is the sum of the durations divided by (batch size times the slowest duration).

Below 26 rollouts the slowest one takes 274 s, and the slots do useful work between a quarter and a third of that time. Cross 26 and one hung rollout stretches the line to 600 s. Slot use drops to about 17%. Every extra rollout you add raises the odds that the batch holds one more slow one.

Why a tail, and why it is not only slowness

The pattern has a name: the long tail. Most events are quick and similar. A few are extreme, and those few decide the total cost. Web services know it as tail latency. Agent training has it worse, because agent tasks are open-ended. A shell command can loop. A test can wait for a network that does not exist. A model can write 30,000 tokens without stopping.

Slowness is only the gentle form of the tail. The harsher forms are failures. The sandbox runs out of memory. The tool returns half of a JSON object. The reward service is down for four minutes. A trajectory arrives with a score of 1 that nobody can explain. At thousands of rollouts per hour, each of these happens several times an hour, not once a month.

So the job of the infrastructure is two jobs at once. Keep the GPUs busy despite the slow cases. Keep the training data honest despite the broken cases. Chapters 2 to 4 cover the first job, and chapters 5 to 9 cover the second.

The road

  1. Anatomy of a step: actors, environments, reward, learner, and the record between them.
  2. The straggler math: why waiting for the batch wastes GPUs, with numbers.
  3. Asynchronous training: let the learner run ahead, and correct for stale data.
  4. Partial rollouts: keep very long agents from setting the pace.
  5. The long tail of failures: seven kinds, four responses, and the bias of each.
  6. Observability: per-environment rates, trajectory sampling, dead-letter queues.
  7. Determinism: logging and replay when order is random.
  8. Capacity planning: sizing the pools from four numbers.
  9. Three silent failures: break the pipeline and find each break.
  10. Field guide: numbers, checklist, core loop, sources.
A synchronous training step uses 64 rollouts. One rollout hangs for ten minutes while the other 63 finish in one minute. What does the step cost?

Chapter 1

Anatomy of an Agentic RL Step

Follow one training step from prompt to updated weights and see the record that moves between actors, environments, reward and learner

One task enters the system: "Fix the bug where parse_date('2024-02-30') crashes." Follow it for one training step. Seven parts touch it, and each one hands the next a specific piece of data. If you know that data, you can debug the whole system.

The seven parts

The task pool holds prompts. The actor is the model being trained, wrapped in an inference engine, a program built to generate tokens fast for many requests at once. The environment is the sandbox and the tools the agent uses. The reward service scores the result. The buffer holds finished trajectories until a batch is ready. The learner changes the weights. Weight sync copies the new weights back to the actors.

Drag through the stages below. The box on the right shows the real shape of the data at each hand-off.

Walk one step

The lit box is the current stage. The text below it is the data that stage receives or makes. Press Play, or drag the stage slider.

1 of 7

Illustrative toy values: task text, rewards, lengths and the 70-billion-parameter size are made up to show shapes and arithmetic. The structure (task, rollout, reward, group baseline, masked loss, weight sync) is the standard design used by the systems in the sources.

What the learner needs to know about RL

Here is all the RL you need, in three steps. First, the actor tries the same task several times, say eight. Second, the reward service scores each try. Third, the learner compares each try with the group average.

The comparison gives each try an advantage: its reward minus the group mean. With rewards 1, 0, 0, 1, 0, 0, 0, 1 the mean is 3/8 = 0.375. A passing try gets advantage +0.625. A failing try gets −0.375. The update raises the probability of every token in the passing tries and lowers it in the failing ones, in proportion to the advantage.

This is the idea behind policy gradient methods; our policy gradients lesson builds it from zero. The group-average trick is the one GRPO uses, as in our GRPO and DAPO lesson. For this lesson one fact matters most: the learner needs whole, scored trajectories, and it needs them in groups.

The record that moves

A trajectory is a record. Here is the one a worker sends to the buffer. Notice what is in it besides text: which policy version wrote it, how it ended, and a flag for each token that says whether the model wrote it.

pythonfrom dataclasses import dataclass
import numpy as np

@dataclass
class Trajectory:
    rollout_id: str        # "swe-1042/g3/a0" = task / group member / attempt
    policy_version: int    # which weights wrote it: needed for staleness (Ch 3)
    tokens: np.ndarray     # int32 [T]: prompt, model text, tool results, in order
    loss_mask: np.ndarray  # bool  [T]: True only where the MODEL wrote the token
    logprobs: np.ndarray   # float32 [T]: log-prob the actor gave each token
    reward: float          # from the verifier, e.g. 1.0 if all tests pass
    status: str            # "ok" | "timeout" | "oom" | "bad_tool_call" | ...

def advantages(group):
    r = np.array([t.reward for t in group], dtype=np.float32)
    return r - r.mean()   # +0.625 for a pass, -0.375 for a fail, in the example

The loss mask deserves a moment. The sandbox wrote the test output, not the model. If the learner trained on those tokens, it would learn to predict test output, which wastes the update and teaches nothing about decisions. So the mask is True on the model's own tokens and False on everything else. A multi-turn agent trajectory alternates between the two, which makes the mask a patchwork, not one block.

Batching adds a second shape problem. Trajectories have different lengths, so the learner pads them to the longest one in the batch, to a rectangle of shape [B, Tmax]. One 60,000-token trajectory in a batch of 64 makes the other 63 mostly padding. We return to this cost in chapters 4 and 8.

Weight sync: the step nobody draws

After the update, the actors still hold the old weights. A 70-billion-parameter model in 16-bit numbers is 70 billion times 2 bytes, which is 140 GB. Moving it to every actor pool takes seconds even on a fast network, and during that time the actors either pause or keep working with the old version. That choice is the core of Chapter 3.

Every system in our sources solves the same two puzzles: how to place actors and learner on GPUs, and how to move weights between them. HybridFlow (verl) and OpenRLHF are frameworks that wire these roles together for RLHF training. LlamaRL uses a single controller and reports scaling to thousands of GPUs. We keep to the shared logic, not each product.

Why does the learner set the loss mask to False on tool output tokens?

Chapter 2

The Straggler Math

Compute why a synchronous batch runs at the speed of its slowest rollout and how fast that waste grows with batch size

A restaurant takes a table of 64 orders and promises to serve every dish at once. Sixty-three dishes take five minutes. One dish takes fifty. The table eats nothing until minute fifty, and 63 cooks stand idle. Nobody calls the kitchen slow. One order was slow, and the promise tied all 64 together.

A synchronous RL system makes this same promise. The learner starts a step only when every rollout in the batch is done. Let us measure what that costs.

One slow rollout in the batch

Say each rollout has a chance p of being a slow one, for example a hung test or a 30,000-token ramble. The chance is independent for each rollout. For a batch of B rollouts, the chance that none is slow is (1 − p) multiplied by itself B times. So the chance that at least one is slow is the rest.

P(stall)
The chance that a step has at least one slow rollout, so the whole step waits.
p
The chance that one rollout is slow. For 1 in 100, p = 0.01.
B
The number of rollouts the step waits for.

p = 0.01, B = 64: 1 − 0.9964 = 1 − 0.525 = 47%    B = 512: 1 − 0.99512 = 99.4%

Read that again. A 1% problem in one rollout becomes a 47% problem in a step of 64, and a near-certainty in a step of 512. Bigger batches, which RL likes for steadier learning, make the stall almost permanent.

From stall chance to wasted GPUs

Now count the time. Make the toy model plain: a normal rollout takes 60 s, a slow one takes 600 s, ten times longer. A step takes 600 s if it holds a slow rollout and 60 s if not.

For B = 64: expected step time = 0.475 × 600 + 0.525 × 60 = 285 + 31.5 = 316 s. Real work per rollout, on average, is 0.99 × 60 + 0.01 × 600 = 65.4 s. Utilization, the share of slot time spent on real work, is the ratio: 65.4 / 316 = 21%.

For B = 512: step time = 0.994 × 600 + 0.006 × 60 = 597 s. Utilization = 65.4 / 597 = 11%. Of every 100 GPU-hours you pay for, 89 are spent waiting.

The slow case is not required for waste. Even when every rollout is "normal", their times vary, and a step waits for the largest of B random numbers. That largest value grows as B grows. Try both effects in the device.

Grow the batch

The warm curve is the chance a step holds a slow rollout. The teal curve is slot utilization. The tick marks your batch size. Raise the tail chance and see how early the curves bend.

64
1.0%

Illustrative: normal rollouts take 60 s times a spread (median 60 s), slow ones take 600 s. Utilization is a sample of 200 simulated batches; the stall curve is the formula above. With a 0% tail the device still shows waste from ordinary variation.

The symptom, the measurement, the fix

Symptom. The GPU dashboard shows inference nodes at 15 to 25% busy on average. Training steps take far longer than the median rollout time would suggest. Adding GPUs barely speeds anything up.

Measurement. Log two times for every step: the wall time of the step, and the median rollout time inside it. Their ratio is the straggler ratio. A ratio near 1 means rollouts are even. A ratio of 5 or 10 means the step is held hostage.

pythondef straggler_report(step_logs):
    # step_logs: list of dicts like {"wall_s": 612.0, "rollout_s": [58.1, 61.0, ..., 600.0]}
    for s in step_logs:
        r = np.array(s["rollout_s"])
        ratio = s["wall_s"] / np.median(r)
        util = r.sum() / (len(r) * s["wall_s"])   # share of slot-time that was real work
        print(f"ratio {ratio:5.1f}   util {util:4.0%}")

Fix. Three families of fixes exist. You can cap rollout time, which turns slow cases into failures (Chapter 5 shows the bias this adds). You can over-sample, start 80 rollouts and train on the first 64 that finish, which quietly favours short tasks (Chapter 9). Or you can stop making the learner wait. That last one is the subject of Chapter 3, and the asynchronous systems in our sources choose it: AReaL reports up to 2.77× training speedup over synchronous systems with the same GPUs, and LlamaRL reports up to 10.7× over DeepSpeed-Chat-like systems on a 405B-parameter policy.

One rollout in 100 is slow. A synchronous step waits for 512 rollouts. About how often does a step contain a slow rollout?

Chapter 3

Asynchronous Training and Stale Data

Let the learner run ahead of the actors, then pay for it with importance weights and a staleness limit

The learner finishes an update at minute three. Four hundred rollouts are half done on the actors, all written with the old weights. You have two choices. Stop and throw them away, or let them finish and use them. Using them is faster. It also means the learner trains on text that its own current model might not have written.

On-policy, off-policy, and lag

The policy is the model as a decision maker: given the text so far, it gives each possible next token a probability. Data is on-policy when the same policy that you are now training wrote it. Data is off-policy when an older version wrote it. We call the writer the behaviour policy, written μ, and the model being trained the target policy, written π.

The lag (or staleness) of a sample is the number of updates between the version that wrote it and the version that now learns from it. A sample written by version 38 and used at version 41 has lag 3. Synchronous training has lag 0 by construction. Every asynchronous design lets lag grow, and the design question is how far.

Why does this hurt? The policy gradient formula assumes samples came from π. A sample from μ shows what μ liked, and μ may like things that π has already stopped doing.

The repair: reweight each sample

Imagine a token that the old policy picked with probability 0.2 and the new policy would pick with probability 0.5. The new policy would have produced this token 2.5 times as often. So we count this sample 2.5 times. Now a token the old policy picked at 0.2, but the new one picks at 0.01. It would appear 0.05 times as often. We count it 0.05 times. This is importance sampling; our importance sampling lesson derives it. The weight for one token is the ratio of the two probabilities.

ρ
The importance weight: how many times more (or less) often the new policy would have made this choice.
π(a | s)
The probability the policy being trained gives to token a in text state s.
μ(a | s)
The probability the older, data-writing policy gave to the same token.

The weights fix the average but they cost something. A few huge weights can dominate the batch. Statisticians measure the damage with the effective sample size (ESS): the number of fresh, equally weighted samples your weighted batch is worth. For weights w, ESS = (sum of w)2 / (sum of w2).

Worked example with four samples and weights 2.5, 0.05, 1 and 1. The sum is 4.55, so its square is 20.7. The squares add up to 6.25 + 0.0025 + 1 + 1 = 8.25. ESS = 20.7 / 8.25 = 2.5. Four samples are worth two and a half.

One more tool. Truncation caps each weight at a ceiling, say 2. The weights become 2, 0.05, 1, 1 and ESS rises to 2.7. You accept a small bias, because the capped sample no longer counts as much as it should, and in return you lose the wild variance. IMPALA calls its version V-trace: it truncates the weights, using ceilings it names ρ̄ and c̄, inside a multi-step value correction.

Use the device to see how ESS responds to lag and to the size of each update.

Age the data

A toy policy chooses among 8 actions. Purple bars are the stale policy that wrote the data. Warm bars are the current policy. The number above each pair is the importance weight. Raise the lag and see how many samples your batch is really worth.

3

Illustrative toy: 8 actions, each update moves the logits along one fixed direction by the step size. ESS is exact: it equals 1 divided by the sum of π2/μ, as a share of the batch. Weights are capped at 2 for the clipped share. Real policies have vocabularies of tens of thousands of tokens.

What the systems report

IMPALA split acting from learning, and used V-trace to correct for the gap; the paper reports that it scales to thousands of machines without losing data efficiency, tested on DMLab-30 and Atari-57. Asynchronous RLHF applied the same idea to language models: generate with an older policy while training on the newest. It reports about 40% faster training on an instruction-following task with an 8B model, and about 70% faster on GSM8k math with a 1B model, at matched final performance. It finds online DPO the most robust algorithm to off-policy data, and robustness improves as the policy gets larger.

AReaL is built for long reasoning. It balances the rollout and training workers to control staleness, uses a staleness-enhanced PPO variant, and reports up to 2.77× speedup over synchronous systems on the same GPUs, with matched or better final performance. LlamaRL reports up to 10.7× on a 405B model, with the advantage growing with model size. In every case the system puts a limit on lag. Nobody lets it grow without bound.

The gate that sets the limit

The hero instrument at the top uses the simplest limit: a slot may start a new rollout only if the total started so far is below (version + 1 + k) × batch size. With k = 0 this is synchronous. With k = 2 the actors may run two batches ahead. Here it is as code, with the truncated weight in the loss.

pythonclass StalenessGate:
    def __init__(self, batch, max_lag):
        self.batch, self.max_lag, self.started, self.version = batch, max_lag, 0, 0

    def may_start(self):                       # called by every idle actor slot
        return self.started < (self.version + 1 + self.max_lag) * self.batch

def policy_loss(logp_new, logp_old, adv, mask, ceiling=2.0):
    rho = torch.exp(logp_new - logp_old)         # pi / mu per token, shape [B, T]
    rho = torch.clamp(rho, max=ceiling)          # truncate: bias for variance
    return -(adv[:, None] * rho * mask).sum() / mask.sum()
An importance weight is capped at 2. What does the cap trade?

Chapter 4

Partial Rollouts for Long Agents

Cut a long trajectory into pieces that span several iterations, so the longest agent no longer sets the pace

A web research agent searches, reads a page, searches again and keeps notes. Some tasks finish in 6,000 tokens. Others reach 100,000. A model that writes about 40 tokens per second needs 2,500 seconds, over 40 minutes, for the long one. A training iteration that lasts ten minutes cannot hold it.

Asynchronous training (Chapter 3) lets the learner skip waiting for slow rollouts. It does not answer a harder question: what do you do with a rollout that is slower than a whole iteration? If you drop it, you never learn from long tasks. If you wait for it, you are back to the straggler.

Cut the rollout into pieces

The answer is the partial rollout. Give each iteration a fixed budget of new tokens, for example 16,000 per trajectory. When a trajectory hits the budget without finishing, do not drop it. Save it, with its text so far, and its environment, and continue it in the next iteration. The trajectory is finished over several iterations, like a long film watched in several evenings.

The Kimi k1.5 report names long-context scaling as a key ingredient of its recipe; its method of partial rollouts is the technique this chapter teaches. (The abstract does not describe it, so we give no numbers from the paper here. The numbers below are ours and illustrative.)

Three things must be true for this to work. First, the sandbox must survive between iterations, or be restorable. A browser tab with 40 minutes of history cannot be rebuilt in a second. Second, each token needs its own record of which policy version wrote it, because the first 16,000 tokens of a trajectory were written by older weights than the last 16,000. Third, the learner must apply the importance correction from Chapter 3 token by token, using the log-probability stored at the time each token was written.

The record from Chapter 1 gains one field: version: int16[T], one version number per token. A 6-iteration trajectory carries six different numbers in it. This is a trajectory with a mixed past, and the weights handle it.

Worked example with five trajectories

Five tasks need 6k, 9k, 14k, 38k and 90k tokens. The budget is 16k per iteration. Iterations needed are the length divided by 16k, rounded up: 1, 1, 1, 3 and 6.

Without partial rollouts, the 38k and 90k trajectories hit the cap and are dropped. The batch keeps three trajectories with mean length (6 + 9 + 14) / 3 = 9.7k tokens. The true mean is (6 + 9 + 14 + 38 + 90) / 5 = 31.4k tokens. The learner sees tasks that are 3 times shorter than reality. It never receives a signal about what makes long tasks succeed.

With partial rollouts, the iteration length is bounded by the budget, 16,000 / 40 = 400 s, instead of 90,000 / 40 = 2,250 s. The longest trajectory finishes in the sixth iteration and contributes then. The cost is that the 90k trajectory holds a sandbox for six iterations, and each of its tokens may carry a different version.

Set the budget

Each row is one trajectory, drawn to its length in tokens. Colours show which iteration wrote each stretch. Move the budget. Then switch partial rollouts off and watch which rows are dropped.

16k tokens

Illustrative: 12 made-up trajectory lengths from 2k to 62k tokens, generation speed 40 tokens per second per trajectory, and the iteration ends when its budget is spent. Lengths are drawn from a long-tailed spread (median about 12k). Nothing here is a measurement from the Kimi k1.5 report.

Symptom, measurement, fix

Symptom. Training reward climbs, yet the agent gets worse on long tasks. The mean length of trajectories in the batch slowly drops over the run, while the task pool has not changed.

Measurement. Compare the length distribution of rollouts started with the length distribution of rollouts consumed by the learner. If consumed is much shorter, long ones are being lost. A simple number is the survivor ratio: mean consumed length divided by mean started length. Below 1 means long tasks are leaking away.

Fix. Keep unfinished trajectories and continue them, as here. If you cannot hold the sandbox, store the tool-call history so you can replay it into a fresh sandbox. Replay costs time and can fail, so treat replay failures as a failure class of their own (Chapter 5).

pythondef run_iteration(actor, carry, new_tasks, budget, version):
    done, still = [], []
    for traj in carry + new_tasks:
        # appends tokens, logprobs and version=[version]*n_new to the trajectory
        traj.generate(actor, max_new_tokens=budget, policy_version=version)
        (done if traj.finished else still).append(traj)
    return done, still   # `still` resumes next iteration with newer weights
A trajectory is finished over four iterations. Why must each token store its own policy version and log-probability?

Chapter 5

The Long Tail of Failures

Sort seven ways a rollout dies and see what each response (retry, drop, zero, quarantine) does to your data

Monday morning. The overnight run launched 40,000 rollouts. The dashboard says 3,100 of them did not end normally. Some sandboxes died. Some tools timed out. Some trajectories ended mid-sentence. A few scored a perfect 1.0 that nobody trusts. What do you do with each group?

The answer is never the same for all. The right response depends on one question: whose fault was it? If the infrastructure failed, the rollout says nothing about the model, so you should repair and retry, not train on it. If the model failed, the rollout is exactly the signal training needs, so you should keep it. Mixing the two up is the most common way to damage a run.

Seven ways a rollout dies

FailureHow you detect itSafe responseBias if you get it wrong
Environment crashContainer exits, or no heartbeat for 30 sRetry on a fresh sandbox, at most 2 times, then quarantine the taskHeavy tasks crash more, so dropping them biases the data to easy tasks
Tool timeoutA command passes its time limitReturn "timed out" to the agent as a tool result and let it recoverIf the disk was slow, you punish the model for the host
Sandbox out of memoryExit code 137 or a kernel kill messageModel's program: keep, reward as scored. Harness's process: retryMislabelling teaches the model that memory use is free, or that it is deadly
Malformed tool callParser error on the model's outputReturn the error to the model, allow a few repairs, keep the trajectoryDropping removes the signal that teaches correct format
Truncated contextLength hit the limit before a final answerMark it truncated and apply a fixed reward rule, or continue it (Chapter 4)Training as if finished rewards runaway length
Poisoned trajectoryReward outlier, repeated text, log-probs that are not numbers, edited test filesQuarantine for review, exclude from the batch, count itHiding hacks hides that the model is hacking
Reward service outageScoring call fails or times outHold the trajectory, retry with backoff, set a deadlineScoring 0 during an outage teaches that everything fails

Two rows deserve more words. A poisoned trajectory is one that should not teach the model what its reward says. The classic case is reward hacking: the agent edits the test file so the tests pass. The reward is 1.0 and the behaviour is the opposite of what you want. Quarantining it protects the update, and counting it tells you the model found a hole.

The reward service outage is the quiet one. If the verifier is down for four minutes and the pipeline scores missing results as 0, every rollout in that window looks like a failure. The reward curve dips, and the learner is pushed away from behaviours that were fine.

Four responses, and the bias of each

Take a toy task pool. A third of tasks are easy (the model passes 90%), a third medium (50%), a third hard (10%). True pass rate: 50%. Failures are not even: hard tasks run longer and touch more tools, so they fail more often. Say infrastructure failures hit 2% of easy, 10% of medium and 40% of hard rollouts.

Drop failed rollouts. Surviving easy: 0.98, medium: 0.90, hard: 0.60. Passing weight: 0.98×0.9 + 0.90×0.5 + 0.60×0.1 = 1.392. Total weight: 2.48. Reported pass rate: 1.392 / 2.48 = 56.1%. Hard tasks shrink from 33% of the batch to 0.60 / 2.48 = 24%. The run looks better than it is, and the model gets less practice where it needs most.

Count failures as zero reward. Reported pass rate: (0.882 + 0.45 + 0.06) / 3 = 46.4%. You now blame the model for the host. On hard tasks the average reward falls from 0.10 to 0.06, so the model learns to avoid hard, tool-heavy tasks.

Retry. A retry fixes transient failures, such as a flaky network. It does not fix persistent ones, such as a task whose setup script always crashes. So retries recover only part of the loss, and each retry costs a full rollout. A retry also risks duplicates: if the first attempt had actually finished when you gave up on it, you now hold two records of one rollout.

Quarantine and resample. Move the failing task to a dead-letter queue (Chapter 6) and fill the slot with a fresh task from the same difficulty bucket. The batch stays balanced. The price is that you must know each task's difficulty, and the quarantined tasks stop teaching until someone fixes them.

Pick a response

Top bar in each row: the pass rate you would report. The dashed line is the true 50%. Lower bar: how much of the batch hard tasks fill, against the fair 33%. Raise the hard-task failure rate and see which responses hold up.

40%
50%

Illustrative toy: three equal buckets with true pass rates 0.9, 0.5 and 0.1, infrastructure failure rates 2%, 10% and the slider value, up to two retries, and a share of failures that repeat on every retry. Quarantine replaces a failed task with a fresh one from the same bucket. The formulas are exact for this toy.

The classifier that decides

The table becomes code as a small function that returns the cause and the action. Keep it boring and explicit. Every unknown error goes to a catch-all that quarantines, never to a silent drop.

pythonACTIONS = {                                 # kind -> (cause, action)
    "env_crash":     ("infra", "retry"),
    "tool_timeout":  ("tool",  "feed_back"),       # agent sees "timed out" and recovers
    "oom_agent":     ("model", "keep"),
    "oom_harness":   ("infra", "retry"),
    "bad_tool_call": ("model", "feed_back"),
    "context_full":  ("model", "keep_truncated"),
    "reward_down":   ("infra", "hold"),            # never score as 0
    "poisoned":      ("data",  "quarantine"),
}
def decide(kind, attempt, max_retries=2):
    cause, action = ACTIONS.get(kind, ("unknown", "quarantine"))
    if action == "retry" and attempt >= max_retries:
        return cause, "quarantine"          # persistent: stop burning compute
    return cause, action
Hard tasks fail more often because of infrastructure limits. The pipeline drops every failed rollout. What happens to the reported pass rate and the batch?

Chapter 6

Observability for a Rollout Factory

Count failures per environment, sample trajectories and route bad ones to a dead-letter queue before the curve tells you

The reward curve has been flat for two days. Nobody changed the model or the data. Searching the logs, an engineer finds it: since a base-image update on Tuesday, one of five environments has been running out of memory in 12% of its rollouts, up from 2%. Across all five environments, the overall failure rate moved from 2.0% to 4.0%. That sits well inside the normal wobble of the dashboard, so no alarm rang.

This chapter is about seeing problems like this early. A rollout factory needs three instruments, and each catches something the others miss.

Instrument 1: failure rates per environment

Count rollouts by environment and by status. Chart the failure rate of each environment as its own line. Do not chart only the total.

The reason is statistics. A shift that hits one part of the traffic is diluted in the total. In our example the broken environment is a fifth of the traffic. Its failure rate rose by 10 points, but the total rose by only 2. Random noise in a rate measured over 200 rollouts has a standard deviation of about 1 point, so the total moved 2 standard deviations. The per-environment line, measured over its own last 40 rollouts, has a standard deviation of about 2.2 points at the old rate, so the same fault moved it 4.5 standard deviations. The same fault is easier to see when you look at the part it hit.

Try it. The simulated stream below has one such fault. Slide the alert threshold and compare when each line crosses it.

Catch the broken environment

The grey line is the failure rate over all five environments. The red line is the one environment that breaks at the dashed vertical mark. The yellow line is your alert threshold. Find a threshold that catches the fault without false alarms.

8%

Illustrative simulation: 600 rollouts spread over 5 environments, a 2% failure rate everywhere, and one environment rising to 12% at rollout 250. The grey line uses the last 200 rollouts; the red line uses the last 40 rollouts of that environment. The random numbers are seeded, so every visit shows the same stream.

Instrument 2: trajectory sampling

Numbers cannot show what no counter counts. A model that has learned to edit the test file passes every test and raises no error. Only a person reading trajectories finds this.

So build a habit and a tool. Every hour, the system picks about ten trajectories and shows them in a viewer. Pick them in groups: a few random ones, the few with the highest reward, the few with the longest length, and the few that were retried. Reading ten trajectories a day takes minutes. It is the cheapest monitor you can buy, and it catches the failures that dashboards cannot define.

Instrument 3: the dead-letter queue

A dead-letter queue (DLQ) is a holding area for items the system could not process. Think of the undeliverable-mail room at a post office. Instead of throwing a failed rollout away, the pipeline writes a record to the DLQ with the reason, and a person or a later job inspects it. Here is one record.

python{
  "rollout_id": "swe-1042/g3/a1",       # task / group member / attempt
  "env": "swe-sandbox", "image": "sha256:9f2c...",
  "policy_version": 41,
  "kind": "oom_harness", "cause": "infra", "action": "quarantine",
  "turns_done": 7, "tokens": 23104, "wall_s": 412.0,
  "last_tool_call": "pytest -x", "first_seen": "2026-10-21T02:14:09Z"
}

Every field earns its place. The image tells you that a base-image change caused the fault. The kind and cause let you chart the DLQ by reason. The attempt in the id lets you spot duplicates. The DLQ depth is itself a chart: a queue that only grows means no one is reading it.

Six numbers worth a chart

pythonCOUNTS = collections.Counter()
def record(traj, kind, cause, action):
    COUNTS[(traj.env, kind)] += 1                 # chart rate = COUNTS[(env, kind)] / started[env]
    if action == "quarantine":
        dlq.put({"rollout_id": traj.rollout_id, "env": traj.env, "kind": kind,
                 "cause": cause, "policy_version": traj.policy_version,
                 "image": traj.image, "wall_s": traj.wall_s})
One of five environments breaks and its failure rate rises from 2% to 12%. Why does a per-environment chart show it sooner than a single total?

Chapter 7

Determinism Under Async

Log enough about each rollout that a run can be audited and replayed, even when arrival order is random

A run diverges at update 312. The reward falls off a cliff. You restart from the update-300 checkpoint with the same data and the same seeds. The run is fine this time. You cannot reproduce the bug, so you cannot fix it, and you cannot tell whether it will come back.

In ordinary supervised training, the same seed gives nearly the same run. An asynchronous RL system loses that comfort. Its inputs depend on timing, and timing is never the same twice.

Where the randomness hides

Five sources work against you.

You will not remove all five. Chasing bit-exact runs across thousands of GPUs and sandboxes costs more than it returns. Aim instead for three smaller goals that you can reach.

Three goals, in order of cost

Auditable. For every update, you can say exactly which rollouts it used, which weights wrote them, and in which environment. This costs a log.

Replayable. Given the log, you can feed the same batches to the learner and rerun the updates. If update 312 breaks again on replay, you have a reproducible bug and can examine it. This costs storage for the trajectories.

Statistically reproducible. Repeated runs land in the same range. You measure the spread, for example by running three seeds, and learn how large a difference must be to count as real. This costs compute, so do it for decisions that matter.

Per-rollout seeds and the manifest

Two small habits give you most of the first two goals. First, derive the seed from the rollout's identity, never from the worker. Then the same rollout id gives the same random stream wherever it runs. Second, write a manifest for every update: a short record listing the rollout ids in the batch and the version that wrote each.

pythonimport hashlib, json

def rollout_seed(run_id, prompt_id, attempt):
    h = hashlib.sha256(f"{run_id}/{prompt_id}/{attempt}".encode()).digest()
    return int.from_bytes(h[:8], "little")         # same id, same seed, on any worker

def write_manifest(update, batch, log):
    log.write(json.dumps({"update": update,
        "rollouts": [{"id": t.rollout_id, "v": t.policy_version, "img": t.image}
                     for t in batch]}) + "\n")

Now compare three ways to run, with the device below. All use a lag limit of 2. Two runs differ only by 15% random jitter in rollout speed, the sort of difference that two real runs always have.

Run it twice

Each row is one update. Each cell is a rollout in the second run's batch, green if the first run used it in the same update, red if it did not. Choose a way to build batches and compare.

Illustrative simulation: 96 actor slots, batch 64, lag limit 2, one hour, made-up rollout times. The second run multiplies every rollout time by a random factor between 0.85 and 1.15. Storage assumes 8,000 tokens per rollout at 4 bytes each; real systems also store log-probabilities and scores.

First to finish gives the best speed and a different batch each time. Fixed order forces the batch to be the same, and brings back the straggler of Chapter 2: update 5 cannot start until every rollout from 256 to 319 is done, even if hundreds of later rollouts are ready. The third way keeps the speed and pays for storage. The first run writes its manifest. A replay reads the stored trajectories listed in it and gives the learner the identical batches. That is the answer for update 312.

One more list belongs in the log, because a replay is only as good as what you can pin down. Record the code commit, the full config, the dataset snapshot id, the sandbox image digest for each environment, and the versions of every tool the agent can call. When a tool is a live web service, store its answers inside the trajectory, since you cannot ask the web to repeat itself. With these, a bug at update 312 becomes a file you can open, not a story you tell.

Which design keeps asynchronous speed and still lets you rerun update 312 with the same batch?

Chapter 8

Capacity Planning With Real Numbers

Size the inference pool, the learner and the retry budget from four measured numbers

You are asked how many GPUs the next run needs. The honest answer is a formula with four measured numbers and one decision. This chapter builds the formula and applies it with real arithmetic, so that a number in a planning meeting has a derivation behind it.

Start from what the learner eats

Capacity planning for a rollout factory works backwards from the learner. The learner consumes one batch of B rollouts per update. If you want U updates per hour, the factory must deliver good rollouts at a steady rate.

Use these illustrative numbers: U = 20 updates per hour, B = 512 rollouts per update, an average rollout time of 90 s, a learner step of 120 s (the update plus the weight sync), a failure rate of 8%, and 16 concurrent rollouts per inference GPU.

  1. Rollouts per second. 20 × 512 / 3600 = 2.84 good rollouts every second.
  2. Slots busy with good work. Each rollout holds a slot for 90 s, so 2.84 × 90 = 256 slots. This is Little's law: the number in the system equals the arrival rate times the time each one stays.
  3. Pay for failures. At 8% failures a good rollout costs 1 / 0.92 = 1.087 attempts. 256 × 1.087 = 278 slots.
  4. Pay for gaps. Asynchronous slots are not busy 100% of the time. They wait at weight syncs and at the lag gate. Assume 90% busy: 278 / 0.9 = 309 slots.
  5. Turn slots into GPUs. 309 / 16 = 19.3, so 20 inference GPUs.

Now check the other side. The learner takes 120 s per update, so it can do at most 3600 / 120 = 30 updates per hour. Your target of 20 is under that ceiling. If you asked for 40, no number of inference GPUs would help. The learner is the bottleneck, and the next purchase is learner capacity or a faster step.

Compare with synchronous training. Chapter 2 gave utilization of 11% at B = 512 with a 1% slow tail. The same arithmetic gives 256 / (0.92 × 0.11) = 2,540 slots, about 159 GPUs. That is the cost of waiting for stragglers, written in hardware.

Size the pools

The first pair of bars compares the GPUs needed in each mode. The second bar compares the updates per hour you want with what the learner can give. The last bar shows where the GPU time goes.

20
512
90 s
120 s
8%

Illustrative planning model, not a benchmark: 16 concurrent rollouts per inference GPU; asynchronous slots 90% busy; synchronous utilization from the Chapter 2 two-point model (1% of rollouts take 10 times longer) for the chosen batch size; every failed attempt costs a full rollout. The synchronous figure ignores the learner's own idle time, so it flatters synchronous.

The four numbers to measure first

Do not guess these. Measure them on a small run before you buy anything.

One more resource is easy to forget: the sandboxes. Each slot is a live environment, so 309 slots means 309 sandboxes running at once, each with its own memory and disk. If a sandbox needs 4 GB, that is 1.2 TB of memory in the sandbox fleet, a separate bill from the GPUs. Our sandbox fleets lesson covers how to run fleets of this kind.

pythonimport math

def size_pool(updates_per_hr, batch, rollout_s, learner_s,
              fail=0.08, busy=0.90, slots_per_gpu=16):
    rate = updates_per_hr * batch / 3600               # good rollouts per second
    slots = rate * rollout_s / ((1 - fail) * busy)      # Little's law, then pay for failures and gaps
    ceiling = 3600 / learner_s                          # what the learner can absorb
    return {"inference_gpus": math.ceil(slots / slots_per_gpu),
            "sandboxes": math.ceil(slots),
            "learner_bound": updates_per_hr > ceiling,
            "max_updates_per_hr": ceiling}
The learner needs 120 s per update. You want 40 updates per hour and have plenty of inference GPUs. What happens?

Chapter 9

Three Silent Failures

Break the pipeline on purpose with silent drops, stale policies and duplicated retries, then find each one by measurement

The loud failures are easy: a crash is a crash. This chapter is about three failures that make no noise. The run keeps going, the loss goes down, and the reward goes up. Only later does a held-out test show that something went wrong a week ago. Each one follows the same plan here: the symptom you see, the measurement that proves it, and the fix.

1. Silent drops bias the data toward easy tasks

Symptom. The training reward rises faster than expected, but a held-out evaluation barely moves. Chapter 5 gave the mechanism: failures are not spread evenly, so dropping them removes hard tasks first.

Measurement. Run a drop audit. Count the rollouts started and the rollouts consumed, for each difficulty bucket or environment. If consumed shares differ from started shares, you have a bias. In the toy pool of Chapter 5 the hard bucket was 33% of what you started and 24% of what you trained on.

Fix. The best fix is to retry or resample so that you do not lose rollouts. When some must be lost, correct for it. Inverse probability weighting gives each surviving rollout a weight of one divided by its chance of surviving. A hard rollout that survives with probability 0.6 gets weight 1 / 0.6 = 1.67, because it stands in for itself and for the 0.67 hard rollouts that vanished. In expectation the weighted batch matches the started batch exactly.

pythondef drop_audit(started, consumed, key=lambda t: t.bucket):
    s = collections.Counter(map(key, started)); c = collections.Counter(map(key, consumed))
    return {b: (s[b] / sum(s.values()), c[b] / sum(c.values()), c[b] / s[b]) for b in s}
    # (started share, consumed share, survival rate); weight each survivor by 1 / survival

2. Stale-policy drift

Symptom. The learning curve rises, then wobbles, then drops. It looks like a bad learning rate. The cause is that you let lag grow, perhaps by adding inference GPUs, and the learner is now fitting to data from policies that no longer exist.

Measurement. Chart four numbers per batch: the mean and maximum lag, the effective sample size (Chapter 3), the share of tokens whose importance weight hit the cap, and the estimated gap between the learner's policy and the data's policy (the KL divergence, a measure of how different two probability distributions are). All four should be flat. If ESS slides down while the cap share slides up, drift has begun.

Fix. Lower the allowed lag. Shrink the update step, since lag matters through its product with step size, as the Chapter 3 device showed. Cap or filter samples whose weights are extreme. And keep the inference pool no bigger than the learner can use (Chapter 8), because rollouts that wait in a buffer only age.

3. Retries duplicate data

Symptom. Updates look oddly confident. The buffer holds more rows than you started rollouts. A few trajectories appear twice, word for word. The cause is a common distributed-systems trap. The orchestrator gave up on a slow rollout and started a retry. The first attempt then finished after all, so both records arrive.

Measurement. Compare the number of rows with the number of distinct rollout ids. If rows exceed ids, you have duplicates. Also compare the retry rate with the share of batch rows that came from retried tasks.

Fix. Give every attempt an idempotency key: a name that is the same for the same piece of work, built here from the run, the prompt, the group member and the attempt. The buffer keeps the first record for a key and ignores the rest. Systems call the result "exactly-once in effect": the network may deliver twice, but the data counts once.

pythonclass Buffer:
    def __init__(self): self.rows, self.seen = [], set()
    def add(self, traj):
        key = (traj.run_id, traj.prompt_id, traj.member, traj.attempt)
        if key in self.seen:                 # a late duplicate from a retried or replayed job
            metrics.incr("buffer.duplicate"); return False
        self.seen.add(key); self.rows.append(traj); return True

When duplicates are rare, they still cost something. If a fraction m of rollouts is double counted, the batch is worth (1 + m)2 / (1 + 3m) of its distinct rollouts. At m = 0.15 that is 1.3225 / 1.45 = 91%. Retries tend to hit slow, hard tasks, so the duplicates are also not a random 9%.

Break it yourself

This is the showcase device. Turn on each fault and watch two lines. The blue line is what your dashboard reports. The green line is what a held-out test would measure. A healthy pipeline keeps them together.

Break the pipeline

The top chart is a toy training run of 40 updates. Below it, three meters show what each fault does to the batch. Toggle drops, raise the lag, and raise the duplicate rate.

1
0%

Illustrative toy, not a measurement: skill starts at 30% and each update closes 4% of the remaining gap, times a signal factor. The factor multiplies the batch's effective sample size from lag (the Chapter 3 formula with medium steps), the duplicate factor (1 + m)² / (1 + 3m), and the hard-task share against a fair third. Silent drops use the Chapter 5 pool: 56.1% reported against a true 50%.

Your training reward climbs but a held-out test is flat, and the hard-task share of consumed rollouts is lower than the share started. What is the likely cause, and the best first fix?

Chapter 10

Field Guide

Keep the numbers, the terms, the checklist and the core loop on one page, with the sources

An agentic RL system is a factory. Actors make rollouts, environments run them, a reward service scores them, a learner trains on them and weight sync closes the loop. Synchronous batches waste GPUs on stragglers. Asynchronous training fixes that at the price of stale data, which importance weights and a lag limit keep under control. Partial rollouts keep long agents in the data. A long tail of failures needs a decision by cause, a response with a known bias, and instruments that see it. Logs make a run auditable and replayable. Four measured numbers size the pools.

The numbers and terms on one page

Number or termWhat it saysWhere
P(stall) = 1 − (1 − p)BChance a step holds a slow rollout. 47% at p = 1%, B = 64. 99.4% at B = 512.Chapter 2, our arithmetic
UtilizationReal work over slot time. 21% and 11% in the two-point model at B = 64 and 512.Chapter 2, illustrative
Lag (staleness)Updates between the policy that wrote a sample and the one that learns from it.Chapter 3
Importance weight ρNew probability over old probability for a token. Cap it to cut variance.Chapter 3, IMPALA
Effective sample size(sum w)2 / sum w2. Four samples with weights 2.5, 0.05, 1, 1 are worth 2.5.Chapter 3
Partial rolloutA trajectory finished over several iterations, with a version stored per token.Chapter 4, Kimi k1.5
Drop auditStarted share against consumed share for each bucket. Weight survivors by 1 / survival.Chapters 5 and 9
Dead-letter queueWhere failed rollouts wait, with a reason, for review.Chapter 6
ManifestThe list of rollout ids and versions that made each update. The key to replay.Chapter 7
Little's lawSlots busy = rollouts per second × seconds per rollout.Chapter 8
Idempotency keyA name that is the same for the same work, so a duplicate is counted once.Chapter 9

The numbers below come from the abstracts of the papers we used. Each is the authors' own claim under their own setup, so compare them as a direction and not as a promise for your hardware.

PaperClaim in the abstract
IMPALAScales to thousands of machines with V-trace off-policy correction; tested on DMLab-30 and Atari-57.
Asynchronous RLHFAbout 40% faster on an instruction task with an 8B model; about 70% faster on GSM8k with a 1B model; online DPO most robust to off-policy data.
AReaLUp to 2.77× training speedup over synchronous systems with the same GPUs.
LlamaRLUp to 10.7× faster than DeepSpeed-Chat-like systems on a 405B-parameter policy; the advantage grows with model size.
HybridFlow (verl)1.53× to 20.57× throughput over baselines across RLHF algorithms.
OpenRLHF1.22× to 1.68× faster than state-of-the-art frameworks, depending on model size.
Kimi k1.5Names long-context scaling as a key ingredient of its RL recipe.
MagistralA scalable RL pipeline that trains a reasoning model with pure RL, without RL traces distilled from earlier models (the small open model adds some cold-start data from the larger one).

A checklist before you launch

  1. Know the cause. Every failure has a kind, a cause (infra, tool, model, data) and an action. Nothing is dropped without a reason in the log.
  2. Limit the lag. A gate on rollouts started, a cap on importance weights, and a chart of lag and ESS.
  3. Keep long tasks. Compare started length with consumed length. Continue unfinished trajectories.
  4. Audit the drops. Started share against consumed share for each bucket, every day.
  5. Split the charts. Failure rate per environment, per kind, per image.
  6. Read ten trajectories a day, including the best-rewarded and the retried.
  7. Write the manifest. Ids, versions, image digests, per-rollout seeds, and the trajectories themselves.
  8. Find the bottleneck. Compare the target updates per hour with 3600 over the learner step before you buy GPUs.
  9. Make duplicates harmless. An idempotency key on every attempt and a dedupe in the buffer.

The core as code

This is the worker loop with every idea in one place: the gate, the seed, the classifier, the dead-letter queue and the idempotent buffer. It is a sketch, not a framework.

pythondef worker_loop(gate, pool, actor, env_factory, reward, buffer, dlq, run_id):
    while True:
        if not gate.may_start():                         # Chapter 3: bound the lag
            time.sleep(0.5); continue
        task, member, attempt = pool.next()              # Chapter 1: tasks come in groups
        gate.started += 1
        seed = rollout_seed(run_id, task.id, attempt)    # Chapter 7: seed from identity
        env = env_factory(task)
        try:
            traj = actor.rollout(env, seed=seed, budget=BUDGET)   # Chapter 4: partial rollouts
            traj.reward = reward.score(traj)                      # may raise RewardDown
            traj.status = "ok"
        except Exception as e:
            kind = classify(e)                           # Chapter 5: kind -> (cause, action)
            cause, action = decide(kind, attempt)
            record(traj_stub(task, member, attempt), kind, cause, action)   # Chapter 6
            if action == "retry":      pool.requeue(task, member, attempt + 1)
            elif action == "hold":    pool.hold_for_reward(task, member, attempt)
            elif action == "quarantine": dlq.put(describe(e, task, member, attempt))
            continue
        finally:
            env.close()
        buffer.add(traj)                                 # Chapter 9: first record per key wins

Where to go next

Sources

  1. Espeholt et al. IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner Architectures (arXiv 1802.01561).
  2. Asynchronous RLHF: Faster and More Efficient Off-Policy RL for Language Models (arXiv 2410.18252).
  3. AReaL: A Large-Scale Asynchronous Reinforcement Learning System for Language Reasoning (arXiv 2505.24298).
  4. HybridFlow: A Flexible and Efficient RLHF Framework (arXiv 2409.19256).
  5. OpenRLHF: An Easy-to-use, Scalable and High-performance RLHF Framework (arXiv 2405.11143).
  6. Kimi k1.5: Scaling Reinforcement Learning with LLMs (arXiv 2501.12599).
  7. LlamaRL: A Distributed Asynchronous Reinforcement Learning Framework for Efficient Large-scale LLM Training (arXiv 2505.24034).
  8. Magistral (arXiv 2506.10910).
The takeaway. A rollout factory is judged by its slowest and its strangest rollouts. Keep the learner from waiting on them, keep the data honest about them, and keep a record that lets you look at them again.

Now press Present or Teach and explain one training step out loud: why the batch waits, how the lag gate lets the learner run ahead, what a failed rollout does to your data under each response, and how you would find the broken environment. Then go back to the instrument at the top, set the lag to 0 and to 4, and explain the difference in the two numbers.

Agentic RL Infrastructure: Surviving the Long Tail
IMPALA · Asynchronous RLHF · AReaL · HybridFlow · OpenRLHF · Kimi k1.5 · LlamaRL · Magistral · Back to Gleams