Skip to content

[rl] Turn the vLLM session KV holder on by default - #5902

Closed
felipemello1 wants to merge 6 commits into
pytorch:mainfrom
felipemello1:felipemello1/session-kv-holder-default-on
Closed

felipemello1 wants to merge 6 commits into
pytorch:mainfrom
felipemello1:felipemello1/session-kv-holder-default-on

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: The vLLM session KV holder is now on by default, and it no longer pins running sessions' blocks under memory pressure. On 1 GB300 (Qwen3.5-4B, multi-turn), it is 5.3% faster than no holder at the knee and ties at heavy pressure. main's holder is 8-10% slower than this one.

# before
session_kv_holder: VLLMSessionKVHolder.Config | None = None
# after
session_kv_holder: VLLMSessionKVHolder.Config | None = field(
    default_factory=VLLMSessionKVHolder.Config
)

Problem

  1. Between turns. While a rollout waits on a tool call, its session has no request in vLLM. Its KV blocks sit in vLLM's free queue, and any new request can take them. The next turn then recomputes its history.
  2. The fix exists but is off. VLLMSessionKVHolder holds those blocks between turns. It is off unless a recipe sets it, and no recipe does.
  3. It is slow under pressure. When free blocks run short, _evict_until_free releases idle sessions only. It never releases a session whose request is running. On hybrid models the holder is the only thing keeping that request's prompt-end GDN state block, so the blocks stay pinned and vLLM preempts running requests instead.
  4. The cost. At 256 blocks, main's holder is 11% slower than no holder (226.2 vs 204.0 s), with 182 vs 70 preemptions.

Solution

  1. _evict_until_free releases sessions with no running request first, as before, then running sessions' holds, oldest first.
  2. VLLMEngine.Config.session_kv_holder defaults to VLLMSessionKVHolder.Config().
  3. The holder can't run with reset_kv_cache_on_model_state_dict_load=True: the engine raises. The 7 batch-invariant alphabet_sort configs that set reset now also set session_kv_holder=None. The reset, batch-invariant, partial-block-hit and speculative-decoding errors say to set it to None.
  4. routing_session_id is a required str from GenerateFn to the inter-generator router. No caller passed None, and with the holder on, None would put unrelated requests under one hold.
  5. Session releases sent after the engine loop closes (shutdown, a crash) are dropped, checked under the queue's lock. With the holder on, they used to raise "generator is closed".
  6. Unchanged: the order of idle sessions, the free-block floor, and every config that sets session_kv_holder itself.

Results

Multi-turn: 1 GB300, Qwen3.5-4B-Base TP1, FULL_DECODE_ONLY, 8 groups x 8 rollouts (4 groups in flight,
4-10 turns, ~384-token replies, 512 tool tokens, ~2 s tool calls). KV pool set with kv_cache_memory_bytes.
Wall time of the whole workload; cells interleaved in one process (off, pr, main, main, pr, off), mean of 2.

KV pool              no holder   this PR            main's holder   preemptions (no holder / PR / main)
256 blocks (heavy)   204.0 s     208.0 s  (+1.9%)   226.2 s         70 / 67 / 182
358 blocks (knee)    177.3 s     167.9 s  (-5.3%)   185.5 s          0 /  0 /  28

Single-turn: 48 groups x 16 rollouts, 512 sequences, 12 GiB pool (heavy pressure), off, pr, pr, off.
300-token prompts    167.5 s     177.9 s  (+6.2%)   no prefix hit (a block is 640 tokens), so the holder holds nothing
1500-token prompts   154.5 s     151.3 s  (-2.1%)

Noise: the same cell ran up to 16% faster later in the same process, so deltas under ~5% are ties.
At scale: Qwen3.5-27B on Terminal-Bench, 12 one-GPU vLLM generators (GB300), gpu_memory_limit=0.33
(574K tokens of KV per engine), ~12 requests running per engine, medians over steps 11-24.
Two jobs submitted ~4 h apart; main's eviction policy; no preemptions in either.

                 GPU prefix hit   TTFT     prefill   ITL       cached tokens per request
no holder        79.0%            435 ms   184 ms    19.7 ms   10,605
holder           92.1%            278 ms   118 ms    18.0 ms   12,419
  • The holder brings the prefix hit rate back to what the default 2.9M-token cache gets without it (92.8%). Step time is not compared: these steps mostly wait on tool calls.
  • At the knee, this PR gets more prefix hits than no holder (1.64M vs 1.56M tokens) and never preempts. main's holder gets the most hits but preempts, so it is the slowest.
  • Numerics: not compared. The holder changes which cached blocks vLLM may evict, not sampling or weights. A prefix hit isn't bitwise equal to a recompute outside batch-invariant mode, and batch-invariant configs turn the holder off.

NOTE:

  • kv_cache_usage now reads higher on every run that isn't batch-invariant: held blocks count as used.
  • At very high concurrency, the free-block floor (16 blocks plus 4 per running request on Qwen3.5-4B) can exceed the pool. Then the holder releases every hold each step and acts like no holder, plus its per-step CPU cost (20 us at 256 running requests, 84 us at 1024, fake scheduler). Single-turn at moderate pressure, where holds survive through decode, is not measured.
  • CI runs the holder for the first time on GPT-OSS (sliding window), DeepSeek V3 (MLA), several generators and generator DP=2. GPU-checked here only on Qwen3.5 (4B above; debug model with generator TP2).

You may ask:

  • Why not turn the holder off automatically when reset-KV is on? That's a silent fallback. An explicit None in the 7 configs keeps the rule visible.
  • Why not release every hold before reset_prefix_cache, so reset-KV runs keep the holder? It's new engine behavior that needs its own bitwise check.
  • Why one PR? The eviction change and the default only make sense together: without it, the default ships the slow policy.

Test plan

  • pytest tests/rl/unit_tests/cpu: 565 passed, 8 skipped.
  • test_evict_until_free_releases_a_session_with_a_running_request_last fails on main. test_session_releases_after_close_are_dropped fails without the close check. test_default_session_kv_holder_rejects_kv_cache_reset_on_model_state_dict_load builds VLLMEngine.Config() and fails if the default goes back to None.
  • GPU: the A/B above, one process per row, at the third commit (before the routing_session_id typing and the close check, which are CPU-tested). Before the eviction change was folded in: rl_grpo_qwen3_5_debug_varlen with generator TP 2 on 4 GPUs, holder on by default, 5 steps, no errors.
  • pre-commit, including pyrefly: clean.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 6, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 6, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@claude

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 3m 1s —— View job


Request changes: turning the holder on by default ships the eviction policy that #5477 measured as slower than no holder under KV pressure, and there's no holder-on result yet. See the review.

@claude claude Bot 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.

Verdict: Request changes -- this turns on, for every vLLM generator, an eviction policy that open PR #5477 measured as slower than no holder under KV pressure, and there is still no holder-on vs holder-off result.

What this PR does. VLLMEngine.Config.session_kv_holder now defaults to VLLMSessionKVHolder.Config() instead of None. The holder can't run with reset_kv_cache_on_model_state_dict_load=True, so the 7 batch-invariant alphabet_sort configs now set session_kv_holder=None. Four error messages now say how to turn the holder off. The config edits are mechanical, and I checked that no other in-repo config sets reset-KV.

Example.

Multi-turn recipe, KV pool too small for all sessions, no session_kv_holder override
before: holder off. Between turns, a session's blocks sit in vLLM's free queue
        and other requests can take them.
after:  holder on. Idle sessions keep their blocks. When the pool runs short,
        _evict_until_free releases only sessions with no running request.
        Running sessions' GDN state blocks stay pinned, and vLLM preempts
        running requests instead (#5477: 187 vs 49 preemptions, 15% slower).
Batch-invariant recipe: must now also set session_kv_holder=None, or the
        engine build raises.

Must fix

  1. PR description: the "Summary (human-written)" section is empty. Also, the only measured result is holder-off in both arms (92.8% vs 79.0% hit rate with different KV budgets), and "holder on" is pending. That shows a smaller cache loses hits. It doesn't show the holder wins them back, or that it wins on throughput. This PR changes the performance and memory of the main RL generator path, so it needs the on/off throughput number before it lands.
  2. torchtitan/rl/generator/vllm/engine.py:112 -- the default ships the eviction policy that #5477 measured at 9-15% slower than no holder under KV pressure. Land #5477 first (or fold it in), then measure (inline comment).

Should consider

  • torchtitan/rl/rollout/types.py:98: GenerateFn still documents routing_session_id=None as "no affinity", and controller.py:553 and actors/monarch/router.py:41 pass None through. Meanwhile EngineRequest.routing_session_id and Generator.generate are typed str. With the holder on by default, every None request shares one holder key. Each one's prefill drops the previous hold, so those requests get no protection. A group that mixes None and string sessions also makes sorted(released) in VLLMSessionKVHolder.release raise TypeError inside the engine loop. No in-repo caller passes None, so the smallest fix is to make routing_session_id: str required along the GenerateFn -> router path. That removes the case instead of handling it.
Details
  • Gate: the problem is real (between-turn blocks can be taken), and the layer is right (vLLM engine config). The default, though, depends on #5477's eviction change, which isn't on main yet: session_kv_holder.py:153 still skips running sessions.
  • Golden numerics: the only RL loss golden (rl_grpo_cuda.txt, rl_grpo_qwen3_0_6b_varlen_batch_invariant) runs batch-invariant with the holder now explicitly off, so it is unaffected. Non-batch-invariant runs will see different prefix hits, so their numerics differ from before. There is no golden for those, which is expected.
  • generator.py:200: the vLLM hint in the generic batch-invariant error is fine. Generator already defaults to VLLMEngine.Config.

Not verified: holder behavior on GPT-OSS (sliding window), DeepSeek V3 (MLA), and generator DP=2. The RL CI (ciflow/rl) will exercise these first.

Comment on lines +112 to +114
session_kv_holder: VLLMSessionKVHolder.Config | None = field(
default_factory=VLLMSessionKVHolder.Config
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This makes the current eviction policy the default, and that policy has a measured regression. On main, VLLMSessionKVHolder._evict_until_free (session_kv_holder.py:153) never releases the hold of a session whose request is running. Your open #5477 measured the cost: when a multi-turn run outgrows GPU KV, the holder runs 9-15% slower than no holder (233.7 s vs 204.1 s, 187 vs 49 preemptions at 310 blocks). The cause is that the GDN prompt-end state blocks stay pinned and vLLM preempts running requests instead.

With this default, every multi-turn recipe that hits KV pressure (Terminal-Bench at gpu_memory_limit=0.33 is exactly that case) gets the slow path. Please land #5477 first, or fold it in. Then flip the default with a holder-on vs holder-off comparison of throughput, not only prefix hit rate, on that policy.

Felipe Mello added 4 commits November 6, 2026 08:41
Under memory pressure _evict_until_free released idle sessions and skipped
sessions whose request runs. Once that request decodes, the hold alone keeps
its prompt-end GDN state (and possibly a duplicate block), so under heavy
pressure those pinned blocks made vLLM preempt running requests instead.

Release sessions with no running request first, as before, then running
sessions' holds, oldest hold first, until the floor is met.

1 H100, Qwen3.5-4B-Base TP1, multi-turn A/B (main vs this, interleaved):
310 blocks 233.7 -> 210.1 s (-10.1%), 372 blocks -3.4%, 434 blocks -0.3%.
VLLMEngine.Config.session_kv_holder now defaults to VLLMSessionKVHolder.Config().
Configs with reset_kv_cache_on_model_state_dict_load=True (the batch-invariant
alphabet_sort recipes) turn it off: the engine can't run the holder with them.
With the session KV holder on by default, a None key would put unrelated
requests under one holder key. No caller passes None, so make the field a
required str from GenerateFn to the inter-generator router.
@felipemello1
felipemello1 force-pushed the felipemello1/session-kv-holder-default-on branch from 7ea6075 to cd137ad Compare November 6, 2026 16:45
With the session KV holder on by default, a rollout that ends during
shutdown or after a generator crash released its session into a closed
queue and raised. Nothing is held then, so drop the release.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: addressed the last review. #5477's eviction change is folded in, routing_session_id is a required str on the generate path, releases after the engine loop closes are dropped, and the body has GB300 holder on/off numbers (multi-turn and single-turn). The human Summary is still empty: Felipe writes it.

@claude review

@claude

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 51s —— View job


Approve (once the human-written Summary is filled in; a maintainer still needs to review). See the review.

@claude claude Bot 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.

Verdict: Approve -- please address the items below before merging. Both earlier blockers are resolved: #5477's eviction change is folded in, and the body now has holder on/off throughput. A maintainer still needs to review, because this changes the default RL generator path.

What this PR does. It turns the vLLM session KV holder on by default. Under memory pressure, _evict_until_free now also releases running sessions' holds, after idle ones and oldest first. Before, it skipped them. Batch-invariant/reset-KV configs turn the holder off explicitly. routing_session_id is now a required str from GenerateFn to the router. Late session releases after the queue closes are dropped. The config and recipe edits are mechanical.

Example.

Multi-turn run, KV pool at the knee (358 blocks), no holder override
main (holder off):        between turns, a session's blocks can be taken by other requests -> 177.3 s
main's holder (opt-in):   running sessions' GDN holds stay pinned -> 28 preemptions, 185.5 s
this PR (default):        idle holds go first, then running ones -> 0 preemptions, 167.9 s
Batch-invariant recipe:   must set session_kv_holder=None, or the engine build raises

Earlier review

  • Holder-on numbers missing: resolved (multi-turn and single-turn A/B in the body).
  • engine.py:112 default ships the slow eviction policy: resolved. session_kv_holder.py:155 now releases running sessions last.
  • routing_session_id=None sharing one hold / sorted() TypeError: resolved. The type is str along types.py:98 -> controller.py:553 -> inter_generator.py:276 -> router.py:41. IntraGeneratorRouter.reserve keeps str | None, but it isn't on the holder path.

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author has to write it before merge.

Should consider

  • torchtitan/rl/generator/engine_loop.py:223 -- check-then-put race with the crash-path close (inline comment).
  • #5477 is still open, and this PR now contains its change. Close it (or mark it superseded) so the change doesn't land twice or conflict.

Questions

  • Single-turn with 300-token prompts is +6.2% (167.5 vs 177.9 s). That is above the ~5% the body calls a tie, and the holder holds nothing there. The per-step CPU cost (~20 us at 256 running) doesn't account for ~10 s. Most in-repo recipes are single-turn, so this is the default path's common case. Is this noise (a rerun would tell), or is there a cost we can't see?
Details
  • Eviction: a released running session keeps held=True in _live, so the same request doesn't re-hold every step. The next turn's request holds again at its prefill. The new test covers the 3 GDN state blocks freed, and the request's own references after release.
  • The no-running/waiting-head branch (after_step, _held order) only fires with an empty running, so the new order doesn't affect it.
  • Golden numerics: the only RL loss golden runs batch-invariant with the holder now off, so it is unchanged. Non-batch-invariant runs see different prefix hits, as the body says.
  • Fakes in test_verifiers.py:543,659 still default routing_session_id=None. They are harmless test doubles, and making them match the new signature is optional.

Not verified: holder behavior on GPT-OSS (sliding window), DeepSeek V3 (MLA), and generator DP=2. ciflow/rl runs these for the first time.

Comment thread torchtitan/rl/generator/engine_loop.py Outdated
Comment on lines 222 to 230
# Nothing is held once the queue closes (shutdown or a crash): drop late releases.
if self._holds_session_kv and self._rank == 0 and not self._queue.closed:
self._queue.put(SessionReleaseMessage(group_ids=group_ids))

def release_sessions(self, session_ids: list[str]) -> None:
"""RANK 0: release the held KV of sessions whose rollout ended (a no-op unless the
engine holds session KV)."""
if self._holds_session_kv and self._rank == 0:
if self._holds_session_kv and self._rank == 0 and not self._queue.closed:
self._queue.put(SessionReleaseMessage(session_ids=session_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.

The crash case still races. release_sessions/release_groups run on the actor's thread, and the crash path closes the queue from the engine loop thread (self._queue.close(CloseMessage(), reason="engine loop crashed") at line 399). If the close lands between not self._queue.closed and put, put raises RuntimeError("engine loop crashed") under its lock. That is the same error this check is meant to drop. The window is small, but it is exactly the crash case the comment names.

Smallest fix: do the check under the queue's lock. For example, add EngineLoopQueue.put_unless_closed(message) -> None, which holds self._lock and returns early when closed (about 5 lines), and call it from both release methods instead of closed + put.

Checking closed before put left a window where a crash-path close landed in
between and put raised. put(drop_if_closed=True) checks under the lock.
@felipemello1
felipemello1 force-pushed the felipemello1/session-kv-holder-default-on branch from ccd1d80 to 2ba7ac1 Compare November 6, 2026 17:24
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude:

  • Race: fixed. EngineLoopQueue.put(..., drop_if_closed=True) checks closed under the queue's lock, and both release methods use it.
  • Single-turn +6.2% (300-token prompts): I read it as noise, not a hidden cost. The two adjacent pairs disagree (-1.1% and +14.2%), and the holder held nothing: 768 releases per cell freed 0 blocks. The GPUs on that box are busy now; I'll rerun that shape with more interleaved cells when they free up and post the numbers.
  • Added an at-scale result to the body: Qwen3.5-27B on Terminal-Bench, 12 generators, 574K-token KV cache per engine. The prefix hit rate goes from 79.0% to 92.1% with the holder on, and TTFT from 435 to 278 ms.
  • The earlier PR with the eviction change: Felipe decides whether to close it.

@claude review

@claude

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 45s —— View job


Approve (once the human-written Summary is filled in; a maintainer still needs to review). See the review.

@claude claude Bot 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.

Verdict: Approve -- please address the items below before merging. The race from the last review is fixed and the new commit adds no new problems. A maintainer still needs to review, because this changes the default RL generator path.

What changed since the last review. One commit (2ba7ac1). EngineLoopQueue.put takes a new drop_if_closed argument and checks _closed_reason under self._lock. close takes the same lock (engine_loop.py:657), so a close can't land between the check and the enqueue. Both release methods call put(..., drop_if_closed=True).

Example.

The actor thread calls release_sessions(["s0"]) while the engine loop thread crashes and calls close().
before (d8d35c9): checks closed=False -> close() runs -> put raises "engine loop crashed"
after  (2ba7ac1): put takes the lock -> either enqueues before close, or sees closed and returns

Earlier review

  • Check-then-put race in release_sessions/release_groups: resolved (engine_loop.py:643-650).
  • Single-turn +6.2% at 300-token prompts: the author reads it as noise. The two adjacent pairs disagree (-1.1% and +14.2%), and the holder freed 0 blocks across 768 releases. That is plausible. A rerun with more interleaved cells is promised, and it would settle the question.
  • #5477, which this PR now contains: left to Felipe.

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author has to write it before merge.
Details
  • put's other callers keep the default drop_if_closed=False, so requests sent after close still raise. Only releases are dropped, and that's right: nothing is held once the loop closes.
  • test_session_releases_after_close_are_dropped closes first and then releases. It guards the close-then-release ordering, not the interleaving, which is enough for a lock-protected check.
  • The at-scale Terminal-Bench numbers (hit rate 79.0% -> 92.1%, TTFT 435 -> 278 ms) come from two jobs started about 3 h apart, using main's eviction policy and no preemptions. They support the hit-rate claim. The throughput claim rests on the GB300 A/B.

Not verified: holder behavior on GPT-OSS (sliding window), DeepSeek V3 (MLA), and generator DP=2. ciflow/rl runs these for the first time.

"""Optional logger instantiated on TP rank 0 to export vLLM metrics."""

session_kv_holder: VLLMSessionKVHolder.Config | None = None
session_kv_holder: VLLMSessionKVHolder.Config | None = field(

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 wonder if we expect people to swap this config to do something customized. If not, maybe a flag disable_session_kv_holder is easier to read / use.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: superseded by #5919, which deletes the session KV holder and evicts an ended rollout's KV from vLLM's prefix cache instead. Closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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