Skip to content

[RL] Start the SGLang Mooncake Store master on the controller host - #6254

Merged
acisseJZhong merged 2 commits into
mainfrom
codex/mooncake-controller-master
Nov 20, 2026
Merged

acisseJZhong merged 2 commits into
mainfrom
codex/mooncake-controller-master

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

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.

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

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 19, 2026
@acisseJZhong
acisseJZhong force-pushed the codex/mooncake-controller-master branch from f2508a1 to 52833d8 Compare November 19, 2026 22:08
@acisseJZhong acisseJZhong changed the title [RL] Start the Mooncake Store master on the controller host [RL] Start the SGLang Mooncake Store master on the controller host Nov 19, 2026
@acisseJZhong
acisseJZhong force-pushed the codex/mooncake-controller-master branch from 52833d8 to 1355c40 Compare November 19, 2026 23:42
@acisseJZhong
acisseJZhong changed the base branch from codex/mooncake-store-kv-offload to main November 19, 2026 23:42
@acisseJZhong
acisseJZhong force-pushed the codex/mooncake-controller-master branch 3 times, most recently from 47c4600 to 885639d Compare November 20, 2026 00:07
@acisseJZhong
acisseJZhong marked this pull request as ready for review November 20, 2026 00:13
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 20, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 20, 2026 00:13
@acisseJZhong
acisseJZhong force-pushed the codex/mooncake-controller-master branch from 885639d to 900f31b Compare November 20, 2026 00:15
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve, with a few items to address before merging. See the review for details.

@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 design is sound: the controller owns the job's lifetime and is the one place every launcher shares, and the base hook keeps the controller from knowing about Mooncake. The remaining items are small, local edits. This touches controller.py, so a maintainer still needs to review.

What this PR does. It adds a no-op GenerationEngine.Config.start_job_services(). The controller calls it once, before spawning the generator router, and builds the generators from the config it returns. With hicache_storage_backend="mooncake", SGLang's override does three things:

  • starts mooncake_master on the controller host, on free ports, tied to the controller with PR_SET_PDEATHSIG;
  • writes <ip>:<port> into hicache_storage_backend_extra_config["master_server_address"];
  • raises if the user already set that key.

Example.

config: hicache_storage_backend="mooncake",
        extra_config={"extra_backend_tag": "run42", "protocol": "rdma", ...}

before: user runs `mooncake_master --rpc_port=50051` somewhere and adds
        "master_server_address": "<host>:50051"; the master outlives the job
after:  controller host 10.0.0.5: mooncake_master --rpc_port=41233 --metrics_port=41877
        generators 0..7 get extra_config + {"master_server_address": "10.0.0.5:41233"}
        controller exits (even kill -9) -> master gets SIGTERM
        extra_config already has master_server_address -> ValueError

Must fix

  1. PR description: "Summary (human-written)" is empty. The author needs to write it (see CONTRIBUTING.md, "AI-assisted contributions").

Should consider

  • torchtitan/rl/generator/sglang/engine.py:206 -- the master_server_address check runs after the trainer is spawned, not at config time (inline).
  • torchtitan/rl/generator/mooncake_master.py:62 -- preexec_fn is not fork-safe when threads are running; setpriv --pdeathsig is a fork-safe alternative (inline).
  • torchtitan/rl/generator/mooncake_master.py:80 -- nothing keeps the Popen handle, so Controller.close() can't stop the master (inline).
  • torchtitan/rl/generator/mooncake_master.py:57 -- the comment about :: vs. 0:0:0:0:0:0:0:0 needs clarifying (inline).
  • torchtitan/rl/generator/mooncake_master.py -- the only consumer today is SGLang. Placing it at rl/generator/ is fine if #5727 (vLLM Mooncake Store) switches to it. #5727 currently still documents a manually started master and MOONCAKE_CONFIG_PATH, so either update it in #5727 or start this file in sglang/.
Details
  • Gate. The problem is real on main: the README told users to start a master by hand, and nothing tied it to the job. Patching the config at runtime (replace(config.generator, engine=...)) runs against "build complete, never mutate", but the value really is runtime-only (a free port and the controller's IP, on whichever host runs the controller). SGLang reads the address only from extra_config once extra_config is set, and extra_backend_tag makes extra_config required, so there is no env-var route. A hook on the engine base with one in-repo consumer is justified here by the alternative (an isinstance(SGLangEngine.Config) check in the controller) and by the in-flight vLLM consumer.
  • Thread for PDEATHSIG. train.py runs asyncio.run(main()) on the main thread, and start_master() is called synchronously from setup_async, so the forking thread lives as long as the process. Don't wrap it in asyncio.to_thread: the master would then get SIGTERM when the worker thread exits.
  • generator_config is used only at controller.py:784, so no stale engine config leaks to other consumers.

Not verified: SGLang/Mooncake behavior (parsing the [ipv6]:port address, the :: exit), and whether the preexec_fn deadlock can happen in practice. Neither package is installed here.

Comment on lines +206 to +212
if "master_server_address" in extra_config:
raise ValueError(
"Remove master_server_address from "
"hicache_storage_backend_extra_config: the controller starts the "
"job's Mooncake master on its host and sets this address for "
f"every generator (got {extra_config['master_server_address']!r})"
)

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 config error is only raised in setup_async, after spawn_trainer has already provisioned hosts and loaded the trainer. A stale recipe that still sets master_server_address therefore fails minutes into the job instead of at config load. .claude/rules/config.md says to validate in the owning config's __post_init__.

You can't simply move the check into __post_init__, because the dataclasses.replace below runs __post_init__ again on the injected config, and the check would then reject the address the controller just set. Smallest fix:

  • move the check next to the extra_backend_tag check in __post_init__;
  • build the returned config with copy.copy(self) and then assign extra_server_args on the copy. This works because the class is slots=True and not frozen, and it skips re-validation.

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.

Done in 32e8df4: the check is now in SGLangEngine.Config.__post_init__. The controller no longer rewrites the config; it passes the address to the engine constructor (per tianyu's comment), so re-validation can't see it.

Comment on lines +62 to +64
process = subprocess.Popen(
args, preexec_fn=lambda: prctl(_PR_SET_PDEATHSIG, signal.SIGTERM)
)

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 Python docs say preexec_fn is not safe when other threads are running: the child can deadlock before exec. By this point in setup_async, the Monarch actor system and the trainer are already up, so the controller has background threads. Resolving prctl before the fork avoids the import lock, but not locks such as malloc's that another thread may hold at fork time. Unverified whether this can hang in practice. It would be rare, and the symptom would be the 60 s startup timeout.

A fork-safe alternative that keeps the same semantics: args = ["setpriv", "--pdeathsig", "TERM", binary, ...] (util-linux >= 2.33). setpriv calls prctl and then execs, so the parent is still this thread. Otherwise, add a comment explaining why the risk is acceptable here.

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.

Kept preexec_fn and added a comment: the child only calls prctl (resolved before the fork) and then execs. setpriv isn't available on every host, e.g. it's not in our conda env.

f"after {_MASTER_START_TIMEOUT_S} s"
) from None
time.sleep(0.5)
return f"{host}:{rpc_port}"

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 Popen handle is dropped, and start_job_services returns only a config, so nothing can stop the master before the process exits. Controller.close() leaves it running. train.py ends the process right after close(), so that path is fine. But any in-process user of the documented setup_async() / run() / close() pattern (a notebook, or a test or driver that builds more than one controller) leaks one master per run, each holding Store memory metadata and two ports.

Consider having start_job_services also return something the controller can stop in close(). Otherwise, state in the GenerationEngine.Config.start_job_services docstring that the services only stop when the process exits, so in-process callers know.

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.

Intentional: the master lives as long as the controller process (PR_SET_PDEATHSIG), and train.py exits right after close(). The start_master docstring says so.

Comment on lines +54 to +57
if host.startswith("["):
# The default listens on IPv4 only. "::" makes mooncake_master exit, and an
# IPv6 address fails on hosts without IPv6, so pass it only for an IPv6 host.
args.append("--rpc_address=0:0:0:0:0:0:0:0")

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.

0:0:0:0:0:0:0:0 and :: are the same address, so the comment reads as a contradiction. Say why the expanded form works (presumably mooncake_master's address parsing rejects ::, not the address itself), and link the upstream issue in a TODO if this is a Mooncake bug.

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.

Fixed: that claim was wrong. :: works with mooncake_master 0.3.13 and 0.3.14 (checked locally), so the code now passes --rpc_address=::, and only on an IPv6 host. Binding IPv6 fails on hosts without it.

Comment thread torchtitan/rl/controller/controller.py Outdated
self.generator_router = await actor_system.spawn_generator_router(
config.generator_router,
generator_config=config.generator,
generator_config=replace(config.generator, engine=generator_engine),

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 wiring is strange. I think ultimately you would like to

  • init something on controller
  • pass it to generator engine's constructor

then just do it in the natural way?

@acisseJZhong
acisseJZhong force-pushed the codex/mooncake-controller-master branch from 900f31b to 32e8df4 Compare November 20, 2026 00:50
@acisseJZhong
acisseJZhong force-pushed the codex/mooncake-controller-master branch from 32e8df4 to 9ce9fd0 Compare November 20, 2026 00:58
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review again latest changes

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve, with one item to address before merging (the empty human-written summary). See the review for details.

@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 item below before merging. The new commit follows tianyu-l's suggestion: the controller starts the master and passes the address to the engine constructors. The config is no longer rewritten at runtime, and the earlier inline items are resolved.

What changed since the last review (9ce9fd0). start_job_services() is gone. GenerationEngine.Config.uses_mooncake_store (False on the base, hicache_storage_backend == "mooncake" on SGLang) decides whether Controller.setup_async calls start_master(). The controller now calls it before _build_actor_system. The address goes through spawn_generator_router -> GeneratorActor -> Generator -> engine __init__ as mooncake_master_address. SGLangEngine._build_server_args merges it into hicache_storage_backend_extra_config, and VLLMEngine drops it with a TODO.

Example.

extra_config={"extra_backend_tag": "run42", ...}
  -> controller: start_master() -> "10.0.0.5:41233"
  -> each SGLang ServerArgs: extra_config + {"master_server_address": "10.0.0.5:41233"}
extra_config={..., "master_server_address": "h:50051"}
  -> ValueError in SGLangEngine.Config.__post_init__ (config load, before any host is provisioned)

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author needs to write it (CONTRIBUTING.md, "AI-assisted contributions").
Earlier findings at HEAD
  • master_server_address is now checked at config time: resolved (sglang/engine.py:196). Nothing re-runs __post_init__ on an injected config anymore, because the address bypasses the config.
  • preexec_fn fork safety: resolved with a comment explaining why the risk is accepted (mooncake_master.py:60-64).
  • Popen handle not kept: the author says this is intentional, and the start_master docstring states the master lives as long as the process. Accepted.
  • The :: vs 0:0:0:0:0:0:0:0 comment: resolved. The code now passes --rpc_address=:: with an accurate comment.
  • Placement in rl/generator/: justified by the vLLM TODO in vllm/engine.py:168.
  • Callsites: the engine constructor is called only from Generator.__init__ (generator.py:275) and the three updated tests. spawn_generator_router has one implementation (Monarch), which forwards **generator_kwargs. rl/generate.py builds vLLM directly and is unaffected.

A maintainer (tianyu-l) has already approved the controller change.

@acisseJZhong
acisseJZhong merged commit c387dd4 into main Nov 20, 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.

2 participants