verl icon indicating copy to clipboard operation
verl copied to clipboard

[trainer] main_ppo_sync: ReplayBuffer.sample() hangs forever when a prompt uid never leaves "running"

Open kevinchenkai opened this issue 4 months ago • 2 comments

System Info

Summary

ReplayBuffer.sample() in verl/trainer/main_ppo_sync.py waits in an unbounded while True loop for all prompts of the current global_steps to leave status="running". If a single prompt's status update never arrives, the main training thread blocks forever — no timeout, no retry, no log line, no exception.

We hit this repeatedly on a single-node 8×H100 GRPO run. Training silently stops with 0% GPU utilization on all 8 cards while the process stays alive, so it looks like a very slow step rather than a failure. Without instrumentation there is nothing in the log to indicate what happened.

This is the mirror image of #6437: that issue is about sample() returning too early with an incomplete batch; this one is about sample() never returning at all. Both stem from the same design gap — sample() treats "no key is running" as its only completion signal, and never considers that a running key might never resolve.

Affected code

verl/trainer/main_ppo_sync.py (v0.8.0.dev), ReplayBuffer.sample():

# L277-296
while True:
    time.sleep(self.poll_interval)
    with self.lock:
        keys, tags = [], []
        should_wait = False
        partition = self.partitions[partition_id]
        for key, tag in partition.items():
            if tag["global_steps"] == global_steps:      # L284
                if tag["status"] == "running":           # L285
                    should_wait = True                   # L286  <-- blocks forever
                    break
                elif tag["status"] == "success":
                    keys.append(key)
                    tags.append(tag)
                else:
                    logger.debug(f"Unknown status {tag['status']} for key {key}")
        if not should_wait:
            return KVBatchMeta(partition_id=partition_id, keys=keys, tags=tags)

Root markers are registered as running before dispatch, and _run_prompt() (L352) is responsible for flipping them to finished (L374) or failure (L377). If neither write ever happens, the loop above spins indefinitely.

Evidence

Single-node 8×H100, GRPO, train_batch_size=64, rollout.n=8 (512 rollouts/step).

We patched sample() locally to add diagnostics and a hard timeout. On the failing step it reported:

TimeoutError: ReplayBuffer.sample() stuck 1801s at step=669 partition=train;
1 key(s) never left 'running'. pending=['3d59865a-...']

The stall diagnostics printed every ~120s, and the numbers never changed once:

STALLED  121s at step=669 partition=train: 1 key(s) still 'running', 511 'success', 30527 total in partition
STALLED  241s at step=669 partition=train: 1 key(s) still 'running', 511 'success', 30527 total in partition
...
STALLED 1684s at step=669 partition=train: 1 key(s) still 'running', 511 'success', 30527 total in partition

511 success + 1 running = 512 = train_batch_size × rollout.n. Exactly one rollout out of the whole batch never reported back, and it stayed that way for the full 30 minutes.

Other observations at the time of the hang:

Observation | Value | Rules out -- | -- | -- GPU utilization | 0% on all 8 GPUs, 115W/700W, 30–36°C | NCCL / GPU kernel hang GPU memory | still 60 GB/card allocated | process death Main thread /proc//wchan | hrtimer_nanosleep | = the time.sleep() above All WorkerDict + RewardLoopWorker wchan | ep_poll (idle, awaiting RPC) | reward / actor hang "Error in _run_prompt" occurrences | 0 | the failure path (L377) never fired Traceback / NCCL timeout / OOM | none | —

Recovered stalls cost ~20s each (a step goes from ~34s/it to ~52s/it, then back). Stalls occurred in both the train and val partitions. Before we added the workaround, runs typically died within a few hundred steps; the same job had previously terminated at steps 201, 213, and 218 across separate attempts.

Note that the stalls occur at different steps on every run, and we verified they are not data-dependent: an earlier run computed step 213 successfully and continued to 217, while another hung at step 201 (the very first step after a resume, sharing no data with the others). With data.shuffle: true and data.seed: null, each resumed run draws a different permutation, so step numbers are not comparable across runs.

Environment

verl        0.8.0.dev  (main_ppo_sync / TransferQueue / agent-loop path)
torch       2.10.0+cu129
vllm        0.19.1
transformers 5.12.1
ray         2.56.0
tensordict  0.10.0
flash_attn  2.8.3
python      3.11
hardware    single node, 8×H100
config      GRPO + FSDP2, train_batch_size=64, rollout.n=8,
            max_prompt_length=4096, max_response_length=10240,
            free_cache_engine=true, enforce_eager=false, tensor_model_parallel_size=1

Expected behavior

A lost rollout status update should not be able to stall training indefinitely and silently.

Concretely, we would expect at least the first of the following, ideally the first three:

  1. The wait should be bounded. sample() should not block forever. A configurable timeout (default on) that raises with the offending keys would turn an indefinite silent hang into an actionable failure. As it stands, a single lost update out of 512 idles 8 GPUs until someone notices manually — for us that was 30+ minutes on several occasions, and the job would have sat there indefinitely had we not added our own timeout.

  2. The wait should be observable. If sample() has been waiting well beyond a normal step time, it should log what it is waiting for (pending key count, and the keys themselves). Today there is no way to distinguish "this step is slow" from "this step will never finish" — the process looks alive, the transfer queue keeps serving requests, and nothing is printed. Any log line naming the pending uid would have saved us most of the debugging effort described above.

  3. Ideally, the lost rollout should be recoverable. Aborting a multi-hour run because 1 of 512 rollouts went missing is a harsh outcome, especially since the other 511 completed normally. Re-dispatching the missing prompt (or, failing that, dropping it and proceeding with 511 while recording the shortfall in metrics) would both be far preferable to termination. Our own re-poll workaround recovered 8 of 9 stalls, which suggests many of these are timing races where the update simply arrives late — but the 9th case had genuinely never been published, and only a re-dispatch of the prompt itself could have saved it.

  4. Malformed tags should not crash the loop. tag["global_steps"] / tag["status"] at L284/L285 assume every tag carries both keys, but the transfer queue legitimately holds bare tags such as {"status": "finished"} written by _run_prompt() at L374. Using .get() would make the loop robust to this (see the caveat under "What we did as a workaround").

We are not attached to any particular design here — a timeout plus a log line would already be a large improvement over the current silent, unbounded wait. Whether the right long-term answer is re-dispatch, fail-closed (as in #6641), or explicit partial-batch handling is a maintainer call, and interacts with the completeness question raised in #6437.

Reproduction

We do not have a deterministic minimal reproducer. This is a low-probability race: ~9 stall events over ~470 steps (≈2% of steps), of which 1 in 9 was unrecoverable. It reproduced across many independent runs on the same setup, always at different step numbers. By default the failure is completely silent, so the practical way to observe it is to instrument sample() (see below).

Config

Launched via python3 -m verl.trainer.main_ppo_sync --config-dir <dir> --config-name <name>. Relevant fields, as resolved by Hydra at runtime (taken from the config dump in our log, not from our source yaml):

algorithm:
  adv_estimator: grpo
  use_kl_in_reward: false

data: train_batch_size: 64 max_prompt_length: 4096 max_response_length: 10240 filter_overlong_prompts: true truncation: error shuffle: true seed: null # note: null -> each run/resume draws a different permutation dataloader_num_workers: 8

actor_rollout_ref: model: use_remove_padding: true enable_gradient_checkpointing: true use_fused_kernels: false actor: strategy: fsdp2 use_dynamic_bsz: false ppo_mini_batch_size: 32 ppo_micro_batch_size_per_gpu: 2 use_kl_loss: true kl_loss_coef: 0.001 kl_loss_type: low_var_kl optim: {lr: 1.0e-6, weight_decay: 0.01, lr_scheduler_type: constant} fsdp_config: {offload_policy: false} rollout: name: vllm mode: async # agent-loop / TransferQueue path n: 8 # 64 x 8 = 512 rollouts per step tensor_model_parallel_size: 1 data_parallel_size: 1 gpu_memory_utilization: 0.6 temperature: 1.0 top_p: 1.0 top_k: -1 enforce_eager: false free_cache_engine: true enable_chunked_prefill: true enable_prefix_caching: true max_num_batched_tokens: 14336 max_num_seqs: 1024 agent: default_agent_loop: single_turn_agent num_workers: 8 agent_loop_config_path: null

reward: custom_reward_function: {path: <custom>, name: compute_score} reward_manager: {name: naive}

trainer: nnodes: 1 n_gpus_per_node: 8 total_epochs: 2 resume_mode: auto save_freq: 50 test_freq: 20 val_before_train: false

Note this is a single-turn agent loop (default_agent_loop: single_turn_agent), i.e. the simplest agent-loop configuration — no tools, no multi-turn.

Stack trace

With upstream code the process does not raise at all: it blocks in sample() indefinitely with 0% GPU utilization. The trace below comes from our locally patched sample(), which converts the infinite wait into a TimeoutError after 1800s. The frames above sample() are unmodified upstream:

Traceback (most recent call last):
File "<frozen runpy>", line 198, in _run_module_as_main
File "<frozen runpy>", line 88, in _run_code
File "verl/trainer/main_ppo_sync.py", line 1996, in <module>
main()
...
File "hydra/core/utils.py", line 186, in run_job
ret.return_value = task_function(task_cfg)
File "verl/trainer/main_ppo_sync.py", line 1992, in main
run_ppo(config, task_runner_class=TaskRunner)
File "verl/trainer/main_ppo.py", line 102, in run_ppo
ray.get(runner.run.remote(config))
...
File "ray/_private/worker.py", line 1050, in get_objects
raise value.as_instanceof_cause()
ray.exceptions.RayTaskError(TimeoutError): ray::TaskRunner.run() (pid=7966, ...,
repr=<main_ppo_sync.TaskRunner object at 0x7f95ba845410>)
File "verl/trainer/main_ppo_sync.py", line 1966, in run
trainer.fit()
File "verl/trainer/main_ppo_sync.py", line 1770, in fit
batch = self.step(batch_dict, metrics, timing_raw)
File "verl/trainer/main_ppo_sync.py", line 1840, in step
batch = self.replay_buffer.sample(partition_id="train", global_steps=self.global_steps)
File "verl/trainer/main_ppo_sync.py", line 419, in sample     # <-- our timeout; upstream L277 loops forever here
raise TimeoutError(
TimeoutError: ReplayBuffer.sample() stuck 1801s at step=669 partition=train;
1 key(s) never left 'running'. pending=['3d59865a-...']

(Line numbers in main_ppo_sync.py are shifted by our patch; the corresponding upstream locations are sample() at L261 and the wait loop at L277–296.)

How to observe it on unmodified verl

Since the upstream failure produces no output at all, the minimal instrumentation to confirm you are hitting this is to bound the wait loop and dump the pending keys. Applied to ReplayBuffer.sample() in verl/trainer/main_ppo_sync.py:

def sample(self, partition_id: str, global_steps: int = None, batch_size: int = None) -> KVBatchMeta:
...
start = time.time()               # <-- add
while True:
time.sleep(self.poll_interval)
with self.lock:
keys, tags = [], []
should_wait = False
pending = []              # <-- add
partition = self.partitions[partition_id]
for key, tag in partition.items():
if tag.get("global_steps") != global_steps:   # .get(): bare tags lack this key
continue
status = tag.get("status")
if status == "running":
should_wait = True
pending.append(key)                       # collect, don't break
elif status == "success":
keys.append(key)
tags.append(tag)
if not should_wait:
return KVBatchMeta(partition_id=partition_id, keys=keys, tags=tags)
n_success, n_total = len(keys), len(partition)

    elapsed = time.time() - start                          # &lt;-- add, outside the lock
    if elapsed &gt; 120:
        msg = (f"sample() STALLED {elapsed:.0f}s at step={global_steps} "
               f"partition={partition_id}: {len(pending)} running, "
               f"{n_success} success, {n_total} total. pending={pending[:10]}")
        logger.warning(msg)
        print(msg, flush=True)    # logger alone is buffered by Ray and lost if the process dies
    if elapsed &gt; 1800:
        raise TimeoutError(msg)</code></pre><p>Two notes from doing this ourselves:</p><ul><li><p><code>print(..., flush=True)</code> matters. With <code>logger.warning()</code> alone we generated 15 stall warnings and <strong>none of them reached the log</strong> — Ray buffers actor stdout and the buffer was lost when the process died. Only the exception survived, because Ray propagates it through a separate channel.</p></li><li><p>Removing the <code>break</code> (to collect all pending keys instead of the first) is what let us confirm it was exactly one key out of 512.</p></li></ul><p>Run a GRPO job with <code>rollout.mode=async</code> and <code>rollout.n&gt;1</code> for a few hundred steps; if you hit the race, you will see the pending key count sit at a small non-zero number while everything else reports <code>success</code>.</p><h3>What we did as a workaround</h3><p>Local patch to <code>ReplayBuffer.sample()</code> (not proposed as an upstream fix, just describing what made the failure visible):</p><ol><li><p><strong>Diagnostics</strong> — after N seconds of waiting, log the pending key list, plus success/total counts.</p></li><li><p><strong>Re-poll</strong> — call <code>tq.kv_list()</code> directly from the waiting thread instead of relying solely on the background poll thread. This recovered 8 of 9 stalls.</p></li><li><p><strong>Hard timeout</strong> — raise <code>TimeoutError</code> instead of blocking forever, so the platform can restart from the last checkpoint rather than sitting idle indefinitely.</p></li></ol><p>One caveat worth flagging for anyone attempting something similar: the more aggressive re-poll surfaced a latent crash in the same loop. <code>tag["global_steps"]</code> at L284 assumes every tag carries that key, but the transfer queue also holds bare tags such as <code>{"status": "finished"}</code> written by <code>_run_prompt()</code> at L374, which do not. This yields:</p><pre><code>File "verl/trainer/main_ppo_sync.py", line 284, in sample
if tag["global_steps"] == global_steps:

KeyError: 'global_steps'

Using tag.get("global_steps") / tag.get("status") avoids it. This is a pre-existing latent bug in upstream code; it just becomes reachable when the loop observes the queue more often.

Relation to #6641

#6641 adds fail-closed completeness checks for the finished / failure case, but by design it still waits only for running markers to disappear — it does not address a marker that never disappears. A run hitting our failure mode would block inside the same loop before any of its checks are reached. The two problems are complementary, and a timeout on the wait would compose cleanly with that PR's validation.

Possibly related

  • #6437 — same code path, opposite symptom (early return with a partial batch). Strongly related; likely the same underlying design gap.

  • #6641 — proposed fail-closed fix for #6437; explicitly does not cover permanently-running markers.

  • #6583 — vLLM EngineCore "RPC call to sample_tokens timed out", where a rollout request silently disappears with no OOM/NCCL/CUDA error. The symptom shape matches ours (request vanishes, nothing raised), which could explain why _run_prompt() never completes. However this is speculation on our part and we have not verified it — that report is on vLLM 0.20.2 and 256×H200 multi-turn, whereas we are on vLLM 0.19.1, single node, and we could not attach a debugger to the rollout workers to confirm.

Information

  • [ ] The official example scripts
  • [ ] My own modified scripts

Tasks

  • [ ] An officially supported task in the examples folder (such as GLUE/SQuAD, ...)
  • [ ] My own task or dataset (give details below)

Reproduction

We do not have a deterministic minimal reproducer. This is a low-probability race: ~9 stall events over ~470 steps (≈2% of steps), of which 1 in 9 was unrecoverable. It reproduced across many independent runs on the same setup, always at different step numbers. By default the failure is completely silent, so the practical way to observe it is to instrument sample() (see below).

Expected behavior

A lost rollout status update should not be able to stall training indefinitely and silently.

Concretely, we would expect at least the first of the following, ideally the first three:

The wait should be bounded. sample() should not block forever. A configurable timeout (default on) that raises with the offending keys would turn an indefinite silent hang into an actionable failure. As it stands, a single lost update out of 512 idles 8 GPUs until someone notices manually — for us that was 30+ minutes on several occasions, and the job would have sat there indefinitely had we not added our own timeout.

The wait should be observable. If sample() has been waiting well beyond a normal step time, it should log what it is waiting for (pending key count, and the keys themselves). Today there is no way to distinguish "this step is slow" from "this step will never finish" — the process looks alive, the transfer queue keeps serving requests, and nothing is printed. Any log line naming the pending uid would have saved us most of the debugging effort described above.

Ideally, the lost rollout should be recoverable. Aborting a multi-hour run because 1 of 512 rollouts went missing is a harsh outcome, especially since the other 511 completed normally. Re-dispatching the missing prompt (or, failing that, dropping it and proceeding with 511 while recording the shortfall in metrics) would both be far preferable to termination. Our own re-poll workaround recovered 8 of 9 stalls, which suggests many of these are timing races where the update simply arrives late — but the 9th case had genuinely never been published, and only a re-dispatch of the prompt itself could have saved it.

Malformed tags should not crash the loop. tag["global_steps"] / tag["status"] at L284/L285 assume every tag carries both keys, but the transfer queue legitimately holds bare tags such as {"status": "finished"} written by _run_prompt() at L374. Using .get() would make the loop robust to this (see the caveat under "What we did as a workaround").

We are not attached to any particular design here — a timeout plus a log line would already be a large improvement over the current silent, unbounded wait. Whether the right long-term answer is re-dispatch, fail-closed (as in #6641), or explicit partial-batch handling is a maintainer call, and interacts with the completeness question raised in #6437.

kevinchenkai avatar Jul 27 '26 03:07 kevinchenkai

Thanks for your report! Here are some suggestions:

  1. Upgrade your verl. verl has updated to V1 trainer, and some problems you mentioned are already fixed, e.g. the KeyError: 'global_steps'. ReplayBuffer.sample() now calls tq.kv_list() itself on every iteration, so the background poll thread whose snapshot went stale is gone. Also V1 trainer will print pending/running/finished/failure counting logs every 60s.
  2. Since you set data.shuffle: true and data.seed: null, the hang can not be described as "not data-dependent". Maybe modify them to reproduce.
  3. ReplayBuffer.sample() shouldn't set a default timeout. When some hang prompts are running, they are hanging in the agentloop. Worth noting that single-turn narrows the chain, but there are still some unbounded awaits in that path: acquire_server, server.generate, _compute_score (your custom_reward_function runs here), and the trajectory async_kv_batch_put. GlobalLoadBalancer.get_status() may help — _release_server() runs in a finally, so a non-zero in-flight count means you are still inside generate(); and ray list tasks filtered to RUNNING, which should name the actor and method outright. Try to add some logs to isolate vLLM, reward function, or other suspicious locations.

Begunner avatar Jul 27 '26 10:07 Begunner

Thanks for the pointers — they match what we found after further debugging.

Root cause

You were right that the stuck running key was still in the agent-loop path. In our case it was _compute_score / custom_reward_function, not vLLM generate.

  1. Trigger: math_verify.verify() on rare pathological math samples. One real rollout: parse ~0.2s, verify ~1677s at ~100% CPU. On veRL 0.8, reward runs via run_in_executor (worker thread). math_verify timeouts use signal.alarm (main thread only), so we passed timeout=None off-thread → effectively no timeout. A stuck CPython thread cannot be killed from outside.
  2. Amplifier: ReplayBuffer.sample() waits for all keys. One of 512 trajectories stuck → whole step idle (GPUs ~0%).

Same real sample, worker thread:

Reward Result
No process timeout Blocks ~1677s
Subprocess + 5s kill Returns 0.0 in ~5s

So this is data-dependent (shuffle: true, seed: null as you noted). Our earlier “not data-dependent” claim was wrong — hang steps moved with the shuffle; the trigger is a tiny set of math GTs + a response that hits the slow symbolic path.

On your suggestions

  • Upgrade to V1: Agreed. Stale poll / KeyError: 'global_steps' and missing status counts were real pain points; the 60s pending/running logs would have helped a lot.
  • No default timeout on sample(): Understood for agent-loop. Our ask softens to observability first (which V1 improves), plus optional configurable timeout for ops — not necessarily a hard default.
  • GlobalLoadBalancer / ray list tasks: Useful for future isolation. Here GPU empty + idle RewardLoopWorker already pointed away from generate.

Mitigation (our side)

Fixed in the custom reward: run parse/verify in a subprocess, parent result(timeout=5), SIGKILL on timeout, score=0. Same bad inputs no longer pin a running key.

If useful for docs/tests, we can share a minimal repro (pathological GT + worker-thread compute_score). Happy to close or retitle once we’re fully on V1 — the original “unbounded silent wait when one stage never returns” still stands; our primary root cause was an unbounded reward.

kevinchenkai avatar Jul 28 '26 11:07 kevinchenkai