Repository navigation
[rl] hold each multi-turn session's KV between its turns (5/5) - #5220
Conversation
5e8d04e to
4244c1e
Compare
| self._strategy.release_session(session_id) | ||
| # Without a pin (non-sticky routing), `release_groups` frees the held KV at group end. | ||
| if self._forward_session_releases and pinned is not None: | ||
| await pinned.rank0_actor.release_sessions.call_one([session_id]) |
There was a problem hiding this comment.
I am wondering if it will overall be simpler:
- rollouter just have a background task, periodically broadcast released session ID batches to generators.
- generators have background tasks to process those session IDs.
Basically async GC.
There was a problem hiding this comment.
reply from claude: we kept the per-rollout forward to the pinned generator. Reasons:
- The generator half already works like async GC.
release_sessionsonly queues a message on rank 0, and every rank applies the whole batch at the next engine-loop decision. - The rollouter half would be new machinery in every rollout-worker process: a batcher, a background task, and its shutdown. A broadcast would also send every id to every generator, while only one of them holds it.
- Today it costs one router call plus one actor call per rollout, not per turn: milliseconds, against rollouts of seconds to minutes.
What a fan-out would buy: it would free the hold that a re-pin leaves on the old generator. Today that hold waits for its group to end or for the floor. Worth doing if re-pins become common.
| requests_per_dp_rank=[], | ||
| pull_version=max(pull.version for pull in pending_pull_messages), | ||
| released_session_ids=released_session_ids, | ||
| released_group_ids=released_group_ids, |
There was a problem hiding this comment.
Instead of adding them to every decision variant, it should be cleaner to do them to the final decision.
There was a problem hiding this comment.
reply from claude: done. PULL and STEP now each build decision, and the release lists are set once after the if/else. test_session_releases_ride_the_pull_or_step_decision checks that both actions carry them.
| ) | ||
| if self.hold_session_kv and self.session_kv_free_floor <= ( | ||
| self.watermark or 0.0 | ||
| ): |
There was a problem hiding this comment.
Does <= watermark provide enough headroom? I feel we still could end up not freeing enough memory, the new requests could not be admitted. If that is possible, should we add some way to observe that, e.g. emit a log?
There was a problem hiding this comment.
reply from claude: yes, it could stall. With nothing running, a waiting turn bigger than the free blocks never started; I reproduced this on vLLM's scheduler. Fixed since:
- The floor is derived from the engine: vLLM's watermark, plus one prefill chunk per KV cache group, plus one block per running request per group. There is no knob.
- After a step where nothing runs and requests wait, the holder releases idle sessions until blocks come back (
test_a_waiting_turn_gets_room_when_held_sessions_fill_the_pool).
To observe it: evictions are logged per step today, and the metrics PR on top of this stack logs evicted_sessions and stall_evicted_sessions per step.
pzhan9
left a comment
There was a problem hiding this comment.
lgtm. iiuc, this PR coverts vllm's LRU into a priority-based cache, whose priority is (inflight, timestamp), by borrowing the protection vllm gives running requests (ref count). Ideally this should be provided by vllm, since it will not need to rely on the session_kv_free_floor trick used by this PR.
The rollout worker calls a ReleaseSessionFn after each rollout's last turn, and the router drops the session from the sticky map. release_groups also drops any session of the group that was not released (a rollouter that never calls it, a failed release). max_sessions (262144) now bounds live sessions plus any that are never released.
With hot_swap=False every generator drains at once, and the first one back used to take every waiting turn and keep those sessions for good. Now a turn whose session is pinned to a draining generator waits for it; new sessions still go to any serving generator.
A pinned session never leaves its generator, so a slow generator keeps all its sessions. With repin_load_ratio set, a session moves to the fallback's choice once its generator holds more than that multiple of the mean load.
SessionKVHolder: right after a request's prefill, hold the blocks vLLM's own prefix lookup says a continuation would hit (attention plus the Gated-DeltaNet state block, which align mode hands back to the free pool during decode), until the session's next prefill or its end. While fewer than session_kv_free_floor blocks are free, release whole sessions, idle longest first, skipping only sessions with a running request. Releases ride the engine-loop decision so every rank applies them in the same order. With sticky routing, the router forwards a rollout's session release to the generator the session is pinned to; otherwise the group's release frees it. Opt-in VLLMGenerator.Config.hold_session_kv. It needs session_kv_free_floor above watermark and reset_kv_cache_on_weight_sync=False.
4244c1e to
a0c3aca
Compare
…group session list - release_session_fn is passed per call next to generate_fn (the controller builds one generate_fn per metrics prefix, so neither can be a setup-time field). - The router's per-group session list and _generate are gone: max_sessions guards sessions nobody releases; release_session takes only the session id.
- Drop _GeneratorState and _GeneratorHandle.state; _candidates reads h.serving and _set_state becomes _set_serving(h, serving). - Reword the pinned-wait comment: all generators drain in the same weight sync, so re-pinning would pile those sessions onto whichever serves first. - TODO to move draining into the generator.
A pinned session never leaves its generator, so a slow generator keeps all its sessions. With repin_load_ratio set, a session moves to the fallback's choice once its generator holds more than that multiple of the mean load.
There was a problem hiding this comment.
could you rebase? current diff shows previous commits as well
There was a problem hiding this comment.
reply from claude: done. 2/5 and 3/5 landed and 4/5 merged main, so this diff now shows only this layer's files. The stack moves by merges rather than rebases, so every push stays a fast-forward.
| config: Config, | ||
| *, | ||
| generators: Sequence[Any], | ||
| forward_session_releases: bool = False, |
There was a problem hiding this comment.
do we need this flag? What if we always forward
There was a problem hiding this comment.
reply from claude: agreed, removed. The router now always forwards a session's release to the generator it is pinned to. Without a holder, the generator's release_sessions is a no-op.
Cost: one actor call per rollout (not per turn), awaited by the rollout's last step: milliseconds on a rollout of seconds to minutes. The controller wiring and 6/6's or kv_offload went with the flag.
| blocks) from the end of a turn's prefill until its next turn or its end, so no other | ||
| request evicts it (see `SessionKVHolder`). Held blocks count in vLLM's KV usage.""" | ||
|
|
||
| session_kv_free_floor: float = 0.05 |
There was a problem hiding this comment.
can we do something like
| session_kv_free_floor: float = 0.05 | |
| session_kv_min_free_ratio: float = 0.05 |
There was a problem hiding this comment.
why we only need such flag when hold_session_kv is on?
There was a problem hiding this comment.
reply from claude: the field is gone. The floor is now derived from the built engine, so there is no ratio left to name:
floor = watermark_blocks
+ per KV cache group: cdiv(max_num_scheduled_tokens, block_size) # one prefill chunk
+ num_kv_cache_groups x len(running) # a block per running request at a boundary
Why only with the hold: without it, every cached block sits in vLLM's free queue, and vLLM keeps its own watermark. Held blocks have a ref count, so vLLM can't take them back. Only the hold can starve admission, so only the hold needs a floor.
| scheduler = self._engine.engine_core.engine_core.scheduler | ||
| # Partial-block prefix hits or speculative decoding move the replay point away from | ||
| # the prompt-end block that SessionKVHolder holds. | ||
| assert ( | ||
| not scheduler.kv_cache_manager.coordinator.enable_partial_hash_hits | ||
| ), "hold_session_kv does not support partial-block prefix hits" | ||
| assert ( | ||
| self._engine.vllm_config.speculative_config is None | ||
| ), "hold_session_kv does not support speculative decoding" |
There was a problem hiding this comment.
reads too involved, can we move the check into SessionKVHolder constructor.
There was a problem hiding this comment.
reply from claude: done. Both checks live in VLLMSessionKVHolder.__init__ now, as ValueError. The generator only builds it: config.session_kv_holder.build(scheduler=...).
| from typing import Any | ||
|
|
||
|
|
||
| class SessionKVHolder: |
There was a problem hiding this comment.
| class SessionKVHolder: | |
| class VLLMSessionKVHolder: |
There was a problem hiding this comment.
reply from claude: done.
| vllm_stat_logger: VllmOtelStatLogger.Config | None = None | ||
| """Optional logger instantiated on TP rank 0 to export vLLM metrics.""" | ||
|
|
||
| hold_session_kv: bool = False |
There was a problem hiding this comment.
I think we should make VLLMSessionKVHolder a configurable here, and include session_kv_free_floor as its config.
There was a problem hiding this comment.
reply from claude: done. VLLMGenerator.Config.session_kv_holder: VLLMSessionKVHolder.Config | None replaces hold_session_kv. The Config has no fields yet, because the free floor is now derived from the engine (see the session_kv_min_free_ratio thread).
There was a problem hiding this comment.
to be honest I didn't understand everything about it
vLLM holds each multi-turn session's reusable prefix between its turns, so no other request can evict it. When memory runs short, it releases whole idle sessions, oldest first.
e.g. what's the relationship with PR #5257 where we set "priority"
would like to chat
There was a problem hiding this comment.
reply from claude: I rewrote the class docstring and the PR summary around this timeline:
turn 1 prefill done -> hold the blocks turn 2 would hit (attention + Gated-DeltaNet state)
tool call -> held: no other request can take them
turn 2 prefill done -> hold the blocks turn 3 would hit, drop turn 1's hold
rollout ends -> release: the blocks go back to vLLM's free queue, still cached
Priority is orthogonal. It orders the requests in vLLM's queue: which waiting request is admitted first, and which running one is preempted last. The holder protects the blocks of a session that has no request in vLLM, between turns, so priority has nothing to act on there. Happy to chat.
# Conflicts: # tests/rl/unit_tests/cpu/test_inter_generator_router.py # tests/rl/unit_tests/cpu/test_rollout_worker.py # torchtitan/rl/distributed/routing/inter_generator.py # torchtitan/rl/generator.py
- StickySessionRoutingStrategy.Config.repin_load_ratio defaults to 1.5 (both routing layers); __post_init__ raises ValueError for <= 1. - The field and choose() docstrings draw the cases, including the low-load one. - Stickiness tests that send two calls of one session at once set repin_load_ratio=None.
…LLM's watermark - Stall: nothing runs and floor <= free < the head's blocks. The holder released nothing and vLLM admitted nothing, every step (vLLM skips the watermark with an empty batch). Now, after such a step, the holder releases idle sessions, idle longest first, until some blocks come back. - session_kv_free_floor -> session_kv_free_headroom (0.05): the holder keeps vLLM's watermark plus this fraction free before each step, so any watermark works. The floor-vs-watermark check is gone. - Test: the stall on vLLM's real KV cache manager (80 blocks, 12 held sessions, a 10-block turn), with the turn in either waiting queue.
…sion_kv_free_headroom Before each step the holder keeps free vLLM's watermark plus the most blocks that step can add to running requests, which vLLM schedules before it admits new ones: per KV cache group, one prefill chunk (cdiv(max_num_scheduled_tokens, block_size)) plus one block per running request (GRPO siblings cross a block boundary together). No config sets it. Too small costs a preemption (recompute), not a hang; too big only holds fewer sessions. Example, Qwen3.5-4B (4 KV cache groups, 528-token blocks, ~4,600 blocks, 2,048 batched tokens): 16 blocks + 4 per running request: 30 running -> 136 blocks (2.9%), 80 -> 336 (7.3%).
…always forward releases Review fixes: - SessionKVHolder -> VLLMSessionKVHolder(Configurable). VLLMGenerator.Config.hold_session_kv (bool) -> session_kv_holder: VLLMSessionKVHolder.Config | None. The Config has no fields: the free floor is derived from the engine. - The partial-block-hit and speculative-decoding checks move from the generator into the holder's constructor, as ValueError. - The router always forwards a session's release to its pinned generator; the forward_session_releases flag and its controller wiring are gone. Without a holder the generator's release_sessions is a no-op. - _decide_next_action builds the PULL or STEP decision, then sets the released sessions and groups once. - Class docstring: a turn timeline before the release rules.
…ists and the config check Review nits: the class docstring spells out Gated-DeltaNet first and ends with two bullets; the generator field docstring is one line pointing at the class; the comment above the release lists repeated LoopDecision's field comment. New tests: both PULL and STEP decisions carry the released sessions and groups; session_kv_holder with reset_kv_cache_on_weight_sync raises.
| @@ -867,7 +868,19 @@ class Config(Configurable.Config): | |||
| vllm_stat_logger: VllmOtelStatLogger.Config | None = None | |||
| """Optional logger instantiated on TP rank 0 to export vLLM metrics.""" | |||
|
|
|||
| session_kv_holder: VLLMSessionKVHolder.Config | None = None | |||
There was a problem hiding this comment.
I agree with keeping it optional, but should it be turned on by default?
There was a problem hiding this comment.
reply from claude: I'd keep it off for now.
- It hasn't paid off yet. On GB300 (35B chess self-play, an earlier version of the hold), prefix hits were 93-96% with and without it, at 52-66% KV use.
- With CPU offload on, it saves only a reload. An 8k turn on one H100 hits in 16 ms on GPU vs 23-26 ms from CPU (196 ms recomputed). At TP=2, offload plus the hold was within 2 ms of offload alone.
- On by default would also break the three batch_invariant recipes: they reset the KV cache on each load, which the holder rejects. Speculative decoding would break too.
Next is a run under memory pressure. If the hold pays off there, we flip the default with those numbers.
| # Every rank holds the same blocks in its own scheduler; only the engine thread touches them. | ||
| self._session_kv: VLLMSessionKVHolder | None = None | ||
| if config.session_kv_holder is not None: | ||
| self._session_kv = config.session_kv_holder.build( |
There was a problem hiding this comment.
let's unify the name
| self._session_kv = config.session_kv_holder.build( | |
| self._session_kv_holder = config.session_kv_holder.build( |
I'm also OK with session_kv, but need to rename the file as well.
There was a problem hiding this comment.
reply from claude: done: _session_kv_holder everywhere, so the field, attribute, class and file share one name. The file moved to torchtitan/rl/generator/vllm/session_kv_holder.py, next to the other vLLM integration code after the package reorg.
| if self._session_kv is not None: | ||
| self._session_kv.evict_until_free() | ||
| with torch.no_grad(): | ||
| request_outputs = self._engine.step() | ||
| if self._session_kv is not None: | ||
| self._session_kv.after_step() |
There was a problem hiding this comment.
Now that we are managing session KV by ourselves manually, why we'd still need these two function calls? Could you explain with simple examples what they do and why they are necesary?
There was a problem hiding this comment.
reply from claude: release() only says when a session ends. The two calls handle what happens inside vLLM's steps, where vLLM has no hook, so the holder checks the scheduler around engine.step():
- hold: session S's turn 1 finishes prefill in step k. On hybrid models (Qwen3.5), vLLM frees the prompt-end GDN state block when decode starts at k+1. So the hold has to be taken right after step k, not at the next decision, which can be up to 16 steps later.
- free floor: held blocks fill most of the pool while 8 requests decode. vLLM can't take held blocks back, so when the 8 need new blocks it preempts running requests. The holder releases the oldest idle sessions before that happens.
- stall: nothing runs, 7 blocks are free, and a 10-block turn waits. vLLM never admits it, so the holder releases idle sessions until the turn fits.
As suggested, it's one call now: after_step() ends with the free-floor check. Between two steps only release() (which frees blocks) and add_request() (which allocates nothing) run, so the check gives the same answer, or releases a step earlier.
|
@claude review my reviews, especially on the two session KV holder methods |
|
Claude finished @tianyu-l's task in 1m 25s —— View job Review of tianyu-l's comments
1.
|
| call | when | job | what happens without it |
|---|---|---|---|
after_step() |
after every step | (a) take the hold for requests whose prefill just finished; (b) note that a request has left; (c) stall release | (a) nothing ever gets held, so the feature does nothing. (c) the engine can deadlock |
evict_until_free() |
before every step | give back holds when free blocks drop below the floor | held blocks fill the pool and vLLM preempts running requests |
Simple examples (pool of 100 blocks, watermark 3):
Why after_step runs every step, not once per decision: request R (session S, hybrid model) finishes its prefill in step k. In "align" mode vLLM releases R's prompt-end GDN state block at step k+1, when decode starts. If the hold were taken only at the next decision, up to 16 steps later (max_engine_steps_between_decisions), that block would already be in the free queue and could be reused. So it has to run right after step k. The "request left" bookkeeping (move_to_end) makes the release order oldest-idle-first instead of insertion order.
Why evict_until_free is needed: 30 idle sessions hold 90 blocks and 8 requests are decoding. Held blocks have ref_cnt > 0, so vLLM's LRU can't take them back. When the 8 decoders cross a block boundary, allocate_slots fails and vLLM preempts running requests, which is worse than having no hold at all. The floor (watermark + one prefill chunk per group + groups x len(running)) releases the oldest idle sessions before schedule() runs inside step(). The holder can't act during the step.
Why after_step also has the stall release: 12 idle sessions hold 73 of 80 blocks, so 7 are free. Nothing is running, and a 10-block turn is waiting. With no running requests the floor is only watermark + chunk, so the free count can sit above it while still being below what the head of the queue needs. vLLM never admits it and nothing ever changes. test_a_waiting_turn_gets_room_when_held_sessions_fill_the_pool covers exactly this case.
But they could be merged into one call. Between after_step() at the end of step k and evict_until_free() before step k+1, the only things that run are release(), which only adds free blocks, and add_request(), which allocates nothing (allocation happens in schedule()). scheduler.running also stays the same in between. So running the floor check at the end of after_step() gives the same result, and the engine loop shrinks to a single hook:
with torch.no_grad():
request_outputs = self._engine.step()
if self._session_kv_holder is not None:
self._session_kv_holder.after_step() # hold new prefixes, stall release, then evict to the floorThat's one call site, the holder owns its own ordering, and the reviewer has one hook to reason about instead of two. Worth doing for readability. Fix this →
Smaller notes on the two methods:
evict_until_freebuildsrunning_ids(a set over all running requests) on every step, even though it usually returns immediately. Compute the floor fromlen(self._scheduler.running)first, and build the set only when an eviction is actually needed (session_kv_holder.py:135-140). At the 108-284 running requests from the GB300 run, this is per-step Python on the critical path.after_stepscans all of_liveevery step to find prefill completions and finished requests. That's fine for now. The finished case could also be read fromrequest_outputs[*].finishedinstead of probingscheduler.requests, but that would need the external id -> internal id mapping, so it's optional.- The stall release also fires when the batch drains naturally while requests wait because of
max_num_seqs. The comment acknowledges this ("one cheap extra release"), so it's OK.
2. Default on? (generator.py:871)
I'd keep it off for now and turn it on in a follow-up:
- The constructor raises on speculative decoding and on partial-block hash hits. The PR notes that hybrid models with TP>1 hit the second one. Turning it on by default would make those configs fail at build time unless the default were "on when supported", which brings back a hidden branch.
- The PR says this branch has not run on GPU, and the gain under memory pressure is unmeasured. In the GB300 run the prefix hit was the same with and without the hold (93-96%).
- Single-turn workloads get nothing from it but still pay the per-step polling and hold blocks until the rollout ends.
Suggestion: land it off, run one GPU job under memory pressure (KV use above ~85%) on this branch, then turn it on in a follow-up with the numbers.
3. Naming (generator.py:1159-1161)
Agree. self._session_kv -> self._session_kv_holder matches the config field session_kv_holder and the class VLLMSessionKVHolder. Keeping the file name session_kv_holder.py is then consistent. Remember the other references at generator.py:1215-1220, 1387, 1442, 1631, 1641, 1757. Fix this →
Your earlier comments: resolution check
- Rebase / forwarding flag / Configurable / checks moved into the constructor /
VLLMSessionKVHoldername / release lists set on the final decision (generator.py:1580-1581): all addressed in the code. session_kv_min_free_ratio: replaced by a floor derived from the engine (session_kv_holder.py:84-87, 137). I think that's better than a knob. As a resultConfighas no fields (pass). That's acceptable, since it keeps the Configurable shape for future fields.
I didn't change any code. This is review only.
tianyu-l
left a comment
There was a problem hiding this comment.
Please address my comments and claude suggestions before merge. In particular this one on simplifying session KV holder API
But they could be merged into one call. Between after_step() at the end of step k and evict_until_free() before step k+1, the only things that run are release(), which only adds free blocks, and add_request(), which allocates nothing (allocation happens in schedule()). scheduler.running also stays the same in between. So running the floor check at the end of after_step() gives the same result, and the engine loop shrinks to a single hook:
# Conflicts: # tests/rl/unit_tests/cpu/test_engine_loop.py # tests/rl/unit_tests/cpu/test_generator.py # tests/rl/unit_tests/cpu/test_inter_generator_router.py # torchtitan/rl/actors/monarch/generator.py # torchtitan/rl/generator/generator.py
…r; module under generator/vllm Review fixes: - The engine loop calls the holder once per step: after_step() now ends with the free-floor check that evict_until_free() ran before the next step (now private _evict_until_free). Between two steps only release() (frees blocks) and add_request() (allocates nothing) run, so the check gives the same answer, or releases a step earlier. - The floor check builds the set of running sessions only when it has to evict. - VLLMGenerator._session_kv -> _session_kv_holder: field, attribute, class and file share a name. - torchtitan/rl/session_kv_holder.py -> torchtitan/rl/generator/vllm/session_kv_holder.py, next to the other vLLM integration code after the package reorg. - The stall test sets its floor after the setup turns (every after_step now checks the floor), and still fails without the stall release.
|
reply from claude: from the bot review:
I also merged main (the package reorg) and moved the holder to |
…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.
TLDR: opt-in
VLLMGenerator.Config.session_kv_holder = VLLMSessionKVHolder.Config(). Between two turns of a multi-turn rollout (a tool call, an env step), the session has no request in vLLM, so any new request can take its cached blocks and the next turn recomputes its history.VLLMSessionKVHolderkeeps a reference on those blocks until the next turn or the rollout's end; when memory runs short, it lets go of whole idle sessions, oldest first. It also covers hybrid models (Qwen3.5). On vLLM's real KV manager, a next turn after full churn hits 48 of 50 prompt tokens with the hold and 0 without; on GPU the gain under memory pressure is unmeasured, so this is headroom.Problem
Solution
VLLMSessionKVHolder(torchtitan/rl/generator/vllm/session_kv_holder.py), aConfigurablebuilt by the generator whensession_kv_holderis set. The engine loop calls it at admission (track), once after each engine step (after_step), and when sessions end (release):block_pool.touch).release_session): the router always forwards it to the generator the session is pinned to; without sticky routing, at group end;release_groups);cdiv(max_num_scheduled_tokens, block_size)(one prefill chunk).freeabove the floor, and the head needing more thanfree.reset_kv_cache_on_model_state_dict_load=True(config check).Results
The GB300 run also used a KV admission gate that is not in this stack, and its releases went to the generator that gate placed the group on.
You may ask:
NOTE:
repin_load_ratio, on by default since 4/5, or an LRU eviction), the session's hold on its old generator is freed at group end or by the free floor.Test plan
pytest tests/rl/unit_tests/cpu: 486 passed, 5 skipped. New:tests/rl/unit_tests/cpu/test_session_kv_holder.py, includingtest_release_frees_sessions_in_sorted_order(every TP rank must free a release's sessions in one order),test_a_waiting_turn_gets_room_when_held_sessions_fill_the_pool(the stall; it fails without the release rule) andtest_holder_rejects_partial_block_hits_and_speculative_decoding;test_session_release_reaches_only_its_pinned_generator;test_session_releases_ride_the_pull_or_step_decision: both decisions carry the released sessions and groups;test_session_kv_holder_rejects_kv_cache_reset_on_model_state_dict_load.