Skip to content

[RL] Integrate Mooncake Store for distributed CPU KV offload - #5727

Merged
acisseJZhong merged 3 commits into
mainfrom
codex/mooncake-store-kv-offload
Nov 25, 2026
Merged

acisseJZhong merged 3 commits into
mainfrom
codex/mooncake-store-kv-offload

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Add distributed cpu kv store option for TitanRL.
Testing TP=1: P2598856702, TP=2: P2599224885

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.

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 ([RL] Start the SGLang Mooncake Store master on the controller 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 and #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, TP=2: 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 [RL] Start the SGLang Mooncake Store master on the controller host #6254).
  • Controller-started master, after rebasing on main with [RL] Start the SGLang Mooncake Store master on the controller host #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.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 2, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 2, 2026
@acisseJZhong
acisseJZhong force-pushed the codex/mooncake-store-kv-offload branch 14 times, most recently from b54f15f to 4eb4c0c Compare November 4, 2026 23:28
@acisseJZhong acisseJZhong changed the title [do not review] [RL] Add Mooncake Store for distributed CPU KV offload [RL] Integrate Mooncake Store for distributed CPU KV offload Nov 4, 2026
@acisseJZhong
acisseJZhong force-pushed the codex/mooncake-store-kv-offload branch from 4eb4c0c to 00bf363 Compare November 5, 2026 03:23
@acisseJZhong
acisseJZhong marked this pull request as ready for review November 5, 2026 03:39
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 5, 2026
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@github-actions
github-actions Bot requested a review from pzhan9 November 5, 2026 03:40
@claude

claude Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 4m 37s —— View job


Request changes: the multi-GPU coordination layer isn't used by any measured or shipped config, the existing Terminal-Bench recipe now requires Mooncake, and there's no end-to-end gain yet. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Request changes -- about 1,000 of the added lines build a TP/DP coordination layer from vLLM scheduler internals. Neither the benchmark nor the recipe exercises it, and the measured end-to-end gain is about zero. Separately, the existing Terminal-Bench recipe now requires Mooncake infrastructure.

What this PR does. It adds VLLMEngine.Config.kv_transfer_config so vLLM's MooncakeStoreConnector can share prefix KV across independent generators through a distributed CPU pool. With the connector on, the cache salt is the loaded policy version (not the request's min_policy_version), and weight loads raise if any request is still active. The engine loop now keeps stepping until asynchronous KV saves drain, and the worker submits finish-time saves on steps that run no forward. When TP*DP > 1, it swaps in a custom connector, a custom scheduler and a priority queue (mooncake.py) so that TP schedulers agree on lookups, completions and block frees.

Example. A 4-turn rollout routes turn 1 to generator A and turn 2 to generator B.

  • Before: B prefills the full turn-1 prompt plus completion from scratch.
  • After: A saves that prefix's KV to the Store under key (cache_prefix, salt=str(loaded_version)). B looks up the same key, loads the matched blocks from CPU, and prefills only the 192 new tokens.

In the PR's own benchmark, prefill tokens drop 62.5%, while rollout throughput moves -0.4% and step time +0.4%.

Must fix

  1. Description. "Summary (human-written)" is empty.

  2. Design gate: split out the multi-GPU coordination. _coordinate_mooncake is true only when TP*DP > 1. Both the benchmark (6 generators, each TP=DP=1) and the recipe (data_parallel_degree=1, tensor_parallel_degree=1) take the single-GPU path. So none of the following is exercised by any measured or shipped config:

    • mooncake.py (363 lines) and test_mooncake_coordination.py (523 lines),
    • the coordinated branches in engine.py,
    • the TP/DP cases of the GPU test.

    This layer is upstream vLLM work done in torchtitan:

    • it overrides private Scheduler methods (_free_blocks, _update_from_kv_xfer_finished, _select_waiting_queue_for_scheduling),
    • it writes connector private state (connector_scheduler._num_workers, worker.lookup_server),
    • it reimplements RequestQueue,
    • it depends on "free in logical-ID order on every rank" invariants that any vLLM upgrade can break.

    Land the single-GPU path first (the config field, salt, drain, no-forward save and engine-loop wake fix, roughly 250 lines). Push external-launcher KV coordination to vLLM, and ban kv_transfer_config with TP*DP > 1 in Generator.Config.__post_init__ until then. Also confirm that vllm-project/vllm#11400 really tracks this; I couldn't check it.

  3. Value. The only measurement shows no end-to-end gain, with paired totals ranging from -1.6% to +2.3%. Before adding a connector field, a recipe default and private-API dependencies, please show a workload where the change pays off: long-context Terminal-Bench turns, where prefill dominates, with the recipe's real routing.

  4. torchtitan_recipes/rl/verifiers_terminal_bench.py:275 -- the existing recipe now requires Mooncake and flips hot_swap=False (inline).

  5. torchtitan/rl/generator/vllm/engine.py:553 -- the hot_swap=True incompatibility is a late RuntimeError; validate at config time (inline).

Should consider

  • torchtitan/rl/generator/vllm/engine.py:516 -- hand-rolled copy of vLLM's DP dummy-batch logic; two collectives per step (inline).
  • torchtitan/rl/generator/vllm/engine.py:486 -- the TODOs link to source files, not issues (inline).
  • torchtitan/rl/generator/vllm/engine.py:432 -- per-restart cache_prefix correctness rule; torchtitan should own a launch nonce (inline).
  • tests/rl/unit_tests/gpu/test_mooncake_store.py:249 -- opt-in test that never runs in CI (inline).
  • tests/rl/unit_tests/cpu/test_mooncake_coordination.py builds vLLM objects with __new__ and private attributes (_capacity_only, _pinned_saves, _gpu_block_pool). It locks in vLLM's internal layout and will break on upgrades. It goes away with must-fix 2.
Details
  • Engine-loop change (engine_loop.py:1557-1605). Passing the last has_unfinished_requests result into _decide_next_action is the right fix for "saves still pending after the final output". For non-Mooncake engines it adds at most one extra non-blocking iteration after a full burst. With saves pending, rank 0 spins (decide with no wait, then a step) until they drain. That's acceptable if saves are short.
  • Salt semantics. With the connector on, the local prefix cache also switches from min_policy_version to the loaded version. After a weight update, later turns of an in-flight group no longer reuse their own earlier-turn KV locally. That's intended for correctness, but it changes behavior relative to the docstring of reset_kv_cache_on_model_state_dict_load (generator.py:147). It's worth a line in that docstring.
  • Requests before the first weight load are rejected per request (engine.py:420). The controller always pulls weights at start_step (controller.py:698) before rollouts, so this is an internal invariant. An assert fits better than a per-request rejection.

Not verified: vLLM internals (the upstream LLMEngine.step dummy-batch path, kv_connector_no_forward being a staticmethod, private scheduler method signatures). vLLM isn't installed in the review environment, and the RDMA/GPU tests couldn't be run. A maintainer still needs to review.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
Comment on lines +539 to +553
if self._uses_mooncake_store:
# Every rank enters the weight-load boundary. Reject active generations
# together, but allow saves of already-computed, versioned KV to finish.
has_requests = self._engine.output_processor.has_unfinished_requests()
if self._coordinate_mooncake:
active = torch.tensor(has_requests, dtype=torch.int32)
dist.all_reduce(
active, op=dist.ReduceOp.MAX, group=get_world_group().cpu_group
)
has_requests = bool(active.item())
if has_requests:
raise RuntimeError(
"Mooncake Store requires drained weight updates: set "
"generator_router.hot_swap=False before loading weights"
)

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=True + Mooncake only fails here, with a RuntimeError, the first time a weight load finds an in-flight request. That can be many steps into a run (and hot_swap defaults to True), so the run dies late instead of at config time.

Both values are visible in Controller.Config.__post_init__ (controller.py:337): raise ValueError there if generator.engine.kv_transfer_config is not None and generator_router.hot_swap. The same goes for the checks at lines 156-180: reset_kv_cache_on_model_state_dict_load, parallelism and engine are all on Generator.Config, so the reset check, the cache_prefix check and the custom kv_connector_module_path check belong in Generator.Config.__post_init__ (generator.py:157), next to the existing batch-invariant check. After that, this runtime all-reduce can become an internal assert (or be dropped).

Comment on lines +275 to +283
kv_transfer_config=KVTransferConfig(
kv_connector="MooncakeStoreConnector",
kv_role="kv_both",
kv_connector_extra_config={
# Created once per controller config and shared by all replicas.
"cache_prefix": f"qwen35-9b-terminal-bench-{uuid4().hex}",
"save_decode_cache": True,
},
),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This turns Mooncake on in the existing Terminal-Bench recipe instead of adding an opt-in example. The description calls the feature "opt-in" and promises "an example recipe". With this change, anyone running rl_grpo_qwen35_9b_terminal_bench needs:

  • a running mooncake_master,
  • MOONCAKE_CONFIG_PATH set on every generator host,
  • the Mooncake SDK and RDMA NICs (the SDK isn't in any requirements file).

The same hunk also flips hot_swap to False (line 219), which changes this recipe's rollout/weight-sync overlap even for users who don't care about the Store.

Two more problems:

  • It combines the connector with FULL_DECODE_ONLY CUDA graphs, which MOONCAKE_STORE.md lists as unvalidated.
  • The recipe routes with StickySessionRoutingStrategy, so later turns mostly go back to the generator that already holds the prefix. The Store only helps on fallback, and there's no measurement of that here.

Smallest fix: leave this recipe unchanged and add a separate ..._mooncake recipe function (or no recipe until there is a measured win on this workload).

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
Comment on lines +507 to +516
if self._coordinate_mooncake and self._engine.dp_group is not None:
core = self._engine.engine_core.engine_core
# Idle DP replicas must still join the EP forward. Include KV-only
# steps, which upstream executes as dummy forwards under DP.
self._engine.has_unfinished_requests_dp(core.scheduler.has_requests())
if self._engine.should_execute_dummy_batch:
self._engine.should_execute_dummy_batch = False
self._engine.engine_core.execute_dummy_batch()
# Continue into step even after a dummy forward: this DP replica may
# still have queued async outputs and KV completions to drain.

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 seems to rebuild LLMEngine.has_unfinished_requests() / LLMEngine.step()'s DP dummy-batch handling by hand, using dp_group, has_unfinished_requests_dp, should_execute_dummy_batch, engine_core.execute_dummy_batch() and engine_core.engine_core.scheduler. It's needed only because has_unfinished_requests() above no longer calls vLLM's version. So each step now does two CPU collectives: the world all-reduce in _sync_unfinished_requests and the DP all-reduce here. The code also depends on private vLLM state that has no TODO.

If the only gap is "scheduler work after the last output" (the scheduler.has_requests() or batch_queue term), ask upstream to count it in LLMEngine.has_unfinished_requests(), and add a TODO with the issue link. Until then, fold the DP decision into the one all-reduce you already do instead of running a second one. Unverified: vLLM isn't installed in the review environment, so I couldn't confirm that upstream step() handles the dummy batch this way.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
Comment on lines +485 to +486
# TODO(acisseJZhong): expose scheduler work through the public LLMEngine interface:
# https://github.com/vllm-project/vllm/blob/main/vllm/v1/engine/llm_engine.py

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 upstream-gap TODO links to a vLLM source file, not an issue. The same is true for worker.py:95-96. Neither link tracks the request or tells a reader when the workaround can go. Please file the vLLM issues (scheduler work missing from the public "unfinished" check; finish-time saves skipped on no-forward steps) and link them, as the repo rules require for upstream workarounds.

Comment thread torchtitan/rl/generator/vllm/engine.py Outdated
Comment on lines +430 to +432
# A rollout group's minimum version can outlive a weight update.
# Shared 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.

Store isolation currently rests on a user rule: MOONCAKE_STORE.md says cache_prefix must be "new for each run or restart, including checkpoint resume". The recipe meets it with uuid4() at config-build time. A user who sets a fixed string and resumes gets salt "N" again for version N. If the trainer weights at N differ (for example, a resume from an earlier checkpoint), stale KV is silently reused across all generators.

Torchtitan could own this instead: have the controller create a nonce once per launch and pass it to the generators, then salt with f"{nonce}:{self._loaded_policy_version}". That removes the per-restart rule from the docs and the uuid4 from the recipe. (Where the nonce comes from is up to you; the point is that correctness shouldn't depend on users rotating a string.)

Comment on lines +246 to +249
@pytest.mark.skipif(
os.getenv("RUN_MOONCAKE_TEST") != "1",
reason="opt-in Mooncake RDMA integration 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 572-line test is skipped unless RUN_MOONCAKE_TEST=1. It also needs the Mooncake SDK, mooncake_master on PATH, GPUDirect RDMA and up to 8 GPUs, so it never runs in CI and doesn't guard anything there. If it's a manual validation script, make it a script next to MOONCAKE_STORE.md (or keep it in your fork) rather than a test file. If it must stay a test, keep only the single-GPU shared-reuse and policy-isolation cases, and say in the PR who runs it and when.

@acisseJZhong
acisseJZhong marked this pull request as draft November 5, 2026 04:26
@acisseJZhong
acisseJZhong force-pushed the codex/mooncake-store-kv-offload branch from ffe0f10 to 0a76c3b Compare November 9, 2026 22:32
@acisseJZhong
acisseJZhong force-pushed the codex/mooncake-store-kv-offload branch 7 times, most recently from 3b605cb to d344fee Compare November 10, 2026 02:49
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review latest code

@acisseJZhong
acisseJZhong marked this pull request as ready for review November 10, 2026 02:50
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 10, 2026
@claude

claude Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

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


Needs discussion: most earlier findings are fixed, but maintainers need to decide whether to own a Mooncake integration that no recipe uses and that trails local CPU offload under default routing. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Needs discussion -- most of the earlier design and recipe findings are fixed, and the change is now small. The open question is for maintainers: should torchtitan carry a Mooncake integration (an external SDK plus private vLLM/Mooncake members) that no recipe uses and that loses to the existing local CPU offload under default routing?

What this PR does. On top of #5847, it accepts kv_connector="MooncakeStoreConnector". It validates at config time that cache_prefix is set and lookup_rpc_port is not, and derives a lookup socket name for each generator. With TP > 1, mooncake.py broadcasts the TP leader's Store lookup and LoadSpec, scopes the save quorum to the TP group, and starts one lookup server per DP replica. worker.py submits finish-time saves on steps that run no forward. Session holders get no offload connector, so no Store key is ever deleted.

Example. Turn 1 of a rollout runs on generator A; turn 2 lands on generator B (repin, or RoundRobin/LeastLoaded routing).

  • Before: B recomputes the whole prefix.
  • After: A saved the prefix KV under (cache_prefix, salt=min_policy_version). B loads it from the Store and prefills only the new tokens.

Must fix

  1. Description. "Summary (human-written)" is still empty. (Still open.)
  2. Upstream TODOs have no issue links (mooncake.py:20, worker.py:117). The adapter writes connector_scheduler._num_workers, worker.lookup_server and load_specs, and the worker override reimplements kv_connector_no_forward. Please file the vLLM issues and link them, as the base PR does in simple_cpu_offload.py (vllm#51428). (Still open; the old link was removed rather than replaced.)
  3. mooncake.py:86 -- followers only ever add to load_specs, so a hit followed by a miss on the same request can leave the TP ranks with different load metadata (inline, unverified).

Should consider

  • MOONCAKE_STORE.md:60 -- cross-run correctness still depends on users rotating cache_prefix on every launch and resume. A launch nonce owned by the controller and mixed into the salt would remove that rule. (Still open.)

Questions

  • Maintainers. Is this worth owning without a recipe? The new data:
    • Under sticky routing (the default, and what Terminal-Bench uses), Mooncake trails local CPU offload on hit rate, prefill time and ITL, and step time is within noise.
    • It wins only in a synthetic run that forces every turn onto a different generator, and only at TP=1 with 32K context (1.35x). At TP=2 with 32K it is 0.80x.
    • A Store shared across hosts is unvalidated, so multi-host runs share KV only within a host.
  • Author. Is there a real routing setup where it pays off end to end, for example the in-repo LeastLoadedRoutingStrategy on the agent workload? If so, who will run it?
Details

Resolved since the last review:

  • the Terminal-Bench recipe is unchanged;
  • session release no longer deletes Store keys (offload_connector=None for Mooncake);
  • the cache_prefix check moved to __post_init__;
  • a user-set lookup_rpc_port now raises;
  • the mocked __init__ test, the opt-in GPU test and the duplicated flow diagram are gone.

generator_name comes from generator_role_names (actors/monarch/system.py:151), so the derived socket names are unique per generator, as the new GenerationEngine docstring claims.

Not verified: vLLM and Mooncake aren't installed here. I couldn't check whether upstream get_num_new_matched_tokens ever removes a load_specs entry or raises (a raise on the leader would leave followers stuck in the broadcast), or what upstream kv_connector_no_forward does beyond wait_for_save=False. A maintainer still needs to review.

Comment on lines +86 to +89
result, load_spec = payload[0]
if load_spec is not None:
self.connector_scheduler.load_specs[request.request_id] = load_spec
return result

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.

Followers only ever add to load_specs; they never remove from it. The leader's load_specs is whatever upstream leaves there. So if one request is looked up twice, the TP ranks can drift apart. Example: a hit whose GPU allocation fails, so the request stays waiting, followed by a miss on the next step because the Store evicted the prefix. If upstream drops or clears the entry on the miss, the leader has no spec, but each follower keeps the old one. The followers then build load metadata the leader doesn't, and the TP forward goes out of lockstep. Unverified: I couldn't check whether upstream ever pops the entry in get_num_new_matched_tokens. Mirroring the leader exactly makes the question moot:

Suggested change
result, load_spec = payload[0]
if load_spec is not None:
self.connector_scheduler.load_specs[request.request_id] = load_spec
return result
result, load_spec = payload[0]
if load_spec is None:
self.connector_scheduler.load_specs.pop(request.request_id, None)
else:
self.connector_scheduler.load_specs[request.request_id] = load_spec
return result

The CPU test's lookup worker could cover this with one extra call: a hit, then a miss.

@felipemello1

Copy link
Copy Markdown
Contributor

from claude to felipe: a TLDR image of this PR, drawn from its diff at ecff03fdf.

A turn that lands on another generator now loads its prefix from a Mooncake Store shared by the generators instead of recomputing it; a 32K-context benchmark runs 1.35x faster at TP=1 but 0.80x at TP=2, and agent RL gets a 35.0% KV hit rate under sticky routing, against 68.3% for local CPU offload.

@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 59s —— View job


Approve: the earlier findings are resolved and the maintainer has approved, but two small edits are left before merging: link the two upstream TODOs to vLLM issues, and fix the stale docstring in mooncake_master.py. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. The rebase fixes the last correctness finding. @tianyu-l's approval settles the ownership question from the previous review. What remains is two small edits.

What changed since the last review.

  • Mooncake is now a typed MooncakeStoreKVOffloadConfig next to SimpleCPUKVOffloadConfig in VLLMEngine.Config.kv_offload, replacing a raw KVTransferConfig. This follows the "select by config type" rule.
  • The controller now starts the job's Store master (#6254). Each generator process writes the master's address into a temp copy of its MOONCAKE_CONFIG_PATH (_use_mooncake_master).
  • The prefix-caching ban is now limited to SimpleCPU offload.

Example.

config: kv_offload=MooncakeStoreKVOffloadConfig(cache_prefix="run-1")
controller: start_master() -> "10.0.0.5:41234"
generator rank: reads $MOONCAKE_CONFIG_PATH {"protocol": "rdma", ...}
                writes /tmp/mooncake_store_XXXX.json {..., "master_server_address": "10.0.0.5:41234"}
                points $MOONCAKE_CONFIG_PATH at the copy -> vLLM's connector joins the shared Store

Earlier findings.

  • Resolved: the "Summary (human-written)" section is filled in.
  • Resolved: mooncake.py:746-750 now mirrors the leader's load_specs exactly, including the case where the leader drops a spec. The CPU test covers a hit followed by a miss.
  • Resolved by the maintainer: ownership without a recipe (approved by @tianyu-l).

Must fix

  1. Still open: the upstream-gap TODOs have no issue links (mooncake.py:679-681, worker.py:783-788). Both workarounds depend on private vLLM members:

    • connector_scheduler._num_workers, worker.lookup_server and load_specs,
    • a reimplemented kv_connector_no_forward.

    CLAUDE.md principle 3 asks for an issue link on each, as the base PR does for simple_cpu_offload.py. Please file the two vLLM issues and link them:

    • external-launcher TP lookup/save-quorum/lookup-server coordination,
    • kv_connector_no_forward passing wait_for_save=False.
  2. torchtitan/rl/generator/mooncake_master.py:7-8 -- the module docstring still says the master is "used by SGLang's HiCache storage backend". After this PR, vLLM's MooncakeStoreConnector uses it too. Update that line (this file isn't in the diff, so this is noted here rather than inline).

Should consider

  • Still open: config.py:483 / MOONCAKE_STORE.md:369 -- correctness across runs still relies on users choosing a new cache_prefix for every launch and resume. A launch nonce owned by the controller and mixed into the salt would remove that rule. The controller now owns the master, so it is the natural owner of the nonce too.
Details
  • _use_mooncake_master (engine.py:148) is called once per generator process. A second build in the same process (as in the CPU test) reads the copy that already holds the address, so it is idempotent. The temp copy is never removed, which leaves one small JSON in /tmp per rank per launch.
  • uses_mooncake_store is read by controller.py:800 to decide whether to call start_master(), so the SDK import fails on the controller before any generator starts.
  • Lifting the prefix-caching ban for Mooncake (engine.py:226) is consistent with how Store lookups work: they key on request block hashes, which vLLM computes whenever a connector is configured (unverified, vLLM isn't installed here).

Not verified: vLLM and Mooncake aren't installed here. I couldn't check that vLLM reads the master address only from MOONCAKE_CONFIG_PATH, or that upstream kv_connector_no_forward returns early on empty output (the override always builds a ModelRunnerOutput).

@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 53s —— View job


Approve: the two remaining items (vLLM issue links in the TODOs, the stale mooncake_master.py docstring) are fixed, and the new commit adds no new problems. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- both must-fix items from the last review are resolved in 4688ade, and the new commit adds no new problems.

What changed since the last review.

  • Resolved: the upstream-gap TODOs now link vLLM issues. mooncake.py:19-22 links vllm-project/vllm#69786 (per-DP lookup server, TP-scoped save quorum, shared TP lookup result). worker.py:118-120 links vllm-project/vllm#69805 (kv_connector_no_forward passes wait_for_save=False).
  • Resolved: the mooncake_master.py module docstring now names both of the master's users, SGLang's HiCache backend and vLLM's MooncakeStoreConnector.
  • The mooncake.py docstring now points at kv_offload_scheduler.py, which exists in the base branch. The SIMPLE_CPU_OFFLOAD.md anchors that MOONCAKE_STORE.md links to (#setup, #weight-and-cache-lifecycle, #multi-gpu-coordination) also exist.

Example.

turn 1 -> generator A: prefill, save KV under (cache_prefix="run-1", salt=min_policy_version)
turn 2 -> generator B (repin or non-sticky routing)
  before: local miss -> recompute the whole prefix
  after:  Store hit  -> load the prefix KV over RDMA, prefill only the new tokens

Should consider

  • Still open: config.py:497 / MOONCAKE_STORE.md:383 -- correctness across runs still depends on users picking a new cache_prefix for every launch and resume. The controller now starts the master, so it could also own a per-launch nonce mixed into the salt, and the rule would go away. This can be a follow-up.

@tianyu-l has approved. This review adds nothing beyond confirming the last two edits.

Not verified: vLLM and Mooncake aren't installed here, so the upstream behavior the two TODOs describe wasn't checked against vLLM source.

Add vLLM's MooncakeStoreConnector as a second KV offload connector, so a turn
routed to a different generator loads its prefix from the shared Store instead
of recomputing it.

- engine.py: accept MooncakeStoreConnector; require cache_prefix; derive
  lookup_rpc_port per generator and reject user values.
- mooncake.py: TP leader lookup broadcast, TP-group save quorum, per-DP-replica
  lookup server.
- worker.py: submit Mooncake saves on no-forward steps before get_finished.
- MOONCAKE_STORE.md: setup, configuration, cache semantics, performance.
- Tests: config/engine-args tests, Gloo lookup broadcast and no-forward save
  tests.
…aster docstring

- mooncake.py and worker.py TODOs link vllm-project/vllm#69786 and #69805.
- mooncake_master.py: vLLM's MooncakeStoreConnector also uses the job's master.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/docker 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