Repository navigation
[rl] Fail an invalid generation request without crashing the generator - #5182
Conversation
| 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." | ||
| ) |
There was a problem hiding this comment.
do we want to raise? what would it crash?
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
No clue why it is here
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
if sampling already check those, does it check the max seq len? and if so, do we need the extra raise then?
tianyu-l
left a comment
There was a problem hiding this comment.
please address my nit, and also wait for felipe's approval
| # Constructing SamplingParams validates them. | ||
| self._build_sampling_params(sampling) |
There was a problem hiding this comment.
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.
| engine_loops_task = asyncio.create_task( | ||
| self._wait_engine_loops(), name="generator_engine_loops" | ||
| ) |
There was a problem hiding this comment.
this is new to me, so I have to review again
but anyways, this should be renamed to generator_task to match others?
There was a problem hiding this comment.
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 aprocess_rejected_requests(), similar toprocess_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
left a comment
There was a problem hiding this comment.
sounds reasonable, I'll trigger claude for another review.
| engine_loops_task = asyncio.create_task( | ||
| self._wait_engine_loops(), name="generator_engine_loops" | ||
| ) |
There was a problem hiding this comment.
| 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: |
There was a problem hiding this comment.
| async def wait_engine_loops(self) -> None: | |
| async def wait_engine_loop(self) -> None: |
|
@claude review this PR |
|
Claude finished @tianyu-l's task in 3m 38s —— View job Review: [rl] Fail an invalid generation request without crashing the generator
Overall: I think the design is right. Catching the error per request at admission (instead of copying vLLM's checks into 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)
When rank 0's engine loop crashes, its peer TP ranks are usually blocked in
2. Watcher: nothing tests the new path through
|
| 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) | .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) |
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.
13ccce6 to
80d981d
Compare
Problem
vLLM validates a request's prompt and sampling params only when the generator's engine loop admits it (
render_cmpl/add_requestinVLLMGenerator._engine_loop). An error there escapes the loop: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:
TokenEnvcheckslen(next_prompt) >= max_rollout_tokensbefore every generation, butmax_rollout_tokensdefaults toNone, which disables the check.max_model_lenthatGenerationServeradvertises onGET /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 exactlymax_model_lenpasses.LLMEngineinside a shared engine loop, so the same request crashed it instead.Fix
1. A request vLLM rejects fails alone (
VLLMGenerator._engine_loop).render_cmpl([prompt]), thenadd_request) and catchesValueError.ValueError(includingVLLMValidationError) is what vLLM raises for every admission check, all before it changes engine state:max_model_len;max_model_len(no room for an output token);max_tokens=0;generate()from the earlier commits is removed.2. Rejections on any DP replica reach rank 0 (
RequestDispatcher)._RejectedRequestsmessage to rank 0 over the existing result port. Rank 0's drain task fails those replies and frees their DP-router reservations.generate()call would hang.3. A dead engine loop fails the run (
wait_engine_loop→wait_engine_loops→Controller.run).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 servinggenerate,pull_model_state_dictandclose.close()).@concurrent_endpoint, likegenerate, so Monarch runs it alongside other calls. That decorator is what makes this safe: a plain@endpointhandles one call at a time, so a call that never returns would block every later call to that actor.wait_engine_loopsis also aconcurrent_endpoint. It callswait_engine_loopon every rank of every generator and suspends in_fanout; routinggeneratecalls continues.run()already waits on withasyncio.wait.run()raises.run()re-raises the engine loop's error; if it returned,run()raises "exited unexpectedly".4. Clean errors for HTTP clients (
GenerationServer).max_rollout_tokenstokens or more with HTTP 400. That's the same bound asTokenEnv.Config.max_rollout_tokens: the prompt plus at least one output token must fit.context_length.ValueErrorwould 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).Notes
max_tokens>max_model_len: vLLM'sLLMEnginepath admits such a request withmax_tokensunchanged and stops it atmax_model_lenwithfinish_reason="length"(check_stop). That isn't an error, so nothing here changes it. vLLM's OpenAI server rejects it instead, because it renders withmax_output_tokens=max_tokens.render_cmpltokenizes nothing for token prompts, so the extra calls are cheap._build_sampling_paramsstill runs once per request, as before.Not in this PR (follow-ups)
AgentConfig.max_total_tokens, so rollouts stop by context size on the env side, asTokenEnvdoes.renderers(upstream): should retry a failed/v1/modelslookup instead of caching "no limit".