Skip to content

[rl] hold each multi-turn session's KV between its turns (5/5) - #5220

Merged
tianyu-l merged 24 commits into
mainfrom
felipemello1/session-kv/5-hold-session-kv
Oct 15, 2026
Merged

tianyu-l merged 24 commits into
mainfrom
felipemello1/session-kv/5-hold-session-kv

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

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. VLLMSessionKVHolder keeps 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.

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

Problem

  1. A multi-turn rollout re-sends its whole history every turn. vLLM skips recomputing it only while the history is still cached.
  2. When a turn finishes, its blocks become "free but cached", and any new request can take them.
  3. For a hybrid model, a continuation also needs the Gated-DeltaNet state saved at the previous prompt's end. vLLM's "align" mode hands that block back to the free pool as soon as decode starts, ~1-3 min before the turn ends.
  4. Under load, the turn's next call misses and recomputes its whole history. A CPU probe on vLLM's real KV manager: hold at finish -> 0 tokens hit after churn; hold right after prefill -> full hit.

Solution

  1. VLLMSessionKVHolder (torchtitan/rl/generator/vllm/session_kv_holder.py), a Configurable built by the generator when session_kv_holder is set. The engine loop calls it at admission (track), once after each engine step (after_step), and when sessions end (release):
    • Right after a request's prefill, hold the blocks vLLM's own prefix lookup says a continuation would hit: attention plus the matching GDN state blocks (block_pool.touch).
    • The session's next prefill takes a new hold, then drops the old one.
  2. Release:
    • when the rollout ends (release_session): the router always forwards it to the generator the session is pinned to; without sticky routing, at group end;
    • at group end (release_groups);
    • after each step, while fewer blocks than a floor are free, so the next step has room: sessions idle longest first, including those whose next request is still waiting (it references none of its blocks yet, so the cost is at most a recompute); only sessions with a running request are skipped. The holder can't act inside a step, so the floor is derived from the engine, with no config field: vLLM's watermark plus the most blocks the next step can add to running requests, which vLLM schedules before it admits new ones. Per KV cache group: one block per running request (GRPO siblings cross a block boundary together) + cdiv(max_num_scheduled_tokens, block_size) (one prefill chunk).
    • after a step where nothing runs and requests wait: with an empty batch vLLM admits the head unless its blocks don't fit, so idle sessions are released, oldest first, until some blocks come back. Without this, held blocks could stall the engine for good: nothing running, free above the floor, and the head needing more than free.
    • A release only demotes: the blocks return to vLLM's LRU free queue with their hashes, so they stay prefix hits until reused.
  3. Releases ride the engine-loop decision that every rank receives, so all TP ranks apply them at the same point.
  4. Held blocks count in vLLM's KV usage. Works with any vLLM watermark, since the floor is read from the built engine. Incompatible with reset_kv_cache_on_model_state_dict_load=True (config check).
  5. Off by default. Without a holder, the forwarded release is a no-op on the generator.

Results

GB300, 35B-A3B chess self-play, the hold on (an earlier fixed free floor of 0.05, watermark 0.03), steps 2-6:
  sessions held per generator    126-252
  released by the free floor     0
  prefix hit                     93-96%
  KV use                         52-66%
A run without the hold had the same prefix hit (93-96%): with KV use under ~66%, little was evicted either way.

CPU (vLLM KVCacheManager, 1 attention + 3 Mamba align groups):
  next turn hits 48/50 prompt tokens after full churn with the hold, 0 without
  80 blocks, 12 held sessions (7 free), nothing running, a 10-block turn waiting:
    floor rule only (before)  never admitted in 20 steps
    this PR                   admitted after the stall release

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:

  • Why off by default? With KV use under ~66% the hold changed nothing on GB300 (93-96% prefix hits either way); a run under memory pressure comes first.
  • Why hold right after prefill, not when the request finishes? The GDN state block leaves the request when decode starts, and under load a freed block survives ~78 s (estimate) while a turn decodes for ~1-3 min.
  • Why always forward a session's release, even without a holder? It saves a flag; the cost is one actor call per rollout (not per turn) to a no-op endpoint.
  • How does this relate to vLLM request priority? Priority orders requests in vLLM's queue; the holder protects blocks of sessions that have no request in vLLM (between turns), which priority can't see.

NOTE:

  • The hold may take an older duplicate of a block that the request also owns, about one extra block per session while it decodes.
  • The holder's constructor raises on partial hash hits and on speculative decoding, since both move the replay point.
  • After any re-pin (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.
  • A turn that doesn't fit in the blocks left above the watermark starts only once the running batch ends (then the stall release admits it).
  • Derived floor before the watermark, from vLLM's logged KV size (4 KV cache groups): Qwen3.5-4B (~4,600 blocks, 2,048 batched tokens) 16 blocks + 4 per running request, so 136 blocks (2.9%) at 30 running and 336 (7.3%) at 80; 35B chess on GB300 (8,169 blocks, 8,192 batched tokens) 32 + 4 per running request, so 464-1,168 (5.7-14.3%) at the 108-284 requests it ran. The old fixed default was 5%.
  • Hybrid models at TP>1: the holder raises if vLLM turns on partial-block hits. Qwen3.5-4B at TP=2 held fine (6/6's TP=2 run); other sizes are untested.
  • Not run on GPU with this branch. The GB300 run used a different router release path and never reached 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, including test_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) and test_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.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Oct 9, 2026
@felipemello1
felipemello1 added this pull request to stack #5221 October 9, 2026 15:45
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 9, 2026
@felipemello1
felipemello1 force-pushed the felipemello1/session-kv/5-hold-session-kv branch from 5e8d04e to 4244c1e Compare October 9, 2026 16:42
@felipemello1
felipemello1 marked this pull request as ready for review October 9, 2026 23:15
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 9, 2026
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])

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 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.

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: we kept the per-rollout forward to the pinned generator. Reasons:

  • The generator half already works like async GC. release_sessions only 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.

Comment thread torchtitan/rl/generator.py Outdated
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,

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.

Instead of adding them to every decision variant, it should be cleaner to do them to the final decision.

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. 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
):

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.

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?

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: 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 pzhan9 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.

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.

Felipe Mello added 4 commits October 11, 2026 12:49
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.
@felipemello1
felipemello1 force-pushed the felipemello1/session-kv/5-hold-session-kv branch from 4244c1e to a0c3aca Compare October 11, 2026 20:01
@felipemello1
felipemello1 removed this pull request from stack #5221 October 11, 2026 20:03
@felipemello1
felipemello1 added this pull request to stack #5293 October 11, 2026 20:03
Felipe Mello added 5 commits October 11, 2026 21:32
…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.

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.

could you rebase? current diff shows previous commits as well

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. 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,

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 need this flag? What if we always forward

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: 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.

Comment thread torchtitan/rl/generator.py Outdated
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

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.

can we do something like

Suggested change
session_kv_free_floor: float = 0.05
session_kv_min_free_ratio: float = 0.05

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.

why we only need such flag when hold_session_kv is on?

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: 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.

Comment thread torchtitan/rl/generator.py Outdated
Comment on lines +1139 to +1147
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"

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.

reads too involved, can we move the check into SessionKVHolder constructor.

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. Both checks live in VLLMSessionKVHolder.__init__ now, as ValueError. The generator only builds it: config.session_kv_holder.build(scheduler=...).

Comment thread torchtitan/rl/session_kv_holder.py Outdated
from typing import Any


class SessionKVHolder:

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
class SessionKVHolder:
class VLLMSessionKVHolder:

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.

Comment thread torchtitan/rl/generator.py Outdated
vllm_stat_logger: VllmOtelStatLogger.Config | None = None
"""Optional logger instantiated on TP rank 0 to export vLLM metrics."""

hold_session_kv: bool = False

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 think we should make VLLMSessionKVHolder a configurable here, and include session_kv_free_floor as its config.

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. 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).

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.

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

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: 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.

Felipe Mello added 10 commits October 12, 2026 08:19
# 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.
Base automatically changed from felipemello1/session-kv/4-repin-load-ratio to main October 13, 2026 20:43
@@ -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

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 agree with keeping it optional, but should it be turned on by default?

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: 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.

Comment thread torchtitan/rl/generator.py Outdated
# 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(

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.

let's unify the name

Suggested change
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.

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: _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.

Comment thread torchtitan/rl/generator.py Outdated
Comment on lines +1462 to +1467
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()

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.

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?

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: 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.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review my reviews, especially on the two session KV holder methods

@claude

claude Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

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


Review of tianyu-l's comments

  • Read the holder (torchtitan/rl/session_kv_holder.py) and the engine loop (torchtitan/rl/generator.py:1387-1470)
  • Explain evict_until_free / after_step and whether we need them
  • Go through the other two comments (default-on, naming)

1. evict_until_free() / after_step() (generator.py:1462-1467)

Short answer: both are needed. These two calls are the manual management. vLLM has no "prefill finished" or "about to allocate" callback, so the holder has to poll the scheduler around each engine.step(). Each call has one job that only it can do:

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 floor

That'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_free builds running_ids (a set over all running requests) on every step, even though it usually returns immediately. Compute the floor from len(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_step scans all of _live every step to find prefill completions and finished requests. That's fine for now. The finished case could also be read from request_outputs[*].finished instead of probing scheduler.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 / VLLMSessionKVHolder name / 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 result Config has 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 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 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:

Felipe Mello added 4 commits October 14, 2026 09:59
# 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.
@felipemello1

Copy link
Copy Markdown
Contributor Author

reply from claude: from the bot review:

  • taken: one holder hook per step, and the running-session set built only when it has to evict;
  • kept off by default, with the reasons in that thread;
  • not taken: reading finished requests from request_outputs. It needs a map from vLLM's internal ids to ours, and per step it only scans the live requests.

I also merged main (the package reorg) and moved the holder to generator/vllm/.

@tianyu-l
tianyu-l merged commit 13ab793 into 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.

3 participants