Repository navigation
[rl] offload idle session KV to CPU (6/6) - #5299
felipemello1 wants to merge 56 commits into
Conversation
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.
- 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.
- 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.
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.
| engine_kwargs.update(extra_vllm_engine_args) | ||
|
|
||
|
|
||
| def _enable_multi_worker_kv_offload(engine: Any) -> None: |
There was a problem hiding this comment.
this is too complicated -- at least encapsulate it nicely in a Configurable (that no one needs to look at)
There was a problem hiding this comment.
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 itattachholds the TP/DP lockstep code, unchanged.evict_firstholds the CPU LRU reordering; the session holder calls it when a session ends.engine_kwargsnames vLLM'sOffloadingConnectorinstead of settingkv_offloading_size. As a result, vLLM's own check now rejects router replay with offload, in-process too.- Deleted: the
/dev/shmhost check and its launcher argument, andeviction_policy="lru"(vLLM's default).
This PR's generator.py diff went from +189/-18 to +34/-7.
# 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.
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.
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.
…e test timeout (6/6)
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.
|
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):
Parking this for now; the 35B run will not use CPU offload. |
|
@claude review |
There was a problem hiding this comment.
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
- 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. 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.controller.py:628-634-- Monarch-onlybuild(generator_env=...)branch plusgetattron the vLLM engine config in the controller. Launcher-built actor systems get no env. Passgenerator_envthroughActorSystem.provisioninstead (inline).
Should consider
session_kv_holder.py:78--hold_gpu_blocksis a mode bool with no setting rule. Delete it (inline).cpu_kv_offload.py:106-109-- thenum_workersoverride 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_sizesandtest_hold_gpu_blocks_off_needs_cpu_kv_offloadonly 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_offloadshould be a field of session_kv_holder's config" is addressed byVLLMSessionKVHolder.Config.cpu_kv_offload. - Size of the TP=1-only alternative:
attachkeeps the LRU lookup and thenum_groupsread, plus oneValueErrorfor TP > 1. That deletes the request-id counter, theupdate_from_outputwrapper, the fingerprint check, thePYTHONHASHSEEDlaunch env, and thesys.flagscheck. TP=1 is the configuration of the headline 8k and 32k results. release()now leaves_session_groupsand_group_sessionsin place when a session is dropped for room (they used to be cleared in_release). Without offload, behavior is unchanged: the next_holdorreleaseupdates the same entries.- I checked
generator_launch_envagainstapply_env_defaults: both allocator vars are already set in the controller process, so the""fallback only matters for launchers that skiptrain.py/generate.py. - The per-step
all_gather_objectruns 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.
| 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 |
There was a problem hiding this comment.
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.
| 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() | ||
| ) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
| tp_group = get_tp_group() | ||
| connector_scheduler.config = connector_scheduler.config._replace( | ||
| num_workers=tp_group.world_size | ||
| ) |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
|
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. |
…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).
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 pinssize_gibonce per DP rank.Problem
expandable_segments:True, whichRL_ENV_DEFAULTSsets for every RL process;Solution
Configurable,CPUKVOffload(torchtitan/rl/generator/vllm/cpu_kv_offload.py), holds everything offload-specific. The holder owns it:expandable_segments:False(other allocator options kept) andPYTHONHASHSEED=0when offload is on. Trainers are unchanged.KVOutputAggregator. The TP ranks' schedulers must stay identical: request ids get a counter suffix instead of vLLM's random one, procs sharePYTHONHASHSEED=0, and each gather raises if the scheduler fingerprints differ. Each scheduler waits for its own TP group only, not DP x TP.hold_gpu_blocks=Falsegives offload without the GPU hold.session_kv_holderstill rejectsreset_kv_cache_on_model_state_dict_load=True(whichbatch_invariantneeds): vLLM can't reset the prefix cache while a request waits on a CPU load either.VLLMEnginerejectscpu_kv_offloadwithdata_parallel_degree > 1when it is built: vLLM gives each DP rank its ownsize_gibregion, so DP=2 pins 2 xsize_gib, and half of it is never written (Results).Results
These were measured before the
CPUKVOffloadrefactor, which moved the code without changing it. Rerun after it (TP=1, 1 H100 each):Why Solution step 6 rejects DP > 1:
You may ask:
kv_offloading_size? vLLM's in-process config check then sees it and rejects router replay with offload (ValueError). Throughkv_offloading_sizeit was accepted, and CPU-restored rows replayed the wrong experts (vLLM 1.0.0.dev20261011, Qwen3-30B-A3B).PYTHONHASHSEED=0? Without it, the two ranks held the same CPU chunks in a different eviction order, so later evictions could differ.engine_idper 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. Dividingsize_gibby DP fixes the RAM total, but still leaves half of each region unused at DP=2.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:
expandable_segments:Falsemay 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).CPUKVOffload; rerun the TP=2 two-turn replay after each vLLM bump:connector_scheduler.manager._policy.evictable_chunks(attachraises if the policy is notLRUCachePolicy);num_workersand_job_counter;InputProcessor.assign_request_idandScheduler.update_from_output(both replaced).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).test_cpu_kv_offload.py:CPUKVOffload.attachwith 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), thesize_gib,PYTHONHASHSEED,assign_request_idand LRU-policy checks.test_session_kv_holder.py: evict-first order on vLLM's realCPUOffloadingManager, the stall release during a CPU load,hold_gpu_blocks=Falsewithout offload raises.test_generator.py: the engine kwargs nameOffloadingConnector;cpu_kv_offloadwithdata_parallel_degree=2raises (fails without the check).test_shutdown.py: the launch env (generator_launch_envdirectly; no CPU test covers the controller passing it asgenerator_env).VLLMGeneratorthroughgenerate()and the router'srelease_session(scripts not checked in).