Skip to content

[rl][easy] vLLM priority scheduling: serve rollout groups in the order they started - #5257

Merged
felipemello1 merged 6 commits into
pytorch:mainfrom
felipemello1:rl/priority-by-policy-version
Oct 15, 2026
Merged

felipemello1 merged 6 commits into
pytorch:mainfrom
felipemello1:rl/priority-by-policy-version

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

TLDR: vLLM now serves requests in the order their rollout groups started, instead of first-come-first-served: every turn of an older group is admitted first from the queue and preempted last. On main, a multi-turn rollout's next turn waits behind groups that started after it. Not measured yet; our multi-turn runs rarely queue requests, so for them this is headroom.

Problem

  1. Many groups. In async RL, one generator serves many rollout groups at once, started under several policy versions.
  2. FCFS. The generator hard-codes scheduling_policy="fcfs", so vLLM admits queued requests in arrival order.
  3. Late turns wait. A multi-turn rollout's next turn is a new request, so it queues behind the first turns of groups that started later.
  4. Repeat victims. When the KV cache is full, FCFS preempts the request that entered the running set last, so an old request that just resumed is preempted again.
  5. When. Single-turn math on GB300 kept 150-290 requests waiting per engine all night and had ~730 preemptions per engine-hour while filling up (watermark 0.03). Its arrivals already follow start order closely, so it mostly gains from point 4.
  6. Headroom. Terminal-Bench and chess had 0 requests waiting in their first waves and at most 35 in chess's refill, so point 3 does not bite them today.

Solution

  1. Priority. Pass each request's priority to vLLM and set scheduling_policy="priority". Lower runs first.
  2. Priority = group_id. Every request already carries it. Training group ids are dataloader indices, so they grow as groups start. Every rollout and turn of a group shares it.
  3. Validation. Its group ids count down (-1, -2, ...) and restart every validation run, so all validation shares priority -1 (max(group_id, -1)): it goes before training, in arrival order.
  4. Ties. vLLM breaks ties by arrival_time. Rank 0 stamps it in generate and broadcasts it on EngineRequest, so a TP rank whose clock jumps back cannot schedule a different batch.
  5. Unchanged. min_policy_version still salts the prefix cache and measures policy age. No new config field.
one generator, one policy version; requests in arrival order:
  g1 turn 1 (t=0)   g2 turn 1 (t=1)   g3 turn 1 (t=2)   g1 turn 2 (t=3)
priority = group_id: g1 = 1, g2 = 2, g3 = 3

vLLM waiting queue at t=3 (g1 turn 1 has finished), front first
before (fcfs):     g2 turn 1 | g3 turn 1 | g1 turn 2
after (priority):  g1 turn 2 | g2 turn 1 | g3 turn 1

preemption victim  before: the request that entered the running set last
                   after:  the youngest group's latest request

You may ask:

  • Main says continuous batching requires FCFS. Why is priority safe? FCFS kept every TP rank admitting in the broadcast order. Priority order depends only on priority and arrival_time, both set by rank 0, so the ranks still agree (ties: see NOTE).
  • Does a queued old request now evict running new ones? No. vLLM preempts only when a running request can't grow. Only the victim changes, so preemption counts can move either way.
  • Why not the policy version, as this PR first did? Within one version it falls back to arrival order, so an old group's turn 5 still queues behind a new group's turn 1. Start order refines it: groups that started earlier, under older policies, have smaller ids.
  • Why does validation go first? Its negative ids give that with one max(group_id, -1). On main, validation runs only before and after training, so no training request waits behind it. Once validation runs beside training, it would delay training's next batch, and that change can pick validation's priority.
  • Why not a config field to keep FCFS? No workload should serve newer groups first. The heap costs ~1.2 us per add + pop with 500 waiting, vs ~0.1 us for FCFS (CPU microbenchmark of vLLM's two request queues).

NOTE:

  • Resumes. Replayed groups carry the oldest ids, so they now go first, and they are often slow stragglers: the groups in flight longest when the checkpoint was saved.
    • On two Terminal-Bench resumes (FCFS), the oldest 24 groups ended at 8,071 s and 6,622 s. The first batches (24 groups) formed at 1,910 s and 1,968 s, from younger groups.
    • In the first resume, the 94 oldest groups ran a median of 139 turns, against 33 for the other 50.
    • So start order may delay the first batch after a resume whenever vLLM queues or preempts (not measured). Watch the first step after a resume.
  • Not measured: no RL A/B (policy age, preemptions, tok/s) and no GPU run.
  • time_to_first_token_ms (and vLLM's e2e latency) now start when generate is called. So they also count the wait for the next engine-loop decision (up to one burst of steps, longer behind a weight pull), the decision broadcast and prompt rendering. On a DP replica on another host, they also include the clock skew between hosts. queue_time_ms still measures only vLLM's queue.
  • Equal priority and arrival time fall back to vLLM's internal id: ours plus a random per-rank suffix. TP ranks still agree unless one request id is another plus -..., which our ids never are.

Test plan

pytest tests/rl/unit_tests/cpu/test_engine_loop.py tests/rl/unit_tests/cpu/test_generator.py
pytest tests/rl/unit_tests/cpu  # 459 passed, 5 skipped (main: 458 passed); both have the same 3 failures: 2 in test_verifiers_terminal_bench.py, 1 in test_rollout_worker.py

New: test_admission_passes_group_id_as_priority_and_arrival_time. It fails with priority = min_policy_version or without the -1 clamp.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 10, 2026
@felipemello1
felipemello1 force-pushed the rl/priority-by-policy-version branch from 791ba1e to d703ee3 Compare October 11, 2026 20:02
@felipemello1 felipemello1 changed the title [rl] vLLM priority scheduling: requests from older policies first [rl] vLLM priority scheduling: serve rollout groups in the order they started Oct 11, 2026
@felipemello1
felipemello1 marked this pull request as ready for review October 12, 2026 06:21
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 12, 2026
@felipemello1
felipemello1 force-pushed the rl/priority-by-policy-version branch from d703ee3 to 8099764 Compare October 12, 2026 06:48
@felipemello1 felipemello1 changed the title [rl] vLLM priority scheduling: serve rollout groups in the order they started [rl][easy] vLLM priority scheduling: serve rollout groups in the order they started Oct 12, 2026
Comment thread torchtitan/rl/generator.py Outdated
request.min_policy_version = self._group_min_policy_versions.setdefault(
request.group_id, self.policy_version
)
request.arrival_time = time.time()

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.

question: why timing is set here in the engine loop's _decide_next_action, instead of when entering the generate method where the request is constructed?

I don't know if it matters in practice, but feels more natural there.

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.

reply from claude: Good point, moved it. generate now builds the request with arrival_time=time.time(), so it's a plain constructor field (no field(init=False), no stamp in _decide_next_action).

  • Still rank 0's clock: generate only runs on rank 0, and the value is broadcast inside EngineRequest, so TP ranks still agree.
  • Same tie order: the engine-loop queue is FIFO and drained in order.
  • One metric change: vLLM measures TTFT from arrival_time, so time_to_first_token_ms now also counts the wait for the next engine-loop decision (up to one step burst, longer behind a weight pull). queue_time_ms still measures only vLLM's queue. The PR description's NOTE says this now.

Comment on lines 1283 to 1289
engine_request=EngineRequest(
request_id=request_id,
prompt_token_ids=prompt_token_ids,
sampling=sampling,
group_id=group_id,
routing_session_id=routing_session_id,
),

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 mean setting the arrival_time 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.

reply from claude: Done, it's set here now (arrival_time=time.time() in the EngineRequest(...) call). Details in the other thread.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR and my review

@claude

claude Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 45s —— View job


Review of #5257 and @tianyu-l's question

  • Gather the diff and context
  • Review the PR
  • Answer the question about where arrival_time gets set

Your question: set arrival_time in generate (L1283-1289) or in _decide_next_action (L1525)?

Both places are correct. generate is rank-0-only (_rank0_check_engine_loop_running), so either way the timestamp comes from rank 0's clock and is broadcast inside EngineRequest. The TP-agreement argument from the PR holds in both. Tie-breaking also comes out the same: _engine_loop_queue is FIFO and _decide_next_action stamps in drain order, so arrival order matches enqueue order either way. Only two things change:

  1. What time_to_first_token_ms measures. vLLM's first_token_latency is counted from arrival_time. If you stamp in generate, TTFT also includes the time a request waits in the engine-loop queue before admission. That is up to one step burst (max_engine_steps_between_decisions steps). It also includes any weight pull that comes first, since a pull is applied before pending requests and they carry over to the next decision (L1509-1514). That is the latency the rollout actually sees. It can also make TTFT jump around pull boundaries. queue_time_ms (scheduled_ts - queued_ts, from vLLM's own timestamps) is unaffected, so you could still separate engine-loop wait from vLLM queueing.
  2. Code shape. Stamping in generate lets arrival_time be an ordinary required init field instead of field(init=False) set later. The tests would pass it to the constructor rather than setting it by hand (test_engine_loop.py:1054, test_generator.py:363). The case for the current spot is that all admission metadata (min_policy_version plus arrival_time) gets set in one place.

Recommendation: I lean slightly toward your suggestion. "Arrival" naturally means when the caller asked. The field becomes a plain constructor argument, and the only downside is a TTFT definition change. If @felipemello1 keeps it in _decide_next_action, the code is fine. In that case, the EngineRequest.arrival_time docstring should say it's the admission time, so TTFT excludes engine-loop queue and pull wait. Either way, the PR's NOTE about the TTFT semantics change should match the final choice.

Review of the PR

The change is small and correct. The reasoning in the description holds up when checked against the code.

Verified

  • add_request is called in only one place in the loop (L1406), and priority/arrival_time are passed on every rank. torchtitan/rl/generate.py:246 is a standalone script that keeps the default policy, so it's unaffected.
  • Where group_id comes from:
    • Training: controller.py:998, the dataloader index.
    • Validation: controller.py:726, -(i + 1).
    • Both match the docstring's "validation first" claim.
  • Rank 0 stamps every pending request in the STEP branch, before routing (L1517-1525), including requests carried over from a decision that turned into a pull. So no follower can see an unset arrival_time. With slots=True and init=False, an unset value would raise AttributeError loudly instead of silently diverging, which is good.
  • The new test pins the essential property: priority is group_id, not min_policy_version. It fails on the earlier version of the PR.

Minor / worth a look

  1. Externally chosen priority (verifiers). In examples/verifiers/generation_server.py:212, group_id comes from client sampling_params, and it now also sets vLLM priority. A client that sends small or negative ids would jump ahead of everything else on that generator. This is probably fine for an example, but a line in that file's docstring that group_id now also controls scheduling would help.
  2. Resume stragglers. The NOTE already flags that replayed groups go first. Consider logging it, e.g. watching num_preemptions and first-step latency on the first resume with this change, before calling it neutral. No code change needed.
  3. Comment wording (L1010-1011): "Priority = EngineRequest.group_id" doesn't say what the priority orders. Something like # vLLM admits lower priority first and preempts it last; priority = EngineRequest.group_id (see its docstring). would stand on its own.
  4. Lint. I couldn't run pre-commit here. The new TODO line at L1011 and the docstring lines at L1712 and L1725 look close to the line-length limit, so it's worth a quick pre-commit run --all-files.

No blocking issues. Your approval stands from my side; the arrival_time placement is a style/metric-semantics call, not a correctness one.

Felipe Mello added 5 commits October 12, 2026 10:08
The generator passes each request's min_policy_version as its vLLM priority and
switches the engine to scheduling_policy="priority". Queued requests from older
policies are admitted first, and running ones are preempted last when the KV
cache is full.

Rank 0 stamps each request's arrival_time and broadcasts it, since vLLM breaks
priority ties by arrival time and every TP rank must schedule the same batch.
Each request's vLLM priority is now its group's start order instead of its
min_policy_version. Training groups use their id, a dataloader index that grows
as groups start, so every turn of an older group goes ahead of a newer group's
turns, also within one policy version.

A validation group (negative id) takes the newest training group id the
generator had seen at its first admission, kept until release_groups, so it runs
after the training groups that started before it.

min_policy_version still salts the prefix cache and measures policy age.
Every request already carries its group_id, so the engine loop passes it as the
vLLM priority. Validation ids are negative, so validation now goes before
training. On main, validation runs only before and after training, so no
training request waits behind it.

Drops EngineRequest.priority, the validation priority map and its release.
generate (rank 0 only) now builds each EngineRequest with arrival_time=time.time(),
so it is a plain constructor field instead of a field(init=False) stamped in
_decide_next_action. Tie order and TP agreement are unchanged; vLLM's TTFT now also
counts the wait in the engine-loop queue.

Also rewords the scheduling_policy comment and the generate docstring, and renames
the admission test.
Validation group ids count down (-1, -2, ...) and restart every validation run,
so passing them raw would serve the newest validation request first. The engine
loop now passes max(group_id, -1): all validation runs before training, in
arrival order among itself. Training priorities are unchanged.
@felipemello1
felipemello1 force-pushed the rl/priority-by-policy-version branch from 8099764 to 8819125 Compare October 12, 2026 17:46
@felipemello1

Copy link
Copy Markdown
Contributor Author

reply from claude: Thanks. On the minor points:

  1. Verifiers: no change. Only our rollouter sets torchtitan_group_id, to the controller's group id, and the Verifiers harness forwards it unchanged to a localhost server. So the priority there comes from the same group_id as everywhere else.
  2. Resume stragglers: agreed, no code change. The NOTE says to watch the first step after a resume.
  3. Comment wording: done, now "Smaller priority runs first and is preempted last; we pass EngineRequest.group_id (-1 for all validation), so older groups have higher priority (see its docstring)."
  4. Lint: pre-commit passes on the changed files.

New since the approval: validation ids count down and restart every run, so all validation now shares priority -1 (max(group_id, -1)) and runs in arrival order, before training.

@felipemello1
felipemello1 merged commit ded719f into pytorch:main Oct 15, 2026
tianyu-l added a commit that referenced this pull request Oct 17, 2026
…gine; add GenerationEngine (#5317)

Stacked on #5316.

## Why

`torchtitan/rl/generator/generator.py` (1860 lines) mixed three concerns
in one class, `VLLMGenerator`:

- calls into vLLM (`EngineArgs`, `render_cmpl` + `add_request`, `step`,
`SamplingParams`, `RequestOutput` parsing, prefix-cache reset,
teardown);
- request dispatch across data-parallel replicas and fan-in of results
to rank 0;
- the engine thread and its SPMD loop (queue, rank 0's decision,
broadcast, step bursts, load coalescing).

That makes each part hard to read in isolation and ties the generator to
vLLM. This PR splits the file along those lines and puts the inference
engine behind an interface, so a second engine (e.g. SGLang) can be
added as another `GenerationEngine` without touching the generator, the
engine loop or the dispatcher.

## What changed

**Generator split**

| File | Contents |
| --- | --- |
| `generator/generator.py` | `Generator` (was `VLLMGenerator`), the
service: config, setup and endpoints |
| `generator/engine_loop.py` | `EngineLoopThread` (the thread and event
loop the engine lives on) and `EngineLoop` (queue, decide -> broadcast
-> apply, load coalescing, policy version, per-group cache-salt pins) |
| `generator/dispatcher.py` | `RequestDispatcher` and the rank-0
completion metrics |
| `generator/types.py` | `SamplingConfig`, `EngineRequest`,
`FinishedRequest`, `RequestMetricsInputs` |
| `generator/engine.py` | `GenerationEngine`, the engine interface |
| `generator/vllm/engine.py` | `VLLMEngine`, holding every vLLM call |
| `generator/vllm/config.py` | `VLLMCudaGraphConfig` |

The dispatcher now receives engine-agnostic `FinishedRequest`s instead
of vLLM `RequestOutput`s, and rank 0 builds each `Completion`. Peer
replicas used to send a `Completion` with a placeholder
`min_policy_version` that rank 0 overwrote; they now send their
`FinishedRequest`s plus the policy version installed when those
finished.

**Engine interface**

- `VLLMGenerator` -> `Generator`, `VLLMGeneratorActor` ->
`GeneratorActor`.
- `GenerationEngine` (`generator/engine.py`) is the interface the engine
loop and the generator call: `add_requests`, `step`,
`has_unfinished_requests`, `load_prefetched_model_state_dict`,
`shutdown`, `prefetched_model_state_dict`, and the data-parallel layout.
Its docstring lists the build arguments every engine accepts.
- `VLLMEngine` implements it. vLLM setup, `EngineArgs` and the stat
logger are private `VLLMEngine` methods, and the engine is built from
its config on the engine loop thread.
- Only `generator/vllm/` imports vLLM; `generator.py` imports the
default engine config lazily.

**Monarch README**

`actors/monarch/README.md` lists the Monarch adapters and the Monarch
use that still lives outside them (provisioning in `train.py`, spawning
in the controller and rollouter, `InterGeneratorRouter` as an `Actor`,
and the RDMA microbatch), with the planned path to confine it to
`actors/monarch/`.

## User-facing changes

- `VLLMGenerator` -> `Generator`, `VLLMGeneratorActor` ->
`GeneratorActor`.
- vLLM-only settings move from `Generator.Config` to
`VLLMEngine.Config`, selected by the new `Generator.Config.engine`
(default `VLLMEngine.Config()`):

  | Before | After |
  | --- | --- |
  | `generator.cuda_graph` | `generator.engine.cuda_graph` |
| `generator.extra_vllm_engine_args` |
`generator.engine.extra_engine_args` |
  | `generator.vllm_stat_logger` | `generator.engine.stat_logger` |
| `generator.session_kv_holder` | `generator.engine.session_kv_holder` |

Engine-agnostic settings stay on `Generator.Config` and are passed to
the engine's build: `model_dtype`, `gpu_memory_limit`,
`max_num_batched_tokens`, `checkpointer`, `dist_moe_runtime`, `debug`.
Every recipe and test is updated. Only Python configs change: the CLI
has no per-field overrides, and `--override` targets override functions,
not config paths.
- `SamplingConfig` moves to `torchtitan.rl.generator.types`,
`VLLMCudaGraphConfig` to `torchtitan.rl.generator.vllm.config`, and
`add_extra_vllm_engine_args` to `torchtitan.rl.generator.vllm.engine`;
every caller is updated.

## Execution order

The per-iteration sequence is unchanged: decide, broadcast, stamp
versions, admit, step burst, fan-in, load. The differences:

- The engine's process-wide setup (`register_to_vllm`, the model runner
env var, the batch-invariant logprob patch) now runs on the engine loop
thread inside the engine build, after `set_batch_invariance` and the
determinism flags. vLLM reads neither at import time.
- `RequestOutput` -> `FinishedRequest` conversion happens in
`VLLMEngine.step` on every rank, not only TP rank 0 (a small list copy
on the other ranks; the n=1 check now fires on every rank instead of
only rank 0).
- A model state dict load sets the policy version after the optional
prefix-cache reset rather than before; both run synchronously on the
engine loop thread, and nothing reads the version in between.
- `generate`'s `stop_token_ids` assert runs before the
closed/not-started guard (error path only).
- Session KV release (#5220) runs through the engine loop as a
`SessionReleaseMessage`, applied on every rank in the next decision;
vLLM priority scheduling (#5257) passes `group_id` as the priority and
rank 0's `arrival_time` to every rank, as on main. Because
`session_kv_holder` is vLLM-only, its check against
`reset_kv_cache_on_model_state_dict_load` now fails when the engine is
built rather than when `Generator.Config` is constructed.

## Testing

- RL CPU unit tests: 492 passed, 8 skipped (rebased on `dc9ea005e`).
`test_engine_loop.py` drives `EngineLoop` directly with a fake engine;
`VLLMEngine`'s admission, salting, rejection, step, shutdown and
KV-reset tests use a fake `LLMEngine`; the engine kwargs test builds
`VLLMEngine` through `Config.build(...)` with vLLM mocked; the
`generate` endpoint and the DP fan-in's min/max versions have their own
tests.
- `pre-commit run --all-files`: clean for the changed files (see #5316
for the unrelated local `kda.py` pyrefly errors).
- Every RL recipe builds, except a hardware-gated MXFP8 recipe.
- GPU A/B against main (2x GB300, Qwen3 debug model with random init and
a deterministic varying reward):
- on-policy, batch-invariant: all 65 non-timing metrics are bitwise
identical to main, and identical run to run;
- async (`target_offpolicy_steps=3`): within main's own run-to-run
variation.
- After the rebase onto `dc9ea005e`, CI's multi-GPU RL suites pass
locally under torchrun: bitwise parity Varlen 3/3, Flex 3/3, Qwen3.5
4/4, and the 4-GPU uneven decode test 1/1.
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.

2 participants