Skip to content

[rl] SGLang engine: support SGLang's unified memory (KV and linear attention states in one pool) - #6261

Merged
acisseJZhong merged 7 commits into
mainfrom
jessicazhong/sglang-unified-memory
Nov 21, 2026
Merged

acisseJZhong merged 7 commits into
mainfrom
jessicazhong/sglang-unified-memory

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Utilize the unified memory feature in latest sglang, will delete this patch once upstream fix sgl-project/sglang#49681 lands.

Why

For GDN/KDA models, SGLang splits memory into a fixed KV pool and a fixed state pool (mamba_full_memory_ratio), so long-context and many-short-request workloads need opposite splits (sgl-project/sglang#49676). SGLang's unified memory (enable_unified_memory) puts KV and states in one pool, but on main it fails at engine build:

AssertionError: --enable-page-major-kv-layout: the resolved attention backends ['torchtitan_varlen'] are not in the allowed set ['fa3', 'fa4', 'flashinfer', 'triton', 'trtllm_mha']

What changed

  • registry.py: SGLang checks the unified memory backend allow-list by name; check torchtitan_varlen as fa3, the FlashAttention backend it subclasses (its varlen kernel reads the strided per-layer K/V views). TODO links the upstream gap.
  • engine.py: always set enable_unified_memory for GDN and KDA models, and reserve it from extra_server_args. SGLang builds the unified pool for hybrid models only, so other models are unchanged.
  • Tests: TestSGLangBitwiseParityGDN now runs on unified memory and checks that SGLang built the unified pool. TestSGLangBitwiseParityGDNHiCache adds HiCache and a next-turn parity check after evicting every GPU copy, so KV and GDN states load back from host memory. Added to the B200 CI job.
  • README: replace the state pool sizing section with a short paragraph.

Follow-up: #6021 (stacked on this PR) moves SGLang to sgl-project/sglang#49681 and replaces the allow-list patch with register_attention_backend(..., page_major_kv_layout=True).

Performance

Qwen3.5-9B, TP 1, one GB300, gpu_memory_limit=0.86, max_num_seqs=512, cuda_graph="breakable", random prompts decoded to max_tokens. Seconds until all requests finish (mean of n runs), max running requests in parentheses.

Workload Default ratio (0.9) Ratio 0.25 Unified memory (untuned) Unified vs default
512 req, 16K prompt, 8K out (KV-bound), n=3/2/3 819 (215) 739 (301) 771 (339) 6% faster
1024 req, 512 prompt, 4K out (512 running), n=3/2/3 234 (512) 267 (301) 248 (512) 6% slower

Under unified memory, the ratio only sets the running-request cap (state slots // 3); memory is not split. Unified memory does not speed up every workload: at equal running requests it costs ~1 ms of a ~25 ms decode step (scheduler + kernels). Its gain is that one setting stays within 4-6% of the best static split on both workloads, while each static split loses 11-14% on the other one.

Testing

test_sglang_bitwise_parity.py with the pinned SGLang (851642ade), unified memory on for every GDN and KDA class:

Class GB300 (FA4) H100 (FA3)
GDN 7 passed 7 passed
GDNHiCache 8 passed in 5 of 6 runs 8 passed in 7 of 7 runs
KDA 6 passed 3 failed, same as without unified memory
KDADPEP 6 passed, 1 skipped 4 failed without unified memory, 1 with
SlidingWindow, Varlen, MoEEP (unchanged) SlidingWindow 6 passed Varlen 7 passed, MoEEP 5 passed
  • HiCache load-back: every cached token of the next turn comes from host memory (cached_tokens_host), and decode matches the trainer bitwise; also passes with hicache_write_policy="write_back" (run once, not in CI).

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 19, 2026
@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 12s —— View job


Approve -- please address the items before merging: review (empty human-written summary, README section that contradicts the new paragraph, fa3 alias not tested on the FA3/H100 path).

@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 change is small and opt-in. It works around a real SGLang gap with a TODO linking the upstream PR, and SGLang's own code does the actual work.

What this PR does. SGLang's unified memory (enable_unified_memory) puts full-attention KV and GDN/KDA states in one pool. It only allows attention backends it has audited for page-major K/V views, and checks them by name. torchtitan_varlen isn't on that list, so the engine fails to build. The PR wraps kv_cache_hook.handle_page_major_kv_layout so that SGLang checks torchtitan_varlen under the name fa3 while that check runs. It also adds a GDN parity class on unified memory to the B200 job and a README paragraph.

Example.

SGLangEngine.Config(cuda_graph="breakable",
                    extra_server_args={"enable_unified_memory": True})
# main: AssertionError: --enable-page-major-kv-layout: the resolved attention
#       backends ['torchtitan_varlen'] are not in the allowed set ['fa3', ...]
# PR:   builds; scheduler.token_to_kv_pool_allocator is a ChainAllocator;
#       trainer vs generator logprobs bitwise equal (GDN class, GB300)

Must fix

  1. The PR description's "Summary (human-written)" section is empty. Please fill it in.
  2. torchtitan/rl/generator/sglang/README.md:208 -- the new paragraph contradicts the section above it (lines 181-187 still say SGLang can't share one pool) and leaves out the measured cost of unified memory. See the inline comment.
  3. torchtitan/rl/generator/sglang/registry.py:173 -- the fa3 alias also applies on H100, where the varlen backend runs FA3. Only FA4 (B200/GB300) was tested over the page-major views. Confirm FA3, or alias only for FA4.

Should consider

  • .github/workflows/integration_test_rl_b200.yaml:123 -- the new class adds a full 2-GPU launch and reruns all six inherited GDN tests. Consider running the existing GDN class on unified memory instead.

Questions

  • Is the unified memory and HiCache (enable_hierarchical_cache) combination supported by SGLang, and does it hold bitwise parity? If either is "no", SGLangEngine.__init__ should raise for it, as it already does for HiCache with KDA.

Not verified: the stride handling of PyTorch's FA3 paged kernel over page-major views. I also couldn't confirm that SGLang calls handle_page_major_kv_layout through the module attribute, though test_runs_on_unified_memory would fail if it didn't.

Comment on lines +208 to +212
With SGLang's unified memory (`extra_server_args={"enable_unified_memory":
True}`), the full attention layers' KV cache and the GDN / KDA layers' conv and
recurrent states share one pool, and KV can use any state slot no request holds.
The state pool size then mainly sets the running-request cap, so the default
ratio works for both workloads without tuning.

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 paragraph is tacked onto the end of a section that still says SGLang can't do this. Lines 181-187 say "SGLang splits an engine's memory between the KV pool and a fixed state pool ... vLLM keeps KV and states in one pool and needs no split (sgl-project/sglang#49676 asks SGLang to do the same)". Lines 189-206 then explain how to tune the split by hand. Since the README should describe the current state, readers get the old limitation first and only learn at the very end that it's optional.

Smallest fix: change 181-187 to say the fixed split is SGLang's default and enable_unified_memory removes it. Then add the tradeoff the PR description measured, so users can choose between unified memory and a tuned ratio: about 1 ms of a 25 ms decode step at equal running requests, and within 4-6% of the best static split on both workloads, where each static split loses 11-14% on the other one. As written, "works for both workloads without tuning" reads as if unified memory is free.

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 my behalf.

Fixed in 1a90803: the section now says the fixed split is SGLang's default and unified memory removes it, and the unified memory paragraph states its cost (~1 ms of a ~25 ms decode step; within 4-6% of the best tuned ratio on both workloads, each tuned ratio 11-14% slower on the other).

Comment on lines +173 to +177
def handle_page_major_kv_layout(server_args: Any) -> None:
kv_cache_hook.attention_backends_of = lambda cfg: tuple(
"fa3" if backend == TORCHTITAN_VARLEN_ATTENTION_BACKEND else backend
for backend in backends_of(cfg)
)

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 always tells SGLang the backend is fa3, but TorchTitanVarlenAttnBackend.__init__ (attention/attention.py:52-59) runs PyTorch's varlen kernel as either FA3 (SM90) or FA4 (SM100+). The stride claim in the docstring ("reads that stride") was only tested on GB300/B200, which run FA4. The H100 path, FA3 over page-major K/V views, isn't tested here or in CI. If FA3's paged path assumes contiguous pages, it would read wrong K/V without raising, which the allow-list exists to prevent.

Either confirm FA3 (for example, run the GDN unified memory class on H100 once and say so in the PR), or alias only after checking current_flash_attention_impl() and let SGLang's allow-list reject the unverified kernel. Unverified: I couldn't inspect PyTorch's FA3 paged path from 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 my behalf.

Confirmed FA3 on H100 (SGLang 851642ade, current_flash_attention_impl() == "FA3"): TestSGLangBitwiseParityGDNUnifiedMemory 7/7 and TestSGLangBitwiseParityGDN 6/6 pass, including bitwise trainer-vs-generator logprobs over the page-major views. Docstring now says FA3 or FA4; testing added to the PR description.

tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py::TestSGLangBitwiseParityVarlen -v \
|| failed_classes+=(Varlen)
for test_class in MoEEP GDN SlidingWindow MLA DistMoE; do
for test_class in MoEEP GDN GDNUnifiedMemory SlidingWindow MLA DistMoE; do

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.

GDNUnifiedMemory adds one more 2-GPU torchrun launch to the B200 job. That means building the trainer model, building the SGLang engine with breakable prefill graphs, and rerunning all six inherited GDN tests. The only torchtitan code it guards is the allow-list alias, plus the ChainAllocator check that the flag took effect. tests.md prefers turning a feature on in an existing configuration over adding an entry. One option is to run TestSGLangBitwiseParityGDN itself on unified memory. Its default-split path is SGLang's code, and the torchtitan GDN backend is the same either way. If you keep both classes, the PR should say what regression the default-split GDN class still catches that the unified memory class doesn't.

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 my behalf.

Keeping both: unified memory is opt-in, so the default split is what users run. The default-split class covers the TorchTitan GDN backend on SGLang's separate state pool (contiguous slots); the unified class covers it on strided per-layer views with virtual-to-physical slot ids, plus the allow-list patch. Replacing the default class would leave the default path untested.

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

AI agent reply on my behalf.

On unified memory + HiCache: SGLang documents it as supported. The GDN parity class with enable_unified_memory and enable_hierarchical_cache passes on GB300, but it does not force evictions, so HiCache load-back is not exercised there. Not adding a raise; happy to add one if you'd rather block the combination until load-back is tested.

@acisseJZhong
acisseJZhong marked this pull request as ready for review November 20, 2026 03:42
@pytorch-bot pytorch-bot Bot added ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests labels Nov 20, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 20, 2026 03:43
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

AI agent reply on my behalf.

Follow-up on unified memory + HiCache: load-back is now tested (92088e2). TestSGLangBitwiseParityGDNUnifiedMemory runs with HiCache and adds test_trainer_vs_sglang_decode_after_host_load_back: it evicts every GPU copy after a turn, then checks that the next turn's cached tokens all come from host memory and that decode matches the trainer bitwise. Passes on GB300 (FA4) and H100 (FA3), and once with write_back. So no raise; the combination is supported and covered by the existing CI launch.

Comment on lines +502 to +506
extra_server_args = {
"enable_unified_memory": True,
"enable_hierarchical_cache": True,
"hicache_size": 8,
}

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.

instead of allowing user to send them as "extra" args, should we pin some of them? e.g. do we ever want non-unified memory, even when there's no linear attention?

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.

we would only want to use unified memory for hybrid attention models(no benefits for non linear attn to have unified memory pool, only has extra overheads).

I will change the default setting for hybrid attention model.

@@ -178,13 +178,12 @@ recurrent states.

### The state pool caps running 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.

related to the other comment:
I added this section to clarify the limitation of sglang. Now that the limitation is gone, do we still need to keep this section? The assumption is that users don't need to worry about the flag -- we'll always turn it on.

@acisseJZhong
acisseJZhong force-pushed the jessicazhong/sglang-unified-memory branch from 6c51765 to 22be3b4 Compare November 20, 2026 09:34
@acisseJZhong
acisseJZhong merged commit bbc9482 into main Nov 21, 2026
29 of 31 checks passed
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/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