Skip to content

[RL] Integrate vLLM's SimpleCPUOffloadConnector for local CPU KV offload - #5847

Merged
acisseJZhong merged 5 commits into
mainfrom
codex/simple-cpu-kv-offload
Nov 25, 2026
Merged

acisseJZhong merged 5 commits into
mainfrom
codex/simple-cpu-kv-offload

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Supersedes #5299 to enable vllm's SimpleCPUOffloadConnector 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.

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, TP=2: 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.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 5, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 5, 2026
@acisseJZhong
acisseJZhong added this pull request to stack #5848 November 5, 2026 05:18
@acisseJZhong
acisseJZhong force-pushed the codex/simple-cpu-kv-offload branch 2 times, most recently from dbfae47 to 671d862 Compare November 5, 2026 07:06
@acisseJZhong
acisseJZhong force-pushed the codex/simple-cpu-kv-offload branch from 671d862 to c45b4de Compare November 5, 2026 07:56
@acisseJZhong
acisseJZhong force-pushed the codex/simple-cpu-kv-offload branch 3 times, most recently from 593836c to 4d360d3 Compare November 5, 2026 09:27
@acisseJZhong
acisseJZhong removed this pull request from stack #5848 November 5, 2026 22:08
@acisseJZhong
acisseJZhong changed the base branch from codex/mooncake-store-kv-offload to main November 5, 2026 22:08
@acisseJZhong
acisseJZhong force-pushed the codex/simple-cpu-kv-offload branch from 4d360d3 to be8af5d Compare November 5, 2026 22:08
@acisseJZhong
acisseJZhong added this pull request to stack #5869 November 5, 2026 22:09
@acisseJZhong
acisseJZhong force-pushed the codex/simple-cpu-kv-offload branch 6 times, most recently from e8ccd2f to 9d7aa55 Compare November 6, 2026 00:50
@acisseJZhong acisseJZhong changed the title [do not review] [RL] Add SimpleCPUOffloadConnector [RL] Add vLLM SimpleCPUOffloadConnector Nov 6, 2026
@acisseJZhong acisseJZhong changed the title [RL] Add vLLM SimpleCPUOffloadConnector [RL] Integrate vLLM's SimpleCPUOffloadConnector for local CPU KV offload Nov 6, 2026
@acisseJZhong
acisseJZhong force-pushed the codex/simple-cpu-kv-offload branch from 9d7aa55 to 0255dc9 Compare November 6, 2026 03:46
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 5m 14s —— View job


Needs discussion — review posted: no throughput gain shown, overlaps with #5299, and it builds on a large private vLLM API surface.

@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: Needs discussion -- the PR adds about 900 lines of RL generator code built on many private vLLM APIs, and its own benchmark shows no throughput gain. Maintainers should decide whether torchtitan owns this now, and how it relates to #5299, before it is polished.

What this PR does. It wires vLLM's SimpleCPUOffloadConnector into VLLMEngine through a new kv_transfer_config field. When TP*DP > 1 it swaps in a subclassed vLLM Scheduler, which sorts by a shared request ID and all-gathers KV completions across TP ranks. Cache keys are salted with the loaded policy version. Session/group releases are now sent to every generator, and the GPU session holder turns them into CPU eviction hints.

Example.

# before: a multi-turn turn whose prefix was evicted from GPU recomputes it
# after:
config.generator.engine.kv_transfer_config = KVTransferConfig(
    kv_connector="SimpleCPUOffloadConnector", kv_role="kv_both",
    kv_connector_extra_config={"cpu_bytes_to_use_per_rank": 1 << 30})
# turn 2 misses the GPU cache and reloads its prefix from this worker's CPU tier
# (PR benchmark: -68.8% prefill tokens, +0.9% rollouts/s, within noise)

Must fix

  1. Description. "Summary (human-written)" is empty.
  2. Value and overlap (gate). The benchmark gets CPU hits only because GPU prefix lookup was artificially disabled. With normal lookup there were 0 hits out of 320, and throughput went -0.3%. The model is an 8-layer, hidden-256 debug model, where prefill is about 8% of latency, so it can't show a gain. #5299 (felipemello1) targets the same problem: it adds torchtitan/rl/generator/vllm/cpu_kv_offload.py and a session-holder integration, and reports 23 ms vs 196 ms TTFT at 8k history on Qwen3.5-4B. Please either benchmark on a workload like that (realistic model, long histories, natural GPU pressure, TP=2), or explain why this PR should land instead of #5299 or alongside it.
  3. engine.py:424 -- turning on offload changes the GPU cache salt from min_policy_version to the loaded version, so there are now two salting rules (inline).
  4. inter_generator.py:311 -- every session end now sends an RPC to every rank of every generator, on every run (inline).
  5. cpu_kv_offload.py:14, simple_cpu_offload.py:82 -- both TODOs link a closed, unrelated vLLM RFC, which covers a large private-API surface (inline).
  6. test_kv_offload.py:337 -- the only real-vLLM test is gated on an env var and never runs in CI. The recipe is unused too (inline).

Should consider

  • engine.py:105 -- a typed Titan config instead of the free-form KVTransferConfig (inline).
  • session_kv_holder.py:260 -- the Future machinery has no consumer in this PR. Leave release hints out until there is a measurement (inline).
  • engine.py:552 -- validate hot_swap=False in Controller.Config.__post_init__ (inline).
  • engine.py:477 -- three CPU collectives per step on the coordinated path, with no measurement (inline).
  • CPU tests: test_kv_offload_coordination.py and test_session_kv_offload.py mostly assert against SimpleNamespace copies of vLLM's private fields (_store_event_to_blocks, _pending_finished_stores, ...). test_unsupported_kv_connector_rejected_at_config_creation and test_kv_offload_does_not_silently_replace_custom_connector only re-read config. Keep the tests that guard real invariants, such as TP ordering of frees, and drop the rest.

Questions

  • Should this land at all before upstream vLLM exposes external-launcher KV coordination? If it should, is TP=1-only (raise for TP*DP > 1) enough as a first step? That would delete cpu_kv_offload.py (309 lines), its 466-line test, and the DP dummy-batch and all-reduce code in engine.py.
Details
  • Sizes. 2284 lines added, 84 deleted. About 900 are source (cpu_kv_offload.py 309, engine.py +151, session_kv_holder.py +119, simple_cpu_offload.py 87, the doc 95). About 1460 are tests, and 527 of those are in an opt-in GPU test.
  • Smallest alternative, about 250 lines of source. A typed offload config, TP=1-only, LRU eviction without release hints, a single salting rule, and one GPU test wired into existing RL CI.
  • Release fanout. _fanout uses h.actor.<method>.call, i.e. all ranks, not rank0_actor.call_one. release_groups already fans out to all generators, so a repinned session's old GPU hold is freed when its group ends even without this change.
  • expandable_segments. The doc requires turning it off for the whole RL job, which overrides RL_ENV_DEFAULTS (needed for DeepEP buffers and CUDA graph pools). Worth stating that tradeoff in SIMPLE_CPU_OFFLOAD.md.

Not verified: the private vLLM symbols against the pinned vLLM version (vLLM isn't importable in this checkout), the collective overhead at TP=2, and the GPU test results.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
continue
# A rollout group's minimum version can outlive a weight update.
# Cached KV must identify the weights that actually computed it.
prompt["cache_salt"] = str(self._loaded_policy_version)

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.

Turning on KV offload also changes the salting rule for the GPU prefix cache, not just the CPU tier. Without offload, a request is salted with its group's min_policy_version (see the reset_kv_cache_on_model_state_dict_load docstring in engine.py). With offload, it is salted with the version currently loaded. So in an off-policy multi-turn group that spans a weight load, the next turn's GPU prefix hit turns into a full recompute just because CPU offload is enabled.

The reason given in the comment ("Cached KV must identify the weights that actually computed it") applies just as much to the existing GPU path. Either that path has a bug, and the fix belongs in its own PR covering both paths, or offload should salt by request.min_policy_version like everything else. One salting rule, not two.

if pinned is not None:
await pinned.rank0_actor.release_sessions.call_one([routing_session_id])
# A repinned or non-sticky session can leave cached KV on several generators.
await self._fanout("release_sessions", [routing_session_id])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This puts a cost on the main path of every RL run, including runs with no offload and no session holder. _fanout calls h.actor.release_sessions.call(...) on every rank of every generator, once for every rollout that ends. Before this change it was a single rank0_actor.call_one to the pinned generator, or nothing at all for non-sticky routing. With 6 generators x TP=2, each session end now sends 12 actor RPCs, and all but one are no-ops (engine_loop.release_sessions returns early unless the rank is 0 and holds_session_kv is set). Also, since return_exceptions=False, one unhealthy generator now fails every rollout's release.

Handling the repin leak is also a separate fix to existing GPU-holder behavior (one concern per PR), and release_groups already fans out when the group ends. Smallest fix: keep the pinned call_one, and have the strategy remember the generators a session was pinned to and release only on those. Alternatively, skip the per-session release entirely when no generator holds_session_kv.

across ranks; each scheduler applies results using its own vLLM request IDs.

TODO(acisseJZhong): upstream external-launcher KV coordination to remove these
adapters: https://github.com/vllm-project/vllm/issues/11400

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.

vllm-project/vllm#11400 is "[RFC]: Fully SPMD Execution for Offline Inference", a 2024 RFC that is now closed. It is not about coordinating external-launcher KV connectors, and it is not about a hash-based eviction API. simple_cpu_offload.py:82 cites the same issue. Both TODOs need an open upstream issue that actually tracks what is missing. That matters here because of how much private vLLM surface this PR uses:

  • Scheduler._free_blocks, _select_waiting_queue_for_scheduling and _update_from_kv_xfer_finished are overridden.
  • scheduler_manager._expected_worker_count, _store_event_to_blocks, _abandoned_store_event_to_blocks, _pending_finished_stores, _store_event_counter and cached_block_hash_to_block._cache are accessed directly.
  • From LLMEngine: engine_core.engine_core.batch_queue and should_execute_dummy_batch.

Each one can break on a vLLM bump without any error.

async_scheduling,
prefix_match_unit,
):
test_flag = "RUN_CPU_OFFLOAD_TEST"

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 test only runs when RUN_CPU_OFFLOAD_TEST=1 is set. Nothing in .github/workflows/ sets it, and the new rl_grpo_qwen3_5_debug_varlen_cpu_offload recipe isn't referenced by any test or workflow. So the only real-vLLM coverage of this feature (527 lines) never runs in CI, and the CPU tests mock vLLM's private fields with SimpleNamespace, so they won't notice when vLLM changes. That also adds a new env var.

Pick one of these:

  1. Add one or two of the hardest parametrizations to integration_test_8gpu_rl.yaml or integration_test_rl_h100.yaml, e.g. TP=2 + DP=2 + EP with async scheduling, and drop the env-var gate.
  2. Delete the test and the recipe.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
cuda_graph: VLLMCudaGraphConfig = field(default_factory=VLLMCudaGraphConfig)
"""CUDA graph capture settings for the vLLM engine."""

kv_transfer_config: KVTransferConfig | None = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This exposes vLLM's free-form KVTransferConfig, but only one value is valid for each of kv_connector and kv_connector_module_path, and kv_role isn't validated at all (kv_producer gets through). Users write three boilerplate fields just to pass the byte count. A Titan-owned typed config, e.g. kv_offload: SimpleCPUKVOffload.Config | None with cpu_bytes_per_rank: int, would let the engine build the KVTransferConfig itself. That removes the connector-name check in __post_init__, the kv_connector_module_path check in __init__ (which is config-only validation and should sit in __post_init__ anyway), and the vllm.config import in the recipe. #5727 then becomes a sibling MooncakeKVOffload.Config, selected by config type (.claude/rules/config.md). #5299 already uses this shape (CPUKVOffload.Config(size_gib=...)).

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.

vllm native config shouldn't be exposed as torchtitan config directly

self._eviction_hashes.clear()
self._pending_saves.clear()
if released:
self._eviction = connector.release_session_cache(released, active_hashes)

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.

SimpleCPUOffloadConnector.release_session_cache is annotated -> None and never returns a Future, so in this PR self._eviction is always None. The Future tracking, the done()/result() branch and the _eviction term in has_pending_work exist only for #5727, and offload_connector: Any is a duck-typed protocol with one implementation. Please move that machinery to #5727.

Bigger picture: CPU release hints are tied to the GPU session_kv_holder, so there is no way to get one without the other. The PR's own benchmark says it "does not establish ... session-release performance". The smallest version of this PR would leave release hints out and rely on the connector's LRU. That deletes about 120 lines here, get_pending_save_ids/release_session_cache in simple_cpu_offload.py, test_session_kv_offload.py, and most of the additions to test_session_kv_holder.py. It can come back once a measurement shows LRU isn't enough. #5299 measured exactly that case: 40 ms vs 883 ms at 32k.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
has_requests = bool(active.item())
if has_requests:
raise RuntimeError(
"KV offload requires drained weight updates: set "

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.

hot_swap=False is a config contract, but here it is checked on the first weight load, partway through a training run, and it costs an extra world-group all-reduce on every load. Controller.Config can see both generator_router.hot_swap and generator.engine.kv_transfer_config, so raise a ValueError in its __post_init__ and delete this runtime check along with its collective.

has_work = self._has_unfinished_local_requests()
if self._coordinate_kv_offload:
work = torch.tensor(has_work, dtype=torch.int32)
dist.all_reduce(

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.

When TP*DP > 1, every engine step now runs:

  • this world-group all-reduce;
  • has_unfinished_requests_dp, a DP all-reduce, in step();
  • a pickled all_gather_object over the TP CPU group in KVOffloadScheduler.update_from_output.

That is three CPU collectives per decode step. The benchmark only covers TP=DP=1 ("no TP coordination cost is involved"), so the coordinated path, which is where most of the complexity is, has no throughput number. Please measure it, at least for the 8-GPU TP=2 recipe, OFF vs ON. Unverified whether the cost matters at realistic batch sizes.

@acisseJZhong
acisseJZhong force-pushed the codex/simple-cpu-kv-offload branch from 0255dc9 to 735e71d Compare November 6, 2026 05:05
@acisseJZhong
acisseJZhong marked this pull request as ready for review November 6, 2026 09:04
@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 3m 2s —— View job


Request changes: re-review posted. tianyu-l's comments are resolved, but the rewritten generate.py no longer tears down its process groups, and the private-API TODO in engine.py was deleted.

@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 -- 26b3946 resolves all of tianyu-l's comments. It also brings a teardown regression in the rewritten generate.py and deletes the private-API TODO in engine.py. The #5919 overlap still needs a maintainer call.

What changed since the last review (26b3946). VLLMEngine.Config.kv_offload: SimpleCPUKVOffloadConfig | None replaces vLLM's KVTransferConfig, and the engine builds the connector config. The files are renamed to kv_offload_scheduler.py and simple_cpu_offload_connector.py. generate.py now builds the recipe's engine through GenerationEngine, so it runs vLLM or SGLang, and KV offload works there too.

Example.

# before
VLLMEngine.Config(kv_transfer_config=KVTransferConfig(
    kv_connector="SimpleCPUOffloadConnector", kv_role="kv_both",
    kv_connector_extra_config={"cpu_bytes_to_use_per_rank": 1 << 30}))
# after: kv_connector, kv_role and module_path are no longer user-settable
VLLMEngine.Config(kv_offload=SimpleCPUKVOffloadConfig(cpu_bytes_per_rank=1 << 30))

Resolved (tianyu-l's review).

  • generate.py SGLang support and the vLLM-only error: the engine-type check and the offload raise are gone.
  • No native vLLM config, and the config owns its own __post_init__ (config.py:458-491). The connector, role and module-path checks are deleted rather than moved.
  • The file naming.
  • The offload/evict/reload policy is now a table in SIMPLE_CPU_OFFLOAD.md.
  • The stale value after a full burst is commented at engine_loop.py:387.
  • The has_unfinished_requests conditions are documented at engine.py:571.
  • The holder and between-turns questions were answered in replies.

Must fix

  1. torchtitan/rl/generate.py:152 -- engine.shutdown() no longer tears down the engine core and process groups. That is what the deleted _shutdown_engine was for (inline).
  2. torchtitan/rl/generator/vllm/engine.py:591 -- the private-API TODO for engine_core.engine_core/batch_queue/DP dummy batches was deleted, not linked (inline).
  3. Overlap with #5919 (still open). The CPU release hints still live in VLLMSessionKVHolder (session_kv_holder.py, simple_cpu_offload_connector.py:get_pending_save_ids/release_session_cache, test_session_kv_offload.py). #5919 is still open and deletes that holder, and the author's reply confirms a draft to remove it. A maintainer should pick the order. The smallest path is still to drop the hints here and rely on LRU.
  4. TODO links (still open). kv_offload_scheduler.py:12 and simple_cpu_offload_connector.py:39 still have no upstream issue link.
  5. SIMPLE_CPU_OFFLOAD.md:29 and config.py:467 (still open). The doc example and the default are both eager offload. The PR's own data shows no gain for eager; every headline number used lazy_offload=True. Either default lazy_offload=True, or say in the docstring and the doc when to pick each mode.

Should consider

  • engine.py:198 -- the reset_kv_cache_on_model_state_dict_load rejection still runs at engine build, on the generator actor. Generator.Config.__post_init__ can see both fields and would reject it at config time.
  • The description's Testing section doesn't say whether the rewritten generate.py was run, on vLLM or on SGLang. No CI job runs it.

A maintainer still needs to review: tianyu-l's CHANGES_REQUESTED is still pending, and the PR changes engine_loop.py and the shared GenerationEngine contract.

Not verified (no vLLM or GPU here): whether dist.destroy_process_group() alone is enough teardown for vLLM's engine core under torchrun.

Comment thread torchtitan/rl/generate.py
)
finally:
_shutdown_engine(engine)
engine.shutdown()

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 drops the teardown that _shutdown_engine did. VLLMEngine.shutdown() (engine.py:654) only closes the renderer. Its docstring says process teardown is left to Monarch's ProcMesh.stop(), and nothing like that runs under torchrun. SGLangEngine.shutdown() is a no-op for the same reason. The deleted helper existed because "leaving vLLM's NCCL process group alive lets the NCCL watchdog query CUDA events while the driver unloads at interpreter exit". So generate.py is back to tearing down with live NCCL groups. Your own GPU test makes the same point: after engine.shutdown() it still has to call engine._engine.engine_core.shutdown() and cleanup_dist_env_and_memory() itself (test_kv_offload.py).

This script owns its process, so the smallest engine-agnostic fix is to destroy the process groups here:

Suggested change
engine.shutdown()
engine.shutdown()
# Unlike RL, where Monarch's ProcMesh.stop() ends the process, this script
# owns it: destroy the process groups so the NCCL watchdog doesn't query CUDA
# events while the driver unloads at exit.
if dist.is_initialized():
dist.destroy_process_group()

(with import torch.distributed as dist). Unverified: whether this is enough for vLLM's engine core, or whether you also need cleanup_dist_env_and_memory() behind an isinstance(engine, VLLMEngine) check. A torchrun TP=2 run of generate.py would show which.

``external_launcher`` uses does not, so the engine loop would otherwise sleep
with pinned blocks and unsent hints until the next request.
"""
core = self._engine.engine_core.engine_core

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 new docstring replaced the only TODO covering the private vLLM surface here and in step() (engine.py:604-611): engine_core.engine_core, scheduler.has_requests(), batch_queue, has_unfinished_requests_dp, should_execute_dummy_batch and execute_dummy_batch. That TODO already lacked an upstream link (earlier must-fix). Now none of these call sites is marked at all, so a vLLM bump that renames any of them fails with no pointer to why. Keep the docstring and put the TODO back (CLAUDE.md principle 3), with an upstream issue link, e.g. one vLLM issue for "public pending-work query and DP dummy step for external_launcher".

@acisseJZhong
acisseJZhong force-pushed the codex/simple-cpu-kv-offload branch from 26b3946 to 17a6a47 Compare November 25, 2026 02:40
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 1m 31s —— View job


Request changes: re-review posted. Lazy offload is now the default, but the generate.py teardown regression is still there, and the private-API TODOs became plain comments without an upstream link.

@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 -- 02e96e7 fixes the eager-default item, but the generate.py teardown regression from the last review is still there. The private-API TODOs were rewritten as plain comments rather than linked to an upstream issue.

What changed since the last review (02e96e7).

  • Resolved: lazy default. SimpleCPUKVOffloadConfig.lazy_offload now defaults to True (config.py:214). SIMPLE_CPU_OFFLOAD.md:40 describes the default to match. The GPU test sets lazy_offload=False and gives the reason, so the doc example now matches the setup that was benchmarked.
  • Changed but not resolved: private-API markers. The three TODOs (kv_offload_scheduler.py:13-16, simple_cpu_offload_connector.py:38-40, engine.py:628-631) are now comments saying "Recheck them on a vLLM upgrade". The deleted one in engine.py is back in that form.

Example (the open teardown item).

torchrun --nproc_per_node=2 -m torchtitan.rl.generate --module ... --config <TP=2 vLLM recipe>
# main:  finally: renderer.shutdown(); engine_core.shutdown(); cleanup_dist_env_and_memory()
# HEAD:  finally: engine.shutdown()   # VLLMEngine.shutdown only closes the renderer (engine.py:695)
#        -> vLLM's NCCL groups are still alive at interpreter exit; that is the watchdog
#           problem the deleted _shutdown_engine docstring describes

Must fix

  1. torchtitan/rl/generate.py:155 -- teardown (still open). VLLMEngine.shutdown() leaves process teardown to Monarch's ProcMesh.stop(), and nothing like that runs under torchrun. The GPU test still has to call engine._engine.engine_core.shutdown() and cleanup_dist_env_and_memory() after engine.shutdown(). Smallest fix: if dist.is_initialized(): dist.destroy_process_group() after engine.shutdown(), with a comment saying this script owns its process. If that isn't enough for vLLM's engine core, also call cleanup_dist_env_and_memory() behind an isinstance(engine, VLLMEngine) check. The inline suggestion from the last review still applies.
  2. Private vLLM API without a TODO and upstream link (still open). CLAUDE.md principle 3: "If torchtitan ... calls a private upstream API, say so in a TODO with an upstream issue link." The new wording drops the TODO marker, so a grep for TODOs no longer finds these, and there is still no link. File one vLLM issue (external-launcher KV coordination: shared request IDs and TP completion aggregation, a TP-scoped save quorum, a public pending-work query, and a DP dummy step). Then turn the three comments back into TODO(acisseJZhong): <link>.
  3. Overlap with #5919 (still open, now a draft). The CPU release hints still live in VLLMSessionKVHolder, which #5919 deletes. The author confirmed it will be removed. A maintainer should decide whether the hints land here and move later, or are dropped here, leaving LRU only and about 350 lines fewer, then re-added on #5919's evictor.

Should consider (still open)

  • engine.py:234: the reset_kv_cache_on_model_state_dict_load rejection still runs when the engine is built on the generator actor. Generator.Config.__post_init__ sees both fields and could reject it at config time.
  • The description's Testing section still doesn't say whether the rewritten generate.py was run, on vLLM or SGLang, or with offload. No CI job runs it. That matters for item 1.

A maintainer still needs to review: tianyu-l's CHANGES_REQUESTED is still pending, and the PR changes engine_loop.py and the shared GenerationEngine.has_unfinished_requests contract.

Not verified (no vLLM or GPU here): whether dist.destroy_process_group() alone is enough teardown for vLLM's engine core under torchrun.

@felipemello1

Copy link
Copy Markdown
Contributor

Please consider adding metrics regarding transport time if we dont have it yet. It would be interesting to monitor how long it takes to load/offload and how long this is exposed. We could also leave a #TODO to "predict" when to warm up the cache back into GPU, to avoid exposed time.

FYI, vllms native offloading has metrics for it: TransferStats.transfer_time, offloading/common.py:15-39

Context: I am seeing slow down in some settings, and I don't understand why. My hypothesis is that the offloading may be the culprit, but i dont have the visibility.

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

Comment posted by an AI agent on behalf of @acisseJZhong.

@claude review again latest changes after rebasing

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 1m 25s —— View job


Needs discussion: re-review posted. The generate.py teardown and the private-API TODO links are fixed, so the only open item is a maintainer call on the overlap with the draft #5919.

@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: Needs discussion -- d8dd4aa fixes both code items left open by the last review. The only item still open is whether the CPU release hints land in VLLMSessionKVHolder now, even though the draft #5919 deletes that holder. That is a maintainer call, not a code defect.

What changed since the last review (d8dd4aa, rebased onto 72e5566).

  • Resolved: generate.py teardown. generate.py:157-165 now calls cleanup_dist_env_and_memory() after engine.shutdown() when the engine is a VLLMEngine. Looking it up through sys.modules keeps vLLM from being imported for SGLang recipes. That works because the recipe's VLLMEngine.Config has already loaded the module. This restores what main's _shutdown_engine did.
  • Resolved: private-API TODOs. All three places are TODO(acisseJZhong) again, each linking vllm-project/vllm#69786: kv_offload_scheduler.py:13, simple_cpu_offload_connector.py:39 and engine.py:628.
  • Resolved: testing. The description now reports generate.py runs at TP=4 on vLLM, on SGLang, and on vLLM with offload, all matching main's output.
  • Rebase. It doesn't change PR logic. The new mooncake_master_address=None argument in generate.py comes from main's GenerationEngine.build signature.

Example (the open decision).

VLLMEngine.Config(
    kv_offload=SimpleCPUKVOffloadConfig(cpu_bytes_per_rank=40 << 30),
    session_kv_holder=VLLMSessionKVHolder.Config(),  # session end -> release_session_cache(...)
)
# #5919 (draft, felipemello1): deletes VLLMSessionKVHolder and adds VLLMSessionKVEvictor.
# Whichever lands second has to move _cpu_sessions/_released_*/_eviction_hashes/
# _pending_saves/_release_cpu_cache onto the surviving release mechanism.

Must fix

  1. Overlap with #5919 (still open, maintainer decision). About 100 lines of CPU-hint state are still in session_kv_holder.py. The same hint path also needs get_pending_save_ids/release_session_cache in simple_cpu_offload_connector.py, plus test_session_kv_offload.py. The headline Terminal-Bench numbers were measured without a session holder. Option A: land the hints here and move them when #5919 lands. Option B: drop them here (LRU only, about 350 fewer lines) and re-add them on the evictor.

Should consider

  • engine.py (reset_kv_cache_on_model_state_dict_load rejection), still open: this runs when the engine is built on the generator actor. Generator.Config.__post_init__ can see both fields and could reject the combination at config time.
  • felipemello1's request for transfer-time metrics (load/offload time, and how much of it is exposed) has no reply yet. It would help diagnose the slowdown they are seeing. At minimum, answer it or add a TODO.

A maintainer still needs to review: tianyu-l's CHANGES_REQUESTED is still pending, and this PR changes engine_loop.py and the shared GenerationEngine.has_unfinished_requests contract. The bot's earlier REQUEST_CHANGES reviews have no open code findings left. The remaining item is the maintainer decision above.

Not verified (no vLLM or GPU here): clean exit of generate.py under torchrun with the new teardown. I'm relying on the author's reported runs.

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude #5919 is still in draft mode and we should revisit the changes in this PR to remove the kv session holder. Shall we approve and land this PR first?
cc @felipemello1

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 1m 9s —— View job


Needs discussion: review posted. Landing first works if the CPU release hints come out. Keeping them would undo felipemello1's plan on #5919 to land that PR first, so that needs their OK, and tianyu-l still has to clear their change request.

@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: Needs discussion -- landing this first is fine if the CPU release hints come out of it. Landing it with the hints reverses the order felipemello1 already set on #5919, so that version needs their agreement.

Answer to the question. #5919 being a draft is not what decides the order. On 2026-11-20, felipemello1 wrote on #5919: "#5847 and #5727 rebase onto this PR after it lands. When they do, they move their release hints from the holder to the evictor's release path." Since then #5919 has been rewritten as a git mv of session_kv_holder.py -> session_kv_evictor.py. It keeps the holder's track / after_step / release methods. So:

  • Land #5847 with the hints first: #5919 then has to carry this PR's ~100 lines of CPU-hint state (_cpu_sessions, _released_*, _eviction_hashes, _pending_saves, _release_cpu_cache) into the evictor, or rewrite them. That moves your rebase work onto felipemello1, so it needs their OK.
  • Land #5847 without the hints first (recommended): neither PR touches the other's code. #5847 can land as soon as it is approved, whatever happens to #5919. The hints come back later as a small follow-up on whichever release path survives. Nothing measured depends on them: the Terminal-Bench numbers in the description ran with no session holder, so CPU eviction there was plain LRU.

Example.

# kept (measured): CPU tier with LRU eviction, with or without the GPU holder
VLLMEngine.Config(kv_offload=SimpleCPUKVOffloadConfig(cpu_bytes_per_rank=40 << 30))
# dropped for now (unmeasured; it lives in the holder that #5919 renames):
#   session end -> holder._release_cpu_cache() -> connector.release_session_cache(released, active)

Must fix (only if landing first)

  1. Remove the hint path, roughly 350 lines:

    • the session_kv_holder.py changes, including the offload_connector= argument at engine build;
    • get_pending_save_ids and release_session_cache in simple_cpu_offload_connector.py;
    • the session_kv_holder.has_pending_work term in VLLMEngine._has_unfinished_local_requests and its docstring bullet;
    • test_session_kv_offload.py, the offload additions to test_session_kv_holder.py, and the "release" command in test_kv_offload.py. cpu-tp2-session can keep hold_sessions=True to cover GPU holder + CPU offload together;
    • the "Session release" section of SIMPLE_CPU_OFFLOAD.md, which becomes one line saying eviction is LRU.

    Since this only deletes code, it does not need another design pass.

Who has to sign off

  • tianyu-l's CHANGES_REQUESTED is still the review decision on this PR. Their comments look resolved at d8dd4aa, but only tianyu-l (or a maintainer dismissing it) can clear it. The bot cannot approve this PR in place of a maintainer.
  • felipemello1, if you keep the hints and land first.

No code changes since the last review (d8dd4aa), so there are no new line-level findings.

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

two more comments; o/w looks great

Comment thread torchtitan/rl/generator/vllm/config.py Outdated
Comment on lines +217 to +218
copies more and showed no speedup when the CPU tier was smaller than the GPU
cache."""

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 didn't understand this sentence, and in general when it's beneficial to offer lazy_offload=False. Could you say more?

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.

oops sorry my agent help me overwrite it with a less clear comment :(

@acisseJZhong acisseJZhong Nov 25, 2026 •

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.

AI agent reply on behalf of @acisseJZhong.

Lazy saves a block only when it nears eviction from the GPU cache (vLLM keeps about two steps' worth of token budget offloaded ahead of eviction), so CPU holds blocks the GPU is dropping instead of copies of blocks still on GPU, with far fewer copies. Eager (False, vLLM's default) saves every full block as it is computed; with a CPU tier smaller than the GPU cache, those copies of still-resident blocks push evicted prefixes out of the CPU LRU, and in our runs CPU served only 14% of GPU misses with no speedup.

Eager only helps when the GPU prefix cache is dropped without eviction (e.g. reset_prefix_cache). RL with KV offload never does that: it rejects reset_kv_cache_on_model_state_dict_load=True. I rewrote the docstring to say this.

Comment on lines 451 to +452
self._request_dispatcher.rank0_num_outstanding_generations()
or has_unfinished_requests

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.

These two have some overlap now. Please confirm that rank0_num_outstanding_generations couldn't be removed because we still have to use it to calculate num_admitted_generations below.

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.

AI agent reply on behalf of @acisseJZhong.

Confirmed: both are needed, and num_admitted_generations below also uses rank0_num_outstanding_generations.

Condition Covers Case the other misses
rank0_num_outstanding_generations() generate calls taken off the queue but not yet replied to, including pending_engine_requests not yet admitted Requests held back (e.g. by a model state dict load): the engine is idle, so has_unfinished_requests is False
has_unfinished_requests Engine work, including KV transfers after final outputs Saves still running after every generate returned: outstanding is 0

With only has_unfinished_requests, rank 0 could block on queue.get() after a load with requests still pending.

@acisseJZhong
acisseJZhong force-pushed the codex/simple-cpu-kv-offload branch 2 times, most recently from ddbd4cd to 70f1b0c Compare November 25, 2026 05:15
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

Needs discussion: #5847 (review). Landing first works if the CPU release hints come out. Keeping them would undo felipemello1's plan on #5919 to land that PR first, so that needs their OK, and tianyu-l still has to clear their change request.

@claude could you help approve this PR? tianyu already cleared his change request.

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 25s —— View job


I can't approve this PR: the bot isn't allowed to submit approving reviews, and a maintainer has to approve it, not the bot. tianyu-l's approval at 2026-11-25T04:46 already replaces their earlier change request, so the bot's approval isn't what's blocking the merge.

Details
  • Since the last review: there's one new commit, 70f1b0c. It only rewrites the lazy_offload docstring in config.py to answer tianyu-l's question. The new text matches your reply in that thread. No new findings.
  • Earlier bot reviews marked CHANGES_REQUESTED (2026-11-22 and 2026-11-25 02:35/02:48): every code item in them is fixed. If they still show as blocking in the merge box, a maintainer can dismiss them.
  • Still open, and only a maintainer can decide it: the CPU release hints in VLLMSessionKVHolder. On [rl] Evict an ended rollout's KV from vLLM's prefix cache #5919, felipemello1 planned for this PR to rebase onto [rl] Evict an ended rollout's KV from vLLM's prefix cache #5919 and move its hints to the evictor. So landing this PR first with the hints needs their OK. Landing it first without the hints (LRU only, about 350 fewer lines) needs nobody's OK. If you want, I can push that removal to this branch.
  • felipemello1's request for transfer-time metrics still has no reply. A reply or a TODO would close it.

More on why the bot can't approve: FAQ.

Keep KV evicted from the GPU prefix cache in CPU DRAM and reload it on later
turns, for Titan's external-launcher generators.

- VLLMEngine.Config.kv_transfer_config (vLLM KVTransferConfig), validated in
  __post_init__: SimpleCPUOffloadConnector with kv_role="kv_both" and prefix
  caching on.
- cpu_kv_offload.py: KVOffloadScheduler orders requests and block releases by
  a shared Titan request ID and aggregates KV completions across the TP group;
  simple_cpu_offload.py scopes the save quorum to one TP group.
- The engine loop keeps stepping while scheduler work or saves remain; idle DP
  replicas join EP forwards with dummy batches.
- Offloaded blocks use the GPU prefix cache's salt (min_policy_version), so
  hot_swap=True works; reset_kv_cache_on_model_state_dict_load=True is rejected.
- With session_kv_holder, released sessions' unused CPU blocks are evicted
  first.
- SIMPLE_CPU_OFFLOAD.md, CPU and GPU tests.
…e.py

- VLLMEngine.Config.kv_offload: SimpleCPUKVOffloadConfig replaces vLLM's KVTransferConfig; the engine builds the connector config.
- generate.py builds the recipe's engine (vLLM or SGLang) through GenerationEngine, so KV offload also works there.
- Rename cpu_kv_offload.py -> kv_offload_scheduler.py and simple_cpu_offload.py -> simple_cpu_offload_connector.py.
- Document has_unfinished_requests conditions, the stale value after a full step burst, and the offload/eviction/reload policy.
- test_kv_offload.py: use EngineRequest.prompt.
…M members

- SimpleCPUKVOffloadConfig.lazy_offload defaults to True, the mode behind every measured gain; the GPU test pins eager.
- Replace the private-vLLM TODOs with comments naming the members to recheck on a vLLM upgrade.
…ODOs

- generate.py: with the vLLM engine, call cleanup_dist_env_and_memory() after shutdown; this script owns its process. SGLang exits cleanly without it.
- Turn the private vLLM member comments back into TODOs linked to vllm-project/vllm#69786.
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve (please handle the #5919 hint sequencing and felipemello1's metrics request before merging): review posted. This clears the bot's earlier change requests.

@acisseJZhong
acisseJZhong force-pushed the codex/simple-cpu-kv-offload branch from 70f1b0c to 8445e31 Compare November 25, 2026 05:29

@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 bot found no open code problems at 70f1b0c, and tianyu-l approved. The only open item is a sequencing choice with #5919 that needs no further review.

This approval clears the bot's earlier CHANGES_REQUESTED reviews from 2026-11-22 and 2026-11-25 02:35/02:48. Every item in them is fixed at HEAD. A maintainer still has to sign off, because this PR changes engine_loop.py and the shared GenerationEngine.has_unfinished_requests contract. tianyu-l's approval covers that.

What changed since the last review (d8dd4aa -> 70f1b0c). Only the lazy_offload docstring changed (config.py:214-220), in answer to tianyu-l's question. I checked its claim against the code: under KV offload, the only reset_prefix_cache call site is engine.py:687. That call runs only when reset_kv_cache_on_model_state_dict_load=True, and engine.py:233-238 rejects that combination. So the eager mode's one benefit never applies in RL.

Still in place from earlier rounds:

  • generate.py:156-165 teardown.
  • The vllm#69786 TODO links at kv_offload_scheduler.py:14, simple_cpu_offload_connector.py:40 and engine.py:632.
  • The typed SimpleCPUKVOffloadConfig with lazy_offload=True as the default.

Example.

VLLMEngine.Config(kv_offload=SimpleCPUKVOffloadConfig(cpu_bytes_per_rank=40 << 30))
# turn N+1 misses the GPU prefix cache -> its prefix reloads from this worker's CPU DRAM
# (Terminal-Bench TP=2: prefill 830 -> 289 ms, ITL 59.8 -> 30.4 ms)

Must fix (before merging, no re-review needed)

  1. CPU release hints vs #5919 (draft). On #5919, felipemello1 planned for this PR to rebase onto #5919 and move its hints to the evictor. Pick one:
    • (a) Land with the hints. Get felipemello1's OK on #5919 to carry the _cpu_sessions / _released_* / _eviction_hashes / _pending_saves / _release_cpu_cache state into VLLMSessionKVEvictor.

    • (b) Land without them. Delete the hint path, about 350 lines:

      • the session_kv_holder.py additions;
      • get_pending_save_ids and release_session_cache;
      • the has_pending_work term in _has_unfinished_local_requests;
      • test_session_kv_offload.py;
      • the "release" command in the GPU test.

      Eviction becomes plain LRU, which is what the headline benchmarks used.

  2. Transfer-time metrics. felipemello1's 02:49 request (load/offload time and how much of it is exposed) still has no reply. Answer it or add a TODO. They are seeing a slowdown and can't tell whether offload is the cause.

Not verified: GPU test results and the vLLM private symbols against the pinned vLLM. vLLM isn't importable here.

@acisseJZhong
acisseJZhong merged commit 034291b into main Nov 25, 2026
28 checks passed
acisseJZhong added a commit that referenced this pull request Nov 25, 2026
## Summary (human-written)
Add distributed cpu kv store option for TitanRL. 
Testing [TP=1:
P2598856702](https://www.internalfb.com/intern/paste/P2598856702/),
[TP=2:
P2599224885](https://www.internalfb.com/intern/paste/P2599224885/)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why

Stacked on #5847. The KV that #5847 offloads to CPU is local to one
generator. When a session's next turn lands on a different generator (a
repin after overload, or non-sticky routing), that generator has no KV
for the prefix and recomputes it.

**Example.**
```python
config.generator.engine.kv_offload = MooncakeStoreKVOffloadConfig(
    cache_prefix="<new per launch>", save_decode_cache=True
)
# turn 1 on generator A: prefill, save KV to the Store
# turn 2 on generator B
#   before: local miss -> recompute the prefix
#   after:  Store hit  -> load the prefix KV, prefill only new tokens
```

## What changed

- `config.py`: `MooncakeStoreKVOffloadConfig` (`cache_prefix`, required
and non-empty; `save_decode_cache`), a sibling of
`SimpleCPUKVOffloadConfig` in `VLLMEngine.Config.kv_offload`.
`engine.py` builds vLLM's `KVTransferConfig` and derives
`lookup_rpc_port` (an IPC socket name upstream) per generator so
generators on one host don't collide. Titan never deletes Store keys.
- `mooncake.py` (new, ~90 lines): adapter for external_launcher TP/DP
groups. The TP leader runs the Store lookup and broadcasts the result
and `LoadSpec`; the save quorum is one TP group; each DP replica's TP
leader starts its own lookup server.
- `worker.py`: on steps without a forward, submit Mooncake's finish-time
saves before `get_finished` (vLLM's `kv_connector_no_forward` skips
them, pinning their GPU blocks).
- The job's Store master: the controller starts it on its host (#6254)
when `uses_mooncake_store`, and each generator process writes the
address into a copy of its `MOONCAKE_CONFIG_PATH` file, the only place
vLLM reads it. Generators on all hosts share one Store.
- `MOONCAKE_STORE.md`: setup, configuration, cache-key semantics,
coordination, comparison with local CPU offload, performance.

The adapter and worker override use private vLLM members; TODOs in
`mooncake.py` and `worker.py` link
[vllm-project/vllm#69786](vllm-project/vllm#69786)
and [#69805](vllm-project/vllm#69805).

## User-facing changes

| Before | After |
| --- | --- |
| `kv_offload` accepts only `SimpleCPUKVOffloadConfig` | also
`MooncakeStoreKVOffloadConfig(cache_prefix=...)` (needs the Mooncake SDK
and `MOONCAKE_CONFIG_PATH` without `master_server_address`; the
controller starts the master) |

Defaults are unchanged (no connector).

## 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 three jobs were started together; means over steps 11-24; SE
= Mooncake vs baseline difference / standard error, |SE| >= 2 is
significant.

| Setting | Value |
| --- | --- |
| Workload | Multi-turn agent rollouts with tool calls; 64K context; 64
rollouts/step; sticky routing (default); `hot_swap=True` |
| Generators | 2 GB300 hosts. 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) |
| Mooncake | RDMA over 4 NICs/host; 40 GB/worker (160 GB/host); one
Master per host |
| CPU offload (#5847) | `lazy_offload=True`, 40 GiB/rank |

| Metric | TP=1 baseline | TP=1 Mooncake | TP=1 CPU offload | TP=2
baseline | TP=2 Mooncake | TP=2 CPU offload |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| KV hit rate (GPU + offload) | 8.2% | 35.0% | 68.3% | 4.0% | 36.3% |
71.1% |
| Cached tokens / request | 1,617 | 5,483 (3.4x, 8.4 SE) | 10,355 | 827
| 5,565 (6.7x, 9.6 SE) | 11,725 |
| Prefill (ms) | 1,076 | 670 (-38%, 4.4 SE) | 398 | 830 | 497 (-40%, 5.2
SE) | 289 |
| Inter-token latency (ms) | 48.0 | 38.5 (-20%, 4.2 SE) | 30.2 | 59.8 |
41.1 (-31%, 6.8 SE) | 30.4 |
| Preemptions / request | 0.141 | 0.014 (-90%, 4.5 SE) | 0.030 | 0.077 |
0.006 (-92%, 4.7 SE) | 0.018 |
| Time to first token (ms) | 5,130 | 6,878 (+34%, 1.2 SE, noise) | 4,128
| 12,357 | 6,606 (-47%, 1.8 SE) | 3,970 |
| Training step (s) | 598 | 485 (-19%, 0.8 SE, noise) | 440 | 640 | 434
(-32%, 1.3 SE, noise) | 408 |

Mooncake beats the baseline on engine metrics but trails local CPU
offload under sticky routing: few turns change generator, and Mooncake
saves every computed block, so the Store churns (~0.5 min turnover)
instead of keeping blocks the GPU is about to evict. Over TCP instead of
RDMA, puts back up (~190 MB/s per engine) and pin GPU blocks.

**Cross-generator microbenchmark** (one 8x H100 host, Qwen3-8B, 4
generators, every turn on a different generator, one shared 200 Gb/s
NIC):

| Context | TP | OFF (s) | Mooncake (s) |
| --- | --- | ---: | ---: |
| 32K | 1 | 41.3 | 30.7 (1.35x) |
| 8K | 1 | 11.3 | 10.6 (1.07x) |
| 32K | 2 | 24.8 | 30.9 (0.80x) |

## Numerics

No change without a connector. With Mooncake, reused KV matches GPU
prefix caching up to bf16 noise: in the 32K benchmark 125/128 requests
produce identical tokens vs. OFF (the other 3 diverge at near-tied
tokens). In the agent RL runs, trainer-vs-generator `logprob_diff/max`
per-step mean was 1.83 vs. the baseline's 1.51 (TP=1) and 1.82 vs. 1.36
(TP=2).

## Testing

- CPU: `test_mooncake_coordination.py` (TP lookup broadcast over real
Gloo ranks; no-forward save submission) and `test_generator.py` (engine
args, config rejection).
- Manual (the RL CI image has no Mooncake SDK): two TP=2 x DP=2
generators on 8 H100 with a real Master and RDMA, the second serving the
next turn from the Store; the MAST runs above (TP=1, 24 steps, one
Master per host, before #6254).
- Controller-started master, after rebasing on main with #6254: 8 vLLM
generators (TP=1) on 3 GB300 hosts, Qwen3-0.6B, RDMA, round-robin
routing: one master (on the controller's host), all 8 generators
registered, 411 keys loaded and 389 saved across hosts with 0 failures,
10 steps. Locally, 2 generators (TP=2) on one H100 host: 610 keys
loaded, 0 failures.

## Known issues / follow-ups

- Store isolation relies on a new `cache_prefix` per launch; keys are
salted by policy version, which repeats across runs.
- The performance numbers above used one Master per host; with the
controller's master, all hosts share one Store, which is functionally
tested but not benchmarked.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants