Skip to content

[rl] offload idle session KV to CPU (6/6) - #5299

Closed
felipemello1 wants to merge 56 commits into
mainfrom
felipemello1/session-kv/6-offload-session-kv
Closed

felipemello1 wants to merge 56 commits into
mainfrom
felipemello1/session-kv/6-offload-session-kv

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

not a priority

TLDR: opt-in VLLMSessionKVHolder.Config(cpu_kv_offload=CPUKVOffload.Config(size_gib=16)) turns on vLLM's native CPU KV offload. A multi-turn session whose history left the GPU reloads it instead of recomputing it: 23-26 ms vs 196 ms for an 8k history (Qwen3.5-4B-Base, 1 H100). Ended sessions are evicted first, so a 16 GiB tier keeps a live 32k session that plain LRU loses (40 ms vs 883 ms). Tokens and logprobs are bitwise equal to a run without eviction. Works with TP; DP > 1 is rejected for now: vLLM pins size_gib once per DP rank.

Problem

  1. A multi-turn rollout re-sends its whole history every turn. vLLM skips recomputing it only while it is still in the GPU prefix cache.
  2. Between turns (env step, tool call), other requests evict it. The session KV holder protects it, but when memory runs short it drops whole idle sessions, which then recompute.
  3. Recompute grows with the history: 196 ms of time to first token (TTFT) for 8k tokens, 882 ms for 32k.
  4. vLLM's native CPU offload would fix this, but here:
    • it refuses to start under expandable_segments:True, which RL_ENV_DEFAULTS sets for every RL process;
    • by default it stores prompt blocks only, so the previous turn's completion is never stored;
    • its LRU fills the CPU tier with finished rollouts, which push out live sessions;
    • with more than one GPU per generator it hangs: each rank runs its own scheduler, which waits for every worker to finish a transfer but sees only its own worker's.

Solution

  1. A new Configurable, CPUKVOffload (torchtitan/rl/generator/vllm/cpu_kv_offload.py), holds everything offload-specific. The holder owns it:
holder = config.session_kv_holder.build()
engine_kwargs.update(holder.engine_kwargs())  # vLLM's OffloadingConnector, offload_prompt_only=False
engine = LLMEngine.from_engine_args(EngineArgs(**engine_kwargs))
holder.attach(engine)                         # CPUKVOffload.attach: the TP fixes in step 4
holder.release(session_ids=[...])             # CPUKVOffload.evict_first: ended sessions' chunks go first
  1. The controller's default actor system launches generator procs with expandable_segments:False (other allocator options kept) and PYTHONHASHSEED=0 when offload is on. Trainers are unchanged.
  2. Evicted first: the ended sessions' chunks that no live session uses (GRPO siblings share their prompt). A session the holder drops from GPU for room keeps its CPU place: that copy is what it reloads. The stall release ignores requests loading from CPU: they wait for the load, not for blocks.
  3. With TP > 1, every engine step all-gathers the TP ranks' finished transfers and merges them with vLLM's KVOutputAggregator. The TP ranks' schedulers must stay identical: request ids get a counter suffix instead of vLLM's random one, procs share PYTHONHASHSEED=0, and each gather raises if the scheduler fingerprints differ. Each scheduler waits for its own TP group only, not DP x TP.
  4. Off by default; hold_gpu_blocks=False gives offload without the GPU hold. session_kv_holder still rejects reset_kv_cache_on_model_state_dict_load=True (which batch_invariant needs): vLLM can't reset the prefix cache while a request waits on a CPU load either.
  5. VLLMEngine rejects cpu_kv_offload with data_parallel_degree > 1 when it is built: vLLM gives each DP rank its own size_gib region, so DP=2 pins 2 x size_gib, and half of it is never written (Results).

Results

Qwen3.5-4B-Base, VLLMGenerator standalone, 1 H100, TP=1, FULL CUDA graphs, greedy.
4 sessions x 8k prompts -> churn of 2x the 124-block GPU pool -> turn 2 (7,920 reusable tokens):
  no eviction              7,920 cached   TTFT  16.4-16.6 ms
  offload off                  0 cached   TTFT 196-197 ms
  offload on (16 GiB)      7,920 cached   TTFT  22.9-25.9 ms
  offload on + hold        7,920 cached   TTFT  24.1-27.6 ms   (the free floor dropped all 4; reloaded from CPU)
  tokens and logprobs bitwise equal to no eviction; churn took 3.05 s with offload off, 3.07 s on

1 live 32k session, offload on, hold off, 16 GiB CPU tier, ~18 GB of churn stored after it,
each churn rollout released through InterGeneratorRouter:
  base branch (plain LRU)                       0 cached   TTFT 882 ms
  this PR, router releases not forwarded        0 cached   TTFT 883 ms
  this PR                                  32,736 cached   TTFT  40.5 ms   bitwise equal to no eviction (15.5 ms)

TP=2 (2 H100, 4B), 4 x 8k two-turn with churn, all bitwise equal to TP=2 no eviction:
  hold off                     7,920 cached x4   TTFT 22.4-24.3 ms
  hold on                      7,920 cached x4   TTFT 20.4-22.2 ms
  hold on + pull               7,920 cached x4   TTFT 18.8-21.7 ms   (pull between turns; same weights: load_state_dict patched to a no-op)
TP=2 churn loop, 16 sessions x 12 turns, 8 GiB tier:
  Qwen3.5-4B           1,787 steps in sync, 939 CPU hits, the same CPU eviction order on both ranks
  Qwen3-0.6B           4,339 steps in sync (attention-only, 16-token blocks)
  per-step all-gather  +0.5% wall time (prototype, offload off: 30.19 s without the gather, 30.33 s with it)
DP=2, Qwen3.5-35B-A3B-Base, EP=2 (vLLM's default all-to-all), CUDA graphs off, before DP > 1 was rejected:
  7,392 cached x4, bitwise equal to DP=2 no eviction; TTFT 1.1-1.2 s vs 2.1-2.5 s recomputed

These were measured before the CPUKVOffload refactor, which moved the code without changing it. Rerun after it (TP=1, 1 H100 each):

offload on + hold, 4 x 8k     7,920 cached x4   TTFT 23.9-26.1 ms   1.244 GB loaded, 10.89 GB stored (as before)
32k session via the router   32,736 cached      TTFT 44.0 ms

Why Solution step 6 rejects DP > 1:

Host RAM per generator, size_gib=4, Qwen3-0.6B, 2 H100, vLLM engine build only, every region pinned whole:
             regions      /dev/shm    slots written
TP=1 DP=2    2 x 4 GiB    +8.0 GiB    rank 0: slot 0 of region A; rank 1: slot 1 of region B
TP=2 DP=1    1 x 4 GiB    +4.0 GiB    rank 0: slot 0, rank 1: slot 1, same region

You may ask:

  • Why name the connector instead of setting kv_offloading_size? vLLM's in-process config check then sees it and rejects router replay with offload (ValueError). Through kv_offloading_size it was accepted, and CPU-restored rows replayed the wrong experts (vLLM 1.0.0.dev20261011, Qwen3-30B-A3B).
  • Why merge every step, not once per engine-loop decision? Per decision delays a reload by up to 16 steps (190-260 ms on the 4B), about an 8k recompute; per step costs +0.5%.
  • Why a counter suffix on request ids? vLLM reports finished loads by its internal id, whose random suffix differs per rank.
  • Why PYTHONHASHSEED=0? Without it, the two ranks held the same CPU chunks in a different eviction order, so later evictions could differ.
  • Why evict ended sessions first instead of not storing them? Often only the env knows after a turn that it was the last (chess: game over after the move).
  • Why reject DP > 1 instead of sharing one region? One engine_id per generator would let its DP ranks on one host share one region, but that relies on vLLM's private slot layout (slot = device index % world size); it is a TODO at the check. Dividing size_gib by DP fixes the RAM total, but still leaves half of each region unused at DP=2.
  • Why not enable_cumem_allocator=True? Our worker routes only weights through CuMem, so the KV cache would stay on expandable segments: it would only silence vLLM's check.

NOTE:

  • Untested: DeepEP (EP ran only with vLLM's default all-to-all), GB300 (reloads go over NVLink-C2C), Qwen3.5-35B-A3B under RL, RL throughput with offload under memory pressure.
  • expandable_segments:False may fragment CUDA graph pools and DeepEP buffers; unmeasured. Launchers that build their own actor system must set both env values (vLLM or our init check raises otherwise).
  • Private vLLM state, all inside CPUKVOffload; rerun the TP=2 two-turn replay after each vLLM bump:
    • connector_scheduler.manager._policy.evictable_chunks (attach raises if the policy is not LRUCachePolicy);
    • the connector's num_workers and _job_counter;
    • InputProcessor.assign_request_id and Scheduler.update_from_output (both replaced).
  • Weight sync: requests carry a per-version cache salt, so a new-version request can't hit old-version CPU chunks.
  • Gaps: a sibling whose first request hasn't reached the generator doesn't protect the shared prompt. TODOs in code: a chunk stored after its release keeps its LRU place; each release rebuilds the live hash set (0.6 ms for 250 Qwen3.5 sessions of 16k tokens, 23 ms with 16-token hash blocks).
  • CPU RAM is ~131 KB per token for Qwen3.5-4B; pinning 16 GiB added at most 5 s to init, 64 GiB 15-25 s (H100 host).

Test plan

  • pytest tests/rl/unit_tests/cpu: 477 passed, 9 skipped, in a venv without Verifiers (its 4 test modules and 2 recipe checks skip).
  • New:
    • test_cpu_kv_offload.py: CPUKVOffload.attach with a scripted TP all-gather (a load finishes once every TP rank did; an empty step still gathers; divergence raises; same request ids on every rank), the size_gib, PYTHONHASHSEED, assign_request_id and LRU-policy checks.
    • test_session_kv_holder.py: evict-first order on vLLM's real CPUOffloadingManager, the stall release during a CPU load, hold_gpu_blocks=False without offload raises.
    • test_generator.py: the engine kwargs name OffloadingConnector; cpu_kv_offload with data_parallel_degree=2 raises (fails without the check). test_shutdown.py: the launch env (generator_launch_env directly; no CPU test covers the controller passing it as generator_env).
  • GPU: the replays above drive VLLMGenerator through generate() and the router's release_session (scripts not checked in).

Felipe Mello added 5 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.
Opt-in VLLMGenerator.Config.session_kv_offload_gib turns on vLLM's native CPU KV
offload for multi-turn sessions: a turn whose history left the GPU reloads it
from CPU instead of recomputing it.

- Engine args: kv_offloading_size, the native backend, offload_prompt_only=False
  (the next turn's prompt holds this turn's completion), and
  DemotableLRUCachePolicy as the CPU eviction policy.
- SessionKVHolder.release (rollout end, group end) moves an ended session's CPU
  chunks to the eviction front, except chunks a live session still uses. The
  holder also runs without hold_session_kv.
- train.py launches generator procs with expandable_segments:False when it is
  set; vLLM refuses a KV connector under expandable_segments:True.
- tensor_parallel_degree > 1 raises: each TP rank's scheduler counts only its
  own rank's finished transfers, so they never complete.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 12, 2026
Felipe Mello added 2 commits October 11, 2026 19:22
- Rename session_kv_offload_gib to kv_offload_gib: it offloads every
  request's KV; only the eviction order is session-aware.
- Forward per-session releases to generators when offload is on, not only
  with hold_session_kv, so a rollout's chunks are evicted first when it ends.
- Weight sync with reset_kv_cache_on_weight_sync also clears the CPU tier
  (reset_connector=True), so no request reloads KV from old weights.
- Raise for any vLLM world size > 1 (TP, DP, PP, prefill CP), checked after
  the engine build; under external_launcher each worker hears only its own
  finished transfers. Raise for a negative size.
- Drop the policy subclass: vLLM's LRU, reordered in SessionKVHolder.release;
  check the policy type at init and import vLLM's offload code only with
  offload on.
- Keep the shared prompt of a sibling still before its first prefill in place.
- train.py flips only expandable_segments in generator procs and keeps the
  other allocator options.
- Hold-off mode skips the free floor and the "sessions held" log; moved hold
  checks raise ValueError.
Each generator rank runs its own vLLM scheduler with one worker, but vLLM's
offload marks a CPU load or store done only once every worker of its
scheduler finished it, and only vLLM's multiprocess executor merges the
workers' finished transfers. _enable_multi_worker_kv_offload replaces the
world_size > 1 raise:

- Each scheduler waits for its own TP group only (under external_launcher
  vLLM's world size also counts DP).
- With TP > 1, every engine step all-gathers the TP ranks' finished transfers
  before the scheduler reads them and merges them with vLLM's
  KVOutputAggregator, as its multiprocess executor does.
- The TP ranks' schedulers stay identical: request ids get a counter suffix
  instead of vLLM's random one, generator procs run with PYTHONHASHSEED=0
  (train.py sets it; checked at init), and each step's gather compares a
  scheduler fingerprint across ranks and raises if they differ.

Also raise for kv_offload_gib with reset_kv_cache_on_weight_sync: vLLM cannot
reset the prefix cache while a request waits on a CPU load.
@felipemello1
felipemello1 added this pull request to stack #5293 October 12, 2026 03:26
Felipe Mello added 8 commits October 11, 2026 21:03
- Raise if vLLM's InputProcessor has no assign_request_id to replace: with
  random ids the first TP reload would hang.
- The per-step fingerprint hashes the scheduled requests and their token
  counts, so ranks that schedule different requests with the same total are
  caught; drop the weaker total-token and request-count fields.
- Unpack the gather once; shorter reset-raise message; fold the empty-step test
  into the first merge test.
A pull's gc.collect() takes ~0.7 s in the full suite's heap; a host stall pushed two pull
tests past the 5 s bound once in ~31 full runs.
…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.
@felipemello1
felipemello1 marked this pull request as ready for review October 12, 2026 04:55
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 12, 2026
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.
Comment thread torchtitan/rl/generator.py Outdated
engine_kwargs.update(extra_vllm_engine_args)


def _enable_multi_worker_kv_offload(engine: Any) -> 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.

this is too complicated -- at least encapsulate it nicely in a Configurable (that no one needs to look at)

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: everything offload-specific is now in one Configurable, CPUKVOffload (torchtitan/rl/cpu_kv_offload.py). The generator only does this:

self._cpu_kv_offload = config.cpu_kv_offload.build()        # VLLMGenerator.Config.cpu_kv_offload
engine_kwargs.update(self._cpu_kv_offload.engine_kwargs())  # before the engine build
self._cpu_kv_offload.attach(self._engine)                   # after it
  • attach holds the TP/DP lockstep code, unchanged. evict_first holds the CPU LRU reordering; the session holder calls it when a session ends.
  • engine_kwargs names vLLM's OffloadingConnector instead of setting kv_offloading_size. As a result, vLLM's own check now rejects router replay with offload, in-process too.
  • Deleted: the /dev/shm host check and its launcher argument, and eviction_policy="lru" (vLLM's default).

This PR's generator.py diff went from +189/-18 to +34/-7.

Felipe Mello added 5 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
# Conflicts:
#	tests/rl/unit_tests/cpu/test_generator.py
#	tests/rl/unit_tests/cpu/test_shutdown.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.
Felipe Mello added 7 commits October 14, 2026 10:30
Review fix: VLLMGenerator.Config.cpu_kv_offload moves to
VLLMSessionKVHolder.Config.cpu_kv_offload, next to a new hold_gpu_blocks (default True).
- Offload alone used to build a holder behind the user's back (the holder knows when a session
  ends and which chunks a live session still uses). Now it is explicit:
  VLLMSessionKVHolder.Config(hold_gpu_blocks=False, cpu_kv_offload=...). hold_gpu_blocks=False
  without offload raises.
- The holder owns the offload, so it has two phases, like CPUKVOffload: build() before the engine
  (engine_kwargs() adds the offload connector's args), attach(engine) after it (reads the
  scheduler, runs the constructor checks, attaches the offload). The generator keeps one object.
- One reset_kv_cache_on_model_state_dict_load check for both.
- torchtitan/rl/cpu_kv_offload.py -> torchtitan/rl/generator/vllm/cpu_kv_offload.py.
Base automatically changed from felipemello1/session-kv/5-hold-session-kv to main October 15, 2026 01:03
Felipe Mello added 6 commits October 14, 2026 18:13
vLLM gives each DP rank its own host region of size_gib, and each rank
writes only its own slot of it, so DP=2 pins 2 x size_gib and half of it
is never written. VLLMGenerator.Config now raises for cpu_kv_offload with
data_parallel_degree > 1. A TODO names the fix (one engine_id per
generator) and why it isn't done now.
@felipemello1
felipemello1 marked this pull request as draft October 18, 2026 01:59
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 18, 2026
Felipe Mello added 3 commits October 17, 2026 19:18
Main moved the session-KV engine code into VLLMEngine and process launch into
the actor system. The offload's pieces move with them:
- VLLMEngine builds the holder before EngineArgs (adds its connector kwargs),
  attaches it after the engine is built, and owns the kv_offloading_size guard.
- Generator.Config rejects offload with data_parallel_degree > 1.
- generator_launch_env moves from train.py to the controller, which passes it
  to the default actor system as generator_env.
…y when set (6/6)

- The DP=1 offload check moves from Generator.Config into VLLMEngine.__init__,
  next to the holder's reset check, so the generic Generator.Config doesn't
  reach into a vLLM-only field. Its test becomes an engine build,
  parametrized with the reset test.
- The controller passes `generator_env` to the default actor system only when
  offload sets one: only MonarchActorSystem takes it.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Status note (2026-10-27), from trying to use this on a Qwen3.5-35B-A3B SWE run (3 generators, each DP8 x EP8 over 2 GB300 nodes):

  1. DP > 1 is rejected for host-RAM cost, not correctness. vLLM gives each DP rank its own size_gib region, so DP=8 pins 8 x size_gib per generator (4 regions per 4-GPU host), and only one slot of each region is written. The DP=2 35B-A3B replay in Results was bitwise equal to no eviction. Lifting the check means either sharing one region per host (relies on vLLM's private slot layout, the TODO at the check) or accepting the extra pinned RAM (e.g. 4 x 32 GiB = 128 GiB per host).
  2. Router replay is the real blocker for MoE RL. With the connector named, vLLM rejects enable_return_routed_experts; through kv_offloading_size it was accepted but CPU-restored rows replayed the wrong experts. Per-turn routed_experts_prompt_start skips restored rows for later turns of the same rollout, but not for turn 1 of GRPO siblings (shared prompt, start 0) or after a context compaction (shorter shared prefix). A fix needs the routed-expert rows offloaded with the KV, or restored blocks never used for returned rows.

Parking this for now; the 35B run will not use CPU offload.

@tianyu-l

tianyu-l commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 4m 34s —— View job


Request changes: nothing in the repo uses this yet, and the TP > 1 path patches vLLM scheduler methods with no upstream issue. 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 -- nothing in the repo uses this yet (the author parked it on 2026-10-27, and the target MoE run can't use it because of router replay), and the TP > 1 path patches two vLLM scheduler methods with no upstream issue.

What this PR does. It adds opt-in vLLM CPU KV offload under VLLMSessionKVHolder.Config.cpu_kv_offload. vLLM copies KV blocks, completions included, to pinned host RAM. A turn whose history left the GPU then reloads it from there instead of recomputing it. When a session ends, its CPU chunks move to the front of vLLM's LRU, except chunks a live session still uses. With TP > 1, every engine step all-gathers the TP ranks' finished transfers so the schedulers stay in lockstep. The controller launches generator procs with expandable_segments:False and PYTHONHASHSEED=0.

Example.

Qwen3.5-4B, 1 H100: session A (8k history) idles while churn fills the GPU pool
main:     A's turn 2 -> prefix gone from GPU -> recompute 8k  (TTFT ~196 ms)
this PR:  A's turn 2 -> prefix found in CPU tier -> reload    (TTFT ~24 ms)
group g ends -> holder.release(group_ids=[g]) -> g's CPU chunks evicted before A's

Must fix

  1. No current consumer. No recipe sets cpu_kv_offload. The description opens with "not a priority". The 2026-10-27 status note says the 35B SWE run won't use it, and that router replay (enable_return_routed_experts, which vLLM rejects with this connector) blocks MoE RL. This is 867 added lines, a dozen of them tied to private vLLM state that each vLLM bump can break, with no CI that runs it. Please name the run or recipe that will turn it on before landing, or keep it on the branch until router replay is solved.
  2. cpu_kv_offload.py:119-169 -- replaces vLLM methods and reads private state with no TODO or upstream issue (inline). Smallest alternative: support TP=1 only and raise for TP > 1.
  3. controller.py:628-634 -- Monarch-only build(generator_env=...) branch plus getattr on the vLLM engine config in the controller. Launcher-built actor systems get no env. Pass generator_env through ActorSystem.provision instead (inline).

Should consider

  • session_kv_holder.py:78 -- hold_gpu_blocks is a mode bool with no setting rule. Delete it (inline).
  • cpu_kv_offload.py:106-109 -- the num_workers override looks like a no-op now that DP > 1 is rejected (inline).
  • engine.py:147 -- the TODO about sharing one region across DP ranks has no vLLM issue link.
  • test_shutdown.py:186 -- the launch-env test is in the shutdown test file (inline).
  • test_cpu_kv_offload_rejects_non_positive_sizes and test_hold_gpu_blocks_off_needs_cpu_kv_offload only check one-line __post_init__ guards. Drop them unless they catch a real regression (rules/tests.md).
Details
  • Earlier maintainer comments (tianyu-l): "encapsulate in a Configurable" is addressed by CPUKVOffload. "cpu_offload should be a field of session_kv_holder's config" is addressed by VLLMSessionKVHolder.Config.cpu_kv_offload.
  • Size of the TP=1-only alternative: attach keeps the LRU lookup and the num_groups read, plus one ValueError for TP > 1. That deletes the request-id counter, the update_from_output wrapper, the fingerprint check, the PYTHONHASHSEED launch env, and the sys.flags check. TP=1 is the configuration of the headline 8k and 32k results.
  • release() now leaves _session_groups and _group_sessions in place when a session is dropped for room (they used to be cleared in _release). Without offload, behavior is unchanged: the next _hold or release updates the same entries.
  • I checked generator_launch_env against apply_env_defaults: both allocator vars are already set in the controller process, so the "" fallback only matters for launchers that skip train.py/generate.py.
  • The per-step all_gather_object runs on the TP CPU group. Both ranks raise together on a fingerprint mismatch, so a divergence can't hang one rank.

Not verified: vLLM's default offload num_workers at DP=1, and whether hold-on also keeps the 32k session. Both need vLLM source or a GPU run.

Comment on lines +119 to +169
request_counter = itertools.count()

def assign_request_id(request) -> None:
# Replaces vLLM's "<request_id>-<8 random chars>", which differs per rank.
request.external_req_id = request.request_id
request.request_id = f"{request.request_id}-{next(request_counter)}"

if not hasattr(engine.input_processor, "assign_request_id"):
raise RuntimeError(
"vLLM's InputProcessor has no assign_request_id to replace; update "
"CPUKVOffload.attach for this vLLM version"
)
engine.input_processor.assign_request_id = assign_request_id

aggregator = KVOutputAggregator(expected_finished_count=tp_group.world_size)
update_from_output = scheduler.update_from_output

def update_from_merged_output(scheduler_output, model_runner_output):
fingerprint = (
hash(tuple(scheduler_output.num_scheduled_tokens.items())),
connector_scheduler._job_counter,
)
gathered: list[Any] = [None] * tp_group.world_size
# Every rank gathers on every step, even with nothing finished, or the ranks deadlock.
dist.all_gather_object(
gathered,
(fingerprint, model_runner_output.kv_connector_output),
group=tp_group.cpu_group,
)
fingerprints, kv_connector_outputs = zip(*gathered)
if any(
rank_fingerprint != fingerprint for rank_fingerprint in fingerprints
):
raise RuntimeError(
"TP ranks' vLLM schedulers diverged; (scheduled requests hash, offload jobs) "
f"per rank: {fingerprints}"
)
# A copy per rank: aggregate() writes into its output_rank entry, and steps without work
# share vLLM's EMPTY_MODEL_RUNNER_OUTPUT.
merged = aggregator.aggregate(
[
replace(
model_runner_output, kv_connector_output=kv_connector_output
)
for kv_connector_output in kv_connector_outputs
],
output_rank=tp_group.rank_in_group,
)
return update_from_output(scheduler_output, merged)

scheduler.update_from_output = update_from_merged_output

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 block replaces two vLLM methods (InputProcessor.assign_request_id, Scheduler.update_from_output) and reads private state (_job_counter; _policy at L98), and none of it has a TODO linking an upstream issue. The gap is in vLLM: under external_launcher, nothing merges the TP workers' KVConnectorOutput across ranks. Because of this patch, generator procs also need PYTHONHASHSEED=0, request ids depend on admission order, and every vLLM bump needs a manual TP=2 replay, since nothing in CI runs this path.

Smallest fix: reject tensor_parallel_degree > 1 with a ValueError (same reasoning as the DP > 1 check in engine.py) and file the vLLM issue. That removes about 50 lines here, the PYTHONHASHSEED half of generator_launch_env, and 5 of the 7 tests in test_cpu_kv_offload.py. If TP > 1 has to stay, add # TODO(<vllm issue>) at each replaced method and at each private attribute.

Comment on lines +628 to +634
launch_env = generator_launch_env(config.generator)
# Only MonarchActorSystem takes `generator_env`, so pass it only when offload needs it.
actor_system = (
config.actor_system.build(generator_env=launch_env)
if launch_env
else config.actor_system.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.

The controller now knows two implementation details: that only MonarchActorSystem.__init__ takes generator_env, and (in generator_launch_env, via getattr) that only VLLMEngine.Config has a session_kv_holder. It also only covers the default path. A launcher that passes its own actor_system gets no env and fails at engine build (the description lists this as a NOTE).

Every actor system launches generator procs, so the env belongs in the ActorSystem.provision(...) interface: add generator_env: dict[str, str] next to generator_parallelism and call provision(..., generator_env=generator_launch_env(config.generator)) unconditionally. Then the branch here disappears, and launcher-built actor systems get the env too. generator_launch_env itself would sit better next to CPUKVOffload in the vLLM package.

self.free_floor_blocks = kv_cache_manager.watermark_blocks + sum(
cdiv(scheduler.max_num_scheduled_tokens, group.kv_cache_spec.block_size)
for group in kv_cache_manager.kv_cache_config.kv_cache_groups
hold_gpu_blocks: bool = True

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.

hold_gpu_blocks is a mode boolean, and it adds a __post_init__ check, four if self._hold_gpu_blocks branches (attach, after_step, _evict_until_free, log_stats) and a test. How would a user decide how to set it? In the description's own numbers the two modes are within noise, and hold is a little faster at TP=2 (20.4-22.2 ms vs 22.4-24.3 ms). The 32k win comes from evict-first. Hold on should get it too, because a free-floor drop keeps the session's CPU place (test_free_floor_release_keeps_the_cpu_chunks_of_a_live_session), but the 32k replay was only run with hold off (unverified). Unless a recipe needs hold off, delete the field: the holder always holds, and cpu_kv_offload is the only option.

Comment on lines +106 to +109
tp_group = get_tp_group()
connector_scheduler.config = connector_scheduler.config._replace(
num_workers=tp_group.world_size
)

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 num_workers override (docstring item 1) exists because vLLM counts DP x TP. VLLMEngine now rejects DP > 1, so at DP=1 it should set the value vLLM already uses. Your own test comments call the old value "DP=2 x TP=2" and "2 (DP=2)". If that holds (unverified against vLLM), delete the override, the docstring item, the num_workers assertions in the tests, and num_workers from the description's list of private state.

),
],
)
def test_kv_offload_generators_launch_without_expandable_segments(

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 tests generator_launch_env, which has nothing to do with shutdown. Move it to test_async_controller.py, or put it next to the function if it moves into the vLLM package as suggested on controller.py.

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

acisseJZhong added a commit that referenced this pull request Nov 25, 2026
…oad (#5847)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->
Supersedes #5299 to enable
vllm's
[SimpleCPUOffloadConnector](https://github.com/vllm-project/vllm/blob/main/vllm/distributed/kv_transfer/kv_connector/v1/simple_cpu_offload_connector.py)
to offload gpu kv cache to local cpu. This PR is local offload, and next
PR integrates distributed kv cache store.

test result 
TP=1 P2598856702
TP=2 P2599224885

## Why

Multi-turn RL rollouts resend a long shared prefix every turn. When the
GPU prefix cache runs out between turns, vLLM evicts that prefix and the
next turn recomputes it. vLLM's `SimpleCPUOffloadConnector` keeps
evicted KV in CPU DRAM, but Titan's external-launcher generator could
not use it: TP ranks run independent schedulers whose request IDs and KV
completions disagree, and nothing drained in-flight saves after
responses returned.

**Example.**
```python
config.generator.engine.kv_offload = SimpleCPUKVOffloadConfig(cpu_bytes_per_rank=40 << 30)
# Before: a turn whose prefix was evicted from GPU recomputes it.
# After:  it reloads the prefix from this worker's CPU cache.
```

## What changed

- **Config.** `VLLMEngine.Config.kv_offload: SimpleCPUKVOffloadConfig |
None` (`cpu_bytes_per_rank`, `lazy_offload`, default True: the mode
behind every gain below); the engine builds vLLM's `KVTransferConfig`
with Titan's connector subclass. Prefix caching must stay on.
- **TP/DP coordination** (`kv_offload_scheduler.py`, TP*DP > 1).
`KVOffloadScheduler` orders requests and block releases by a shared
Titan request ID, all-gathers KV completions within the TP group, and
feeds them one request at a time, in that order, to vLLM's
`_update_from_kv_xfer_finished`. `simple_cpu_offload_connector.py`
scopes the save quorum to one TP group.
- **Drain.** `has_unfinished_requests` also covers scheduler work and
queued saves, so the engine loop keeps stepping until transfers finish.
Idle DP replicas join EP forwards with dummy batches.
- **Weight updates.** Offloaded blocks use the GPU prefix cache's salt
(the group's `min_policy_version`). `hot_swap=True` is supported:
transfers only copy KV blocks, which a weight load does not touch. As on
the GPU path, cached blocks may hold KV from older weights within a
group. `reset_kv_cache_on_model_state_dict_load=True` is rejected (it
cannot free blocks held by in-flight saves).
- **Session release.** With `session_kv_holder`, a released session's
unused CPU blocks move to the front of the eviction queue after its
requests and saves finish; blocks of locally active sessions are
protected. Without it, the CPU cache is plain LRU.
- **`generate.py`** builds the recipe's engine through
`GenerationEngine` instead of driving vLLM's `LLMEngine` directly, so it
runs vLLM or SGLang, with or without KV offload.
- **Docs.** `SIMPLE_CPU_OFFLOAD.md`: what is saved, evicted and
reloaded. Capacity is per worker; generators and DP replicas have
separate caches.

First PR in the stack, based on `main`; #5727 adds Mooncake distributed
caching on the same API. Unlike #5299 (`OffloadingConnector`), this
keeps native vLLM request IDs and supports DP/EP.

## Alternatives considered

- Salting offloaded KV by the loaded weights: exact isolation, but loses
within-group reuse after every update and forces drained
(`hot_swap=False`) loads.
- Copying vLLM's `_update_from_kv_xfer_finished` with sorted loops:
already missed upstream bookkeeping (vllm#65319).

## User-facing changes

| Before | After |
| --- | --- |
| No KV offload |
`VLLMEngine.Config.kv_offload=SimpleCPUKVOffloadConfig(cpu_bytes_per_rank=...)`
|
| `kv_transfer_config` via `extra_engine_args` | Rejected; use
`kv_offload` |
| `generate.py` runs vLLM only, without KV offload | Runs the recipe's
engine (vLLM or SGLang), KV offload included |
| `session_kv_holder` holds GPU prefixes only | With offload, also sends
CPU eviction hints when sessions end |
| — | Requires `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False` (vLLM
rejects expandable segments with KV connectors) |

## Performance

**Agent RL, Terminal-Bench, Qwen3.5-27B** ([TP=1:
P2598856702](https://www.internalfb.com/intern/paste/P2598856702/),
[TP=2:
P2599224885](https://www.internalfb.com/intern/paste/P2599224885/); for
each TP the runs started together; mean over training steps 11-24; SE =
difference / standard error, |SE| >= 2 is significant).

| Setting | Value |
| --- | --- |
| Workload | Multi-turn agent rollouts with tool calls; 64K context; 64
rollouts/step, up to 512 in flight; sticky routing; `hot_swap=True` |
| Generators | 2 GB300 hosts, FULL CUDA graphs. TP=1: 8 engines,
`gpu_memory_limit=0.30` (450K GPU KV tokens/engine). TP=2: 4 engines,
`gpu_memory_limit=0.21` (854K tokens/engine) |
| CPU offload | `lazy_offload=True`, 40 GiB/rank (655K tokens/engine at
TP=1, 1.31M at TP=2); host memory peak 776 GiB (TP=1) and 398 GiB (TP=2)
of 845 GiB |

| Metric | TP=1 OFF | TP=1 ON | TP=2 OFF | TP=2 ON |
| --- | ---: | ---: | ---: | ---: |
| KV hit rate (GPU + CPU) | 8.2% | 68.3% (+60 pp) | 4.0% | 71.1% (+67
pp) |
| Cached tokens / request | 1,617 | 10,355 (6.4x, 12 SE) | 827 | 11,725
(14x, 12 SE) |
| Prefill (ms) | 1,076 | 398 (-63%, 7.8 SE) | 830 | 289 (-65%, 11 SE) |
| Inter-token latency (ms) | 48.0 | 30.2 (-37%, 8.3 SE) | 59.8 | 30.4
(-49%, 12 SE) |
| Preemptions / request | 0.141 | 0.030 (-78%, 3.8 SE) | 0.077 | 0.018
(-76%, 3.9 SE) |
| Time to first token (ms) | 5,130 | 4,128 (-20%, 0.9 SE, noise) |
12,357 | 3,970 (-68%, 2.8 SE) |
| Training step (s) | 598 | 440 (-26%, 1.1 SE, noise) | 640 | 408 (-36%,
1.6 SE, noise) |

Step time is mostly waiting for rollouts (tool execution) and varies ~3x
between steps, so it does not resolve the difference. Lazy mode matters:
with eager offload and a CPU tier smaller than the GPU cache (0.33 GPU
memory, 32 GiB), CPU served only 14% of GPU misses and speed changed
within noise.

**Generator microbenchmark** (one host, Qwen3-8B, 4 sessions x 4 turns,
8K-token prefix, 32 output tokens/turn, 80-block GPU cache forcing LRU
eviction, 4 GiB CPU/rank; 3 OFF/ON pairs):

| Metric | TP=2 OFF | TP=2 ON | TP=4 OFF | TP=4 ON |
| --- | ---: | ---: | ---: | ---: |
| Sessions/s | 0.837 | 1.350 (+61%) | 1.261 | 1.916 (+52%) |
| CPU-hit requests | 0/80 | 60/80 | 0/80 | 60/80 |
| Computed prefill tokens | 682,240 | 185,600 (-73%) | 682,240 | 185,600
(-73%) |
| Time to first token (ms) | 319.8 | 101.3 (-68%) | 196.1 | 65.2 (-67%)
|

With a GPU cache large enough to hold every prefix (512 blocks/rank), ON
was 1.8-1.9% slower (no CPU hits).

## Numerics

CPU reload matched native GPU prefix reuse exactly (tokens and logprobs,
80 requests per TP degree). Versus full recomputation, logprob
differences reached 0.123 (bf16 noise, same as GPU prefix caching). In
the agent RL runs, the trainer-vs-generator `logprob_diff/max` was
comparable to the baseline's (TP=1 per-step mean 1.76 vs 1.51, worst
step 4.0 vs 4.05; TP=2 per-step mean 1.45 vs 1.36).

## Testing

- `tests/rl/unit_tests/gpu/test_kv_offload.py` (8 H100):
`cpu-hybrid-tail` (TP=1), `cpu-tp2-session`, `cpu-hybrid-tail-tp2` (sync
scheduling), `cpu-tp2-dp2-ep4`. Covers CPU restoration vs. an uncached
reference, policy-version isolation, session release, and hot swap with
pending saves. TP=2/DP=2/EP=4 and hybrid TP=2 run in RL multi-GPU CI.
- 217 RL CPU unit tests in the touched files.
- `generate.py` (torchrun, TP=4, Qwen3-0.6B, greedy): vLLM, SGLang, and
vLLM with KV offload produce the same text as `generate.py` on `main`
(vLLM) and exit cleanly.

## Known issues / follow-ups

- `KVOffloadScheduler`, the SimpleCPU connector subclass and
`VLLMEngine` rely on private vLLM members; TODOs at each use link
[vllm-project/vllm#69786](vllm-project/vllm#69786).
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.

4 participants