Skip to content

[rl] Fail an invalid generation request without crashing the generator - #5182

Merged
wwwjn merged 6 commits into
mainfrom
jianiw/rl-reject-overlong-prompts
Oct 12, 2026
Merged

wwwjn merged 6 commits into
mainfrom
jianiw/rl-reject-overlong-prompts

Conversation

@wwwjn

@wwwjn wwwjn commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Problem

vLLM validates a request's prompt and sampling params only when the generator's engine loop admits it (render_cmpl / add_request in VLLMGenerator._engine_loop). An error there escapes the loop:

  • every outstanding request on that generator fails;
  • the generator closes for good, and every later call to it fails with "generator is closed";
  • the inter-generator router keeps routing to it: a closed generator fails fast, so it looks least loaded;
  • nothing tells the controller. The rollouter turns each failed call into an ERROR rollout, so the run silently loses that generator.

One bad request is enough. In a multi-turn agentic RL run (Terminal-Bench with Terminus-2, 131,072-token context), four prompts of 131,149 to 133,854 tokens closed four of 28 generators within 30 minutes. After that most rollouts failed and no batch was trainable. An earlier run lost a generator to a prompt of exactly 131,072 tokens.

The prompts were not dataset prompts. Each turn's prompt is the whole conversation so far, so it grows over a long rollout. The env side is meant to end such a rollout:

  • TokenEnv checks len(next_prompt) >= max_rollout_tokens before every generation, but max_rollout_tokens defaults to None, which disables the check.
  • Verifiers checks each prompt against the max_model_len that GenerationServer advertises on GET /v1/models. But it looks the limit up once per worker process and caches "no limit" if the lookup fails, and it uses >, so a prompt of exactly max_model_len passes.
  • prime-rl uses the same Verifiers client, but vLLM's API server validates each request and returns a 400 for that request only. Our generator runs LLMEngine inside a shared engine loop, so the same request crashed it instead.

Fix

1. A request vLLM rejects fails alone (VLLMGenerator._engine_loop).

  • The loop renders and admits each request on its own (render_cmpl([prompt]), then add_request) and catches ValueError.
  • ValueError (including VLLMValidationError) is what vLLM raises for every admission check, all before it changes engine state:
    • prompt longer than max_model_len;
    • empty prompt, or one of exactly max_model_len (no room for an output token);
    • invalid sampling params, e.g. max_tokens=0;
    • out-of-vocab token ids.
  • Only that request's reply fails, with vLLM's own error. The loop keeps running.
  • No vLLM rules are copied. The pre-check in generate() from the earlier commits is removed.
  • TP ranks stay in step: the checks are deterministic, so every TP rank of a replica rejects the same requests and none of them adds it.

2. Rejections on any DP replica reach rank 0 (RequestDispatcher).

  • Rank 0 holds every reply future, but with DP > 1 a request can be admitted, and rejected, on another replica.
  • Rank 0's own replica fails those replies directly.
  • Another replica's TP rank 0 sends a _RejectedRequests message to rank 0 over the existing result port. Rank 0's drain task fails those replies and frees their DP-router reservations.
  • Without this, a request rejected on a peer replica would never be answered, and its generate() call would hang.

3. A dead engine loop fails the run (wait_engine_loop → wait_engine_loops → Controller.run).

  • Generator: wait_engine_loop() awaits the engine loop's future, await asyncio.wrap_future(self._engine_loop_future). That adds a done-callback and suspends only this call. The engine loop keeps running on its own engine thread and event loop, untouched. The actor's event loop keeps serving generate, pull_model_state_dict and close.
    • It returns when the loop ends cleanly (on close()).
    • It raises the loop's exception if the loop crashed.
  • Actor endpoint: a @concurrent_endpoint, like generate, so Monarch runs it alongside other calls. That decorator is what makes this safe: a plain @endpoint handles one call at a time, so a call that never returns would block every later call to that actor.
  • Router: wait_engine_loops is also a concurrent_endpoint. It calls wait_engine_loop on every rank of every generator and suspends in _fanout; routing generate calls continues.
  • Controller: it's one more task among the background tasks run() already waits on with asyncio.wait.
    • Engine loops only end at close, so if this task finishes mid-run, run() raises.
    • If it raised, run() re-raises the engine loop's error; if it returned, run() raises "exited unexpectedly".
    • Before this, a crash surfaced only as failed rollouts.
  • Cost: one pending RPC per generator rank and a callback. No polling, no GPU work.

4. Clean errors for HTTP clients (GenerationServer).

  • Rejects a prompt of max_rollout_tokens tokens or more with HTTP 400. That's the same bound as TokenEnv.Config.max_rollout_tokens: the prompt plus at least one output token must fit.
  • The message uses the OpenAI-style "maximum context length" wording, which Verifiers maps to an overlong prompt, so the rollout ends cleanly as context_length.
  • Without it, the generator's ValueError would come back through the router as a wrapped actor error and an HTTP 500, which harnesses retry.

5. A first prompt that doesn't fit is flagged (VerifiersRollouter).

  • A rollout that stops for context length before its first turn has a first prompt that never fit, which is a data problem, not the policy's.
  • It already ends as ERROR (no turns). It now also logs a warning naming the task.
  • The dataset can't be filtered for this up front: the harness builds the first prompt inside the env server from the task plus its own system prompt and tools.

Notes

  • prompt + max_tokens > max_model_len: vLLM's LLMEngine path admits such a request with max_tokens unchanged and stops it at max_model_len with finish_reason="length" (check_stop). That isn't an error, so nothing here changes it. vLLM's OpenAI server rejects it instead, because it renders with max_output_tokens=max_tokens.
  • Cost of per-request rendering: render_cmpl tokenizes nothing for token prompts, so the extra calls are cheap. _build_sampling_params still runs once per request, as before.

Not in this PR (follow-ups)

  • Fail the run vs stop routing: a dead engine loop now fails the run. Keeping the run going on the remaining generators would be a router change (mark the generator unroutable); it trades a loud failure for silently reduced capacity.
  • Terminal-Bench recipe ([RL] Add Terminal-Bench 2.1 experiment via Verifiers (Qwen3.5 9B, 35B-A3B) #4942): should set Verifiers' AgentConfig.max_total_tokens, so rollouts stop by context size on the env side, as TokenEnv does.
  • renderers (upstream): should retry a failed /v1/models lookup instead of caching "no limit".

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Oct 8, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 8, 2026
Comment on lines +185 to +190
if len(prompt_token_ids) > self.max_rollout_tokens:
raise ValueError(
f"This model's maximum context length is {self.max_rollout_tokens} "
f"tokens. However, your prompt contains {len(prompt_token_ids)} "
"input tokens."
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we want to raise? what would it crash?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, raise here will let HTTP server return 400, will not crash the server. And it could also prevent the extra-long input hit vllm engine.

Comment thread torchtitan/rl/generator.py Resolved
Comment thread torchtitan/rl/generator.py Resolved
Comment thread torchtitan/rl/generator.py Outdated
f"tokens, and a prompt must leave room for at least one output token, "
f"but this prompt has {len(prompt_token_ids)} tokens"
)
self._build_sampling_params(sampling)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

accidental line?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No clue why it is here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry my agent correct me: this is not a random, some other sampling parameter could also fail the generator,(eg, max_tokens=0 raises), otherwise that first happens in the engine loop at admission, where an error takes down the generator the same way an over-length prompt does.

so here we are checking these parameter by rebuliding the Sampling config to trigger the check. I will put this to a better/clear function name.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if sampling already check those, does it check the max seq len? and if so, do we need the extra raise then?

@wwwjn
wwwjn requested review from felipemello1 and tianyu-l October 9, 2026 02:49

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please address my nit, and also wait for felipe's approval

Comment thread torchtitan/rl/generator.py Outdated
Comment on lines +1187 to +1188
# Constructing SamplingParams validates them.
self._build_sampling_params(sampling)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know what error it'd be validating against, but without try catch, we are relying on vLLM error to make sense, which doesn't sound the best way for validation.

Comment thread torchtitan/rl/controller.py Outdated
Comment on lines +863 to +865
engine_loops_task = asyncio.create_task(
self._wait_engine_loops(), name="generator_engine_loops"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is new to me, so I have to review again

but anyways, this should be renamed to generator_task to match others?

@wwwjn wwwjn Oct 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes please, I was about to ask for a review.

This new version, the goal is to make the generator able to catch more kinds of failure, not only the input is too long, and add a comprehesive safe guard. 3 main points to note ( suggested by @felipemello1 )

  • Keep the generator-server return 400 HTTP code
  • Replace the generator pre-check with a per-request try/except: current the failure check is moved to add_requests(). I added a process_rejected_requests(), similar to process_finshed_requests()
  • Make a dead engine loop fail loudly: I added wait_engine_loop() which will watch the engine loop future, and raise expection to controller if the loop crashed.

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sounds reasonable, I'll trigger claude for another review.

Comment thread torchtitan/rl/controller.py Outdated
Comment on lines +863 to +865
engine_loops_task = asyncio.create_task(
self._wait_engine_loops(), name="generator_engine_loops"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
engine_loops_task = asyncio.create_task(
self._wait_engine_loops(), name="generator_engine_loops"
)
generator_task = asyncio.create_task(
self.generator_loop(), name="generator_wait_engine_loop"
)

some renaming suggestion to be consistent with other APIs

await self._fanout("start_engine_loop")

@concurrent_endpoint
async def wait_engine_loops(self) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
async def wait_engine_loops(self) -> None:
async def wait_engine_loop(self) -> None:

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR

@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 38s —— View job


Review: [rl] Fail an invalid generation request without crashing the generator

  • Gather the diff and context
  • Review generator engine loop / rejection path
  • Review controller / router / actor changes
  • Review verifiers server / rollouter changes
  • Review tests
  • Post review

Overall: I think the design is right. Catching the error per request at admission (instead of copying vLLM's checks into generate()) gets at the root cause. It answers @felipemello1's earlier question about whether the separate length check is still needed: it isn't, because vLLM's own check now fails only that request. The DP fan-in reuses the existing result port, and having the controller watch the engine loops closes the "silently lost generator" gap. I found no correctness bugs in the rejection path. The points below are mostly about edge cases in the new watcher and about test coverage.

I couldn't run the tests or try anything against vLLM or Monarch here: commands that import them need approval in this environment. Everything below comes from reading the code.


1. Watcher: a crash may surface late when TP > 1 (worth checking)

torchtitan/rl/distributed/routing/inter_generator.py:294: wait_engine_loops → _fanout("wait_engine_loop") → h.actor.wait_engine_loop.call() on the whole mesh of each generator.

When rank 0's engine loop crashes, its peer TP ranks are usually blocked in broadcast_object_list (gloo) or engine.step() (NCCL), waiting for a decision that never comes. The reverse also happens: if a follower crashes, rank 0 blocks. So "raise as soon as one crashes" holds only if Monarch's ActorMesh.call() fails as soon as one rank raises. If it waits for every rank to answer, the crash shows up only when the collective times out, which could take a long time.

  • Please check how .call() behaves when one rank fails, or add a short comment if it's already known to fail fast.
  • If it doesn't fail fast, one option is to fan out with one call_one per rank and asyncio.wait(..., FIRST_EXCEPTION).

2. Watcher: nothing tests the new path through Controller.run()

  • test_engine_loop.py covers VLLMGenerator.wait_engine_loop well (it raises on a crash and returns on a clean close).
  • No test drives Controller.run() with a watcher that raises or returns, so both the "exited unexpectedly" and re-raise branches for engine_loops_task are untested. A small CPU test with a stub router whose wait_engine_loops.call_one() raises would pin this down. That matches CLAUDE.md's ask for CPU unit tests on new features.

3. Watcher: what it doesn't cover (minor, can go in the docstring)

torchtitan/rl/controller.py:893-901: the finally cancels engine_loops_task before the final _validate_and_log, and pre-training validation runs before the task exists. A crash during validation still shows up only as failed validation rollouts. That's probably fine, but the run() docstring could say so.

Cancelling engine_loops_task also only cancels the controller-side future. The router's concurrent_endpoint call, and each generator's wait_engine_loop, stay pending until close() ends the loop. That's harmless, since a clean exit returns None. Just confirm that shutdown doesn't log noise when the actor mesh is torn down with those calls still pending.

4. Rejection path: the except ValueError relies on vLLM internals (nit)

torchtitan/rl/generator.py:1377-1391: the comment says vLLM "raises before changing engine state". As far as I know that's true for process_inputs validation. But LLMEngine.add_request also updates output_processor/engine_core after validating. If a later vLLM version raises ValueError after that bookkeeping, the loop would keep running with a half-registered request on every TP rank. Two cheap mitigations, either works:

  • name the vLLM version/function in the comment, so a bump knows what to recheck; or
  • add a test that engine.has_unfinished_requests() is unchanged after a rejected add_request on the real LLMEngine path. test_admission_rejects_only_the_invalid_request already gets most of the way there with max_tokens=0.

5. Rejection path: _rank0_fail_generations uses .pop() (follows existing code)

torchtitan/rl/generator.py:651: a KeyError in the drain task would kill it without anyone noticing. Later peer completions would then never resolve, so generate() hangs. _rank0_resolve_generations already has the same behavior, so this isn't a regression. Since the drain task runs on the engine loop's event loop and isn't watched by wait_engine_loop, consider a follow-up TODO to watch it, or to have its failure fail the engine loop.

6. Reviewer suggestions not applied yet

@tianyu-l's naming suggestions are still open:

  • controller.py:863: engine_loops_task / _wait_engine_loops / name "generator_engine_loops" → suggested generator_task, "generator_wait_engine_loop".
  • inter_generator.py:294: wait_engine_loops → suggested wait_engine_loop. That would also match start_engine_loop, which is singular on the router too.

7. Smaller notes

  • generation_server.py:181: >= against max_rollout_tokens matches vLLM (there must be room for one output token), and the advertised max_model_len is still max_rollout_tokens. Good. One assumption remains: max_rollout_tokens <= generator max_model_len. If a recipe sets it higher, an overlong prompt gets past the server, is rejected by the generator, and comes back as a 500. Harnesses retry 500s, so the same prompt would be rejected again on each retry. A sentence in the Config docstring would help; a startup check against the generator's max_model_len would be better if it's reachable from the rollouter.
  • rollouter.py:319-329: the warning is useful. sample.verifiers_task_data.get("name") or sample.verifiers_task_data.get("idx") logs None when neither key exists; falling back to group_id/rollout_id, which are already in the message, is fine.
  • Sending ValueErrors over the Monarch port: standard exception pickling keeps __dict__, so VLLMValidationError's parameter/value should survive the round trip. If it fails to pickle, the engine loop on the peer replica crashes. That failure is loud now thanks to the watcher, so it's an acceptable failure mode.
  • process_rejected_requests docstring: the bullet list mixes ; and . endings. Trivial.

Summary

Area Verdict
Rejecting one request per admission (_engine_loop) ✅ Correct; TP ranks stay in step
Sending DP-peer rejections to rank 0 (_RejectedRequests) ✅ Correct, tested; frees DP-router reservations
Engine-loop watcher (actor, router, controller) ⚠️ Check Monarch .call() fails fast (1); add a Controller.run test (2)
GenerationServer 400 ✅ Matches vLLM's limit and Verifiers' wording
Naming suggestions from review ⏳ Not applied yet (6)

wwwjn added 5 commits October 11, 2026 22:09
vLLM checks a request's prompt length and sampling params only when the
generator's engine loop admits it (`render_cmpl` / `add_request`). An error
there escapes the loop: every outstanding request on that generator fails,
the generator closes for good, and every later call to it fails. One
over-length prompt from a long multi-turn rollout is enough.

- `VLLMGenerator.generate` now runs the same checks before queueing the
  request, so only that call fails: the prompt must be non-empty and shorter
  than `max_model_len` (vLLM needs room for one output token), and the
  `SamplingParams` must build.
- `GenerationServer` now rejects a prompt longer than `max_rollout_tokens`
  with HTTP 400. Verifiers checks this limit before sending, but only if its
  one `GET /v1/models` lookup per worker process succeeds; a failed lookup
  turns the check off for that process. The error uses the OpenAI-style
  "maximum context length" wording, which Verifiers maps to an overlong
  prompt, so the rollout ends as `context_length`.
Address review: the bare _build_sampling_params call read as accidental.
_rank0_reject_inadmissible_request fails fast, before the engine loop, on a
request vLLM would reject at admission; a comment on each check says what it
guards.
…ents

GenerationServer now rejects a prompt of max_rollout_tokens tokens or more,
the same bound as TokenEnv.Config.max_rollout_tokens and vLLM: a prompt of
exactly max_model_len passed Verifiers' pre-flight check and the server, and
reached the generator. Shorten the comments per review.
…if an engine loop dies

Addresses review on the generator pre-check, which copied two of vLLM's admission rules.

- The engine loop renders and admits each request on its own and catches
  ValueError, the type vLLM raises for prompt length, sampling params and
  out-of-vocab token ids, before it changes engine state. Only that request's
  reply fails. The checks are deterministic, so every TP rank of a replica
  rejects the same requests and the ranks stay in step.
- A rejection on rank 0's DP replica fails its reply directly. Another DP
  replica's TP rank 0 sends a _RejectedRequests message to rank 0 over the
  existing result port; rank 0's drain task fails those replies and frees
  their DP-router reservations.
- generate() no longer pre-checks; _rank0_reject_inadmissible_request is gone.
- New wait_engine_loop on the generator (and its actor endpoint) and
  wait_engine_loops on the router (every rank of every generator). The
  controller runs it as a background task in run(), so a crashed engine loop
  fails the run with its own error instead of leaving a closed generator that
  fails every call routed to it. The wait only awaits the engine loop's
  future: both endpoints are concurrent endpoints and nothing blocks, so
  generate, pull_model_state_dict and close keep being served.
- VerifiersRollouter warns when a rollout stops for context length before
  its first turn: the harness builds the first prompt in the env server, so
  the dataset can't be filtered for it.
- GenerationServer's 400 for a prompt without room for output is unchanged.
…ed engine loop

- Admission catches (ValueError, VLLMClientError): VLLMValidationError is not a
  ValueError, so an overlong prompt crashed the engine loop instead of failing
  only its request.
- wait_engine_loop streams per-rank replies, so the first crashed rank raises
  without waiting for its TP peers stuck in collectives.
- Rename to wait_engine_loop / _generator_loop; document the watcher's scope
  and the max_rollout_tokens <= max_model_len assumption.
- Drop "task None" from the rollouter's overlong-prompt warning.
@wwwjn
wwwjn force-pushed the jianiw/rl-reject-overlong-prompts branch from 13ccce6 to 80d981d Compare October 12, 2026 05:17
#5290 added test_compute_rollout_metrics_folds_generator_metrics with
RolloutTurn(prompt_token_ids=...), but #5273/#5274 had replaced that field
with prompt_prefix_len / prompt_delta_token_ids and made the per-token fields
numpy arrays, so the test fails on main with a TypeError.
@wwwjn
wwwjn merged commit cc0ad1f into main Oct 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants