Skip to content

[rl] SGLang generator: share KV across generators through Mooncake Store - #6027

Merged
acisseJZhong merged 1 commit into
pytorch:mainfrom
acisseJZhong:sglang-mooncake-store
Nov 17, 2026
Merged

acisseJZhong merged 1 commit into
pytorch:mainfrom
acisseJZhong:sglang-mooncake-store

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Why

A multi-turn session's KV lives on one generator. When its next turn lands on another generator (after a repin, or with non-sticky routing), that generator recomputes the whole history. This is the SGLang counterpart of #5727 (vLLM).

Background: SGLang HiCache. SGLang's hierarchical cache (HiCache) keeps prefix KV in three tiers. Only L3 is shared across generators:

Tier Where Shared across generators? SGLang (extra_server_args) vLLM counterpart in TorchTitan
L1 GPU memory no prefix (radix) cache, on by default prefix cache
L2 host memory no enable_hierarchical_cache=True, hicache_size (already supported, see the README's "CPU KV offload") SimpleCPUOffloadConnector (#5847)
L3 storage backend yes hicache_storage_backend="mooncake" (this PR) MooncakeStoreConnector (#5727)

L3 works through L2: a load goes Store -> host -> GPU, so enabling the Store also enables L2. SGLang itself moves KV between tiers, prefetches from L3, and keeps TP ranks consistent, so unlike #5847/#5727 this needs no connector or coordination code in TorchTitan: users can already turn L3 on through extra_server_args. But turned on as is, L3 silently serves KV that other weights computed in two cases. This PR adds one config check for each:

  1. Across runs. Store keys are the model path, the request's cache salt (its pinned policy version: "0", "1", ...), the token prefix and the TP rank. Every run starts at policy version 0, so two runs' keys for the same prompt are identical. The Store outlives a run, so run B loads KV that run A's weights computed, and Mooncake's write-once put keeps run B's own KV from replacing it.
    Check: "mooncake" requires a non-empty extra_backend_tag, a key prefix that scopes keys to a run. A resume can keep its tag to reuse KV; the README notes the catch (KV the previous launch computed after the checkpoint).
  2. With reset_kv_cache_on_model_state_dict_load=True. This mode relies on clearing all KV at each weight load, so requests carry no cache salt and keys depend only on tokens. But SGLang's KV reset (flush_cache) clears L1 and L2, never L3, for any storage backend, so after a load a request can load KV that earlier weights computed. verl hit the same gap ([rollout, vllm, sglang, trtllm, cfg] feat: salt external KV caches by weight version instead of resetting them verl-project/verl#8323).
    Check: a storage backend with this mode raises; the default mode (False) salts requests by their pinned policy version, so it is safe.

Example of case 2 (reproduced locally, Qwen3-0.6B, TP 2):

generator A, reset mode, weights at version 0: turn 1 -> KV written to the Store (unsalted keys)
generator B, reset mode, weights at version 7: turn 2 -> 649 of 650 history tokens loaded from the Store,
                                                         i.e. KV that version-0 weights computed

What changed

  • engine.py (config validation only):
    • Case 1, Config.__post_init__: with hicache_storage_backend="mooncake", raises unless hicache_storage_backend_extra_config sets a non-empty extra_backend_tag. The tag is the key prefix that scopes keys to a run, like [RL] Integrate Mooncake Store for distributed CPU KV offload #5727's cache_prefix; the check cannot tell a new tag from a reused one. Other storage backends raise: their keys can also outlive a run (e.g. file keeps them on disk under /tmp/hicache) and have no verified run-scoped prefix.
    • Case 2, __init__: raises when any storage backend is combined with reset_kv_cache_on_model_state_dict_load=True; the error tells users to keep it False. [rl] Add reprefill_after_model_state_dict_load="next_turn"; drop the KV reset on load #5953 proposes removing the reset mode; this check goes away with it.
  • README.md: a new section covering setup (scripts/install_rl_env.sh already installs the Mooncake SDK for the transport API; start one mooncake_master per SGLang's deployment guide; each generator contributes Store memory, as in [RL] Integrate Mooncake Store for distributed CPU KV offload #5727), how the Store sits below HiCache's host memory, configuration, key semantics, constraints and measured results.

No new config fields: users configure Mooncake through extra_server_args, as they already do HiCache.

Performance

What is compared. Turn 2 of 4 sessions on a generator that has not seen them, done two ways:

  • Recompute: a fresh generator without a Store prefills each session's whole history (16,024 tokens).
  • Load from the Store: generator A runs turn 1 (16,000 distinct random tokens per session, 16 decoded tokens) and stays alive, keeping the KV in the Store memory it contributed. Generator B, on other GPUs with empty GPU and host caches, runs turn 2: it loads 16,015 of the 16,024 history tokens per session from the Store and prefills only the rest.

Time is wall clock from submitting the 4 turn-2 requests until all finish (16 decoded tokens each).

Setup. One host, 8x H100; each generator TP 2 on its own GPUs; RDMA over 1 NIC; prefetch policy wait_complete. The Store side runs HiCache with 16 GB of host memory per rank (the L2 that every Store load goes through: Store -> host -> GPU) and contributes 32 GB to the Store; the recompute side runs without HiCache (its caches would be empty anyway). One run per cell, no warmup.

Model Recompute (s) Load from the Store (s) Store vs. recompute
Qwen3-8B 1.38 1.93 1.4x slower
Qwen3-32B 5.24 2.45 2.1x faster

Takeaway. From 8B to 32B, recompute time grew 3.8x but load time only 1.3x: loading scales with KV size, recompute with model compute. The Store pays off when recomputing costs more than moving KV: bigger models, longer histories, faster interconnect (RDMA).

Caveats.

  • The engine's 1-token pages (needed for batch invariance) make one Store object per token, K and V, and TP rank, so loads move many small objects.
  • No end-to-end RL run was measured.

Known issues / follow-ups

  • Not verified: linear attention (GDN, KDA, whose HiCache already raises), MLA, sliding window, or a Store shared across hosts.
  • 1-token pages make many small Store objects. Newer SGLang adds l3_page_span, which could group them.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 11, 2026
@acisseJZhong
acisseJZhong force-pushed the sglang-mooncake-store branch 7 times, most recently from d23e970 to 22a7fe2 Compare November 16, 2026 21:54
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items in the review before merging; the main item is to ban the HiCache storage backends other than mooncake.

@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 PR adds only docs plus two config-time bans that close real silent-stale-KV holes. The one gap is that unverified storage backends still pass through.

What this PR does. Users can already turn on SGLang HiCache's L3 tier through extra_server_args. This PR documents using Mooncake Store as that tier, shared across generators. It also adds two checks. __post_init__ requires a non-empty extra_backend_tag for mooncake, because policy-version salts restart in every run while the Store outlives a run. __init__ rejects any storage backend combined with reset_kv_cache_on_model_state_dict_load=True, because flush_cache never clears L3 and reset-mode requests are unsalted. No new fields. It is consistent with the vLLM counterpart #5727 (cache_prefix).

Example.

run A, policy v0: session S turn 1 -> Store key (model, salt "0", tokens, tp0)
run B (same model/prompts), policy v0: turn 1 of S
  before: same key -> loads run A's KV (write-once put keeps it)
  after:  raises unless each launch sets its own extra_backend_tag
reset mode: generator at v7 sends unsalted request
  before: loads 649/650 tokens of v0 KV from the Store
  after:  ValueError at engine build

Must fix

  1. torchtitan/rl/generator/sglang/engine.py:177 -- only mooncake is guarded. Other storage backends (e.g. file, which persists on disk) carry the same cross-run hazard and are passed through unverified. Ban every backend except mooncake.

Should consider

  • torchtitan/rl/generator/sglang/engine.py:226-241 -- move the rationale out of the 10-line error string into a comment with a TODO for #5953, and trim the __post_init__ comment.
  • torchtitan/rl/generator/sglang/README.md:311 -- the table shows the Store 1.4x slower on 8B. Add the description's one-line takeaway (it pays off when recompute costs more than moving the KV: large models, long histories, RDMA) so readers know when to turn it on.

Questions

  • README.md:292 says generators sharing a tag need the same TP degree. Store keys carry the TP rank but not the TP size. If one run mixes generators with different TP degrees, does a mismatch show up as a miss, as an error, or as silently loading another shard's heads? If it is silent, should the TP degree go into the required tag, or should mixing be banned? Unverified.

Not verified: the key composition of non-Mooncake backends, and SGLang's behavior on a TP-size mismatch. A maintainer still needs to review.

# and the TP rank. The Store outlives a run and policy versions
# restart, so without a new key prefix (extra_backend_tag) per launch a
# run could read KV that another run's weights computed.
if self.extra_server_args.get("hicache_storage_backend") == "mooncake":

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 guards only "mooncake". Every other hicache_storage_backend (file, hf3fs, nixl, ...) is still accepted, and the PR says they are "not verified". Case 1 applies to them too. Take the file backend: it persists on disk after the run ends, so its keys outlive a run even more than a Store does, and they also contain only model path, salt, tokens and TP rank (unverified for each backend). A second run with the same prompts would silently load KV that the first run's weights computed, which is the exact hazard this PR exists to close.

Smallest fix: ban the backends you haven't verified instead of passing them through (principle 8).

backend = self.extra_server_args.get("hicache_storage_backend")
if backend not in (None, "mooncake"):
    raise ValueError(
        "SGLangEngine supports only the 'mooncake' HiCache storage backend, "
        f"got {backend!r}"
    )
if backend == "mooncake":
    ...  # extra_backend_tag check as now

With that ban in place, the reset-mode check in __init__ can also compare against "mooncake" directly.

Comment on lines +226 to +241
if (
config.extra_server_args.get("hicache_storage_backend") is not None
and reset_kv_cache_on_model_state_dict_load
):
raise ValueError(
"SGLangEngine does not support a HiCache storage backend "
"(hicache_storage_backend) with "
"reset_kv_cache_on_model_state_dict_load=True: this mode clears "
"KV at each weight load instead of salting requests by policy "
"version, but SGLang's KV reset (flush_cache) clears GPU and "
"host memory, not the storage backend. Unsalted storage keys "
"depend only on tokens, so requests would read KV that earlier "
"weights computed. Keep "
"reset_kv_cache_on_model_state_dict_load=False, which salts "
"requests by their pinned 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.

The error string runs to 10 lines and carries the whole rationale, which the README already gives. Move the "why" into a short comment above the check, and add a TODO for #5953, since the description says this check goes away once that lands. Keep the message to what the user has to do:

        # SGLang's KV reset (flush_cache) clears GPU and host memory but not the
        # storage backend, and reset mode sends unsalted requests, so a request
        # would read KV that earlier weights computed.
        # TODO(https://github.com/pytorch/torchtitan/pull/5953): drop with the reset mode.
        if (
            config.extra_server_args.get("hicache_storage_backend") is not None
            and reset_kv_cache_on_model_state_dict_load
        ):
            raise ValueError(
                "A HiCache storage backend requires "
                "reset_kv_cache_on_model_state_dict_load=False"
            )

The same goes for the 7-line comment in __post_init__ (lines 170-176): it repeats the README's key description, and one sentence on why the tag must be new per launch is enough.

@acisseJZhong
acisseJZhong force-pushed the sglang-mooncake-store branch 2 times, most recently from a09b29e to 369a230 Compare November 16, 2026 22:08
@acisseJZhong
acisseJZhong marked this pull request as ready for review November 16, 2026 22:11
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 16, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 16, 2026 22:12
Comment on lines +257 to +260
Install the Mooncake SDK on each generator host (`pip install
mooncake-transfer-engine`, or `mooncake-transfer-engine-cuda13` for CUDA 13
PyTorch), start a master (`mooncake_master --rpc_port=50051`), and configure
the generators; each generator contributes the Store memory:

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.

Hmm how should we handle the installation as a framework -- should we put this into RL install script? I know that transport API has mooncake as one of the backends. Also, SGLang should already depend on mooncake?

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.

Comment on lines +188 to +193
if not extra_config.get("extra_backend_tag"):
raise ValueError(
"The Mooncake HiCache storage backend needs a new "
"'extra_backend_tag' per launch in "
"hicache_storage_backend_extra_config (a JSON string)"
)

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.

If users set the same tag between two runs, that should be allowed because they might want to reuse the stored KV?

E.g. when restarting from a checkpoint on cluster, during which users couldn't edit any configs, the KV store would be reused; but that seems expected.

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.

@acisseJZhong
acisseJZhong force-pushed the sglang-mooncake-store branch 6 times, most recently from b44d38c to 8da4026 Compare November 17, 2026 08:35
SGLang's HiCache already supports Mooncake Store as its storage tier, and
SGLangEngine passes it through extra_server_args. Validate the settings that
would otherwise serve KV computed by other weights: only the 'mooncake'
storage backend, with an extra_backend_tag (a key prefix scoping keys to a
run), and no KV reset on model state dict load (which leaves requests without
a cache salt while SGLang's flush leaves the Store as is). Document the setup,
the key semantics and measured results.
@acisseJZhong
acisseJZhong merged commit 8e0c77f into pytorch:main Nov 17, 2026
acisseJZhong added a commit that referenced this pull request Nov 20, 2026
…6254)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->
start the mooncake master on controller host, instead of user defined
host/port that might live with random trainer/generator, for better
fault tolerance.
## Why

With SGLang's Mooncake Store backend (#6027), users start
`mooncake_master` by hand on some host and copy its address into every
generator's `hicache_storage_backend_extra_config`. The master is not
tied to the job.

```text
before: user starts mooncake_master somewhere, copies "<host>:50051" into the config
after:  the controller starts it on its host; all generators (on any host) get its address
```

## What changed

- When `config.generator.engine.uses_mooncake_store` (SGLang:
`hicache_storage_backend="mooncake"`), the controller starts
`mooncake_master` on its host and passes `mooncake_master_address` to
the engine constructors, like `vision_processor`. SGLang adds it to
`hicache_storage_backend_extra_config`.
- `generator/mooncake_master.py`: free ports, the controller host's IP
(other hosts may not resolve its name), and the master exits with the
controller (`PR_SET_PDEATHSIG`).
- Setting `master_server_address` yourself raises at config time.
- SGLang README: no manual master; with generators on several hosts, set
`MOONCAKE_LOCAL_HOSTNAME` per host (plus `MC_USE_IPV6=1` for IPv6).

## Testing

8 SGLang generators on 3 GB300 hosts, Qwen3-0.6B, Mooncake over RDMA,
round-robin routing: all 8 registered with the controller's master,
~140K Store objects loaded across hosts, 0 failures, 10 steps. Local (1
H100 host, 2 generators): same, and the master exits with the
controller, also after `kill -9`. Both set `prefetch_threshold: 32`,
since AlphabetSort prefixes are below SGLang's 256-token default.

## Follow-ups

- TODO: vLLM's Mooncake Store connector (#5727, not merged) should use
`mooncake_master_address`.
- No master HA: if it dies mid-run, Store operations fail.
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.

2 participants