Skip to content

[PD] feat: refactor custom mem pool and add barex pd support#12332

Merged
ShangmingCai merged 22 commits intosgl-project:mainfrom
openanolis:mateng/add_barex_pd_support
Nov 9, 2025
Merged

[PD] feat: refactor custom mem pool and add barex pd support#12332
ShangmingCai merged 22 commits intosgl-project:mainfrom
openanolis:mateng/add_barex_pd_support

Conversation

@stmatengss
Copy link
Collaborator

@stmatengss stmatengss commented Oct 29, 2025

Motivation

  1. Provide a function to switch between different custom allocator class for more backends.
  2. ACCL-Barex (https://www.alibabacloud.com/help/en/pai/user-guide/accl-alibaba-high-performance-collective-communication-library) is a point-to-point transfer library for Alibaba Cloud. We provide a Barex allocator ([Integration] feat: introduce barex allocator kvcache-ai/Mooncake#932) in mooncake side to support GDR because of several hardware limitations, thus GDR-style PD disaggregation can be enabled with ACCL.

Usage

export SGLANG_MOONCAKE_CUSTOM_MEM_POOL=NVLINK|BAREX

Modifications

  1. Change SGLANG_MOONCAKE_CUSTOM_MEM_POOL from Bool to String type, and keep forward compatibility (still support SGLANG_MOONCAKE_CUSTOM_MEM_POOL=true|false).
  2. Import BarexAllocator from mooncake, and make it as default torch.cuda.mempool.

Accuracy Tests

Benchmarking and Profiling

Checklist

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @stmatengss, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request integrates support for Barex, a specialized point-to-point transfer library, into the system to facilitate GDR-style PD disaggregation. It refactors the custom memory pool configuration mechanism, transitioning the SGLANG_MOONCAKE_CUSTOM_MEM_POOL environment variable from a boolean flag to a string-based selector. This enhancement allows for more granular control over memory allocation strategies, enabling users to explicitly choose between different custom allocators like NVLink and Barex, while also ensuring compatibility with existing configurations.

Highlights

  • Barex PD Support: Introduced support for ACCL-Barex, an Alibaba Cloud point-to-point transfer library, enabling GDR-style PD disaggregation.
  • Flexible Memory Pool Configuration: The SGLANG_MOONCAKE_CUSTOM_MEM_POOL environment variable now accepts string values ("NVLINK", "BAREX") to specify the desired custom memory pool type.
  • Backward Compatibility: The system retains backward compatibility, interpreting SGLANG_MOONCAKE_CUSTOM_MEM_POOL=true as "NVLINK".
  • Dynamic Allocator Selection: The memory pool initialization logic has been updated to dynamically import and utilize either NVLinkAllocator or BarexAllocator based on the configured environment variable.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request adds support for the BAREX custom memory pool, which is a valuable addition. The implementation correctly handles the new allocator type and maintains backward compatibility. However, I've identified significant code duplication in handling the SGLANG_MOONCAKE_CUSTOM_MEM_POOL environment variable and creating the memory pool. This logic is repeated across four different places. Additionally, the list of supported custom memory pool types is duplicated and, in some cases, hardcoded. I recommend refactoring the duplicated logic into a utility function and defining the list of supported types as a central constant to improve maintainability and consistency.

logger = logging.getLogger(__name__)

# Global constants for custom memory pool types
SUPPORTED_CUSTOM_MEM_POOL_TYPES = ["NVLINK", "BAREX"]
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This constant SUPPORTED_CUSTOM_MEM_POOL_TYPES is also defined in python/sglang/srt/mem_cache/memory_pool.py. To avoid duplication and ensure consistency, it would be better to define it once in a central location, for example, python/sglang/srt/constants.py, and import it where needed.

Comment on lines 206 to 215
custom_mem_pool_type = os.getenv("SGLANG_MOONCAKE_CUSTOM_MEM_POOL")
if custom_mem_pool_type is not None:
# Handle boolean True as NVLINK
if custom_mem_pool_type.lower() == "true":
custom_mem_pool_type = "NVLINK"
self.enable_custom_mem_pool = (
custom_mem_pool_type in SUPPORTED_CUSTOM_MEM_POOL_TYPES
)
else:
self.enable_custom_mem_pool = False
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

There's significant code duplication in handling the SGLANG_MOONCAKE_CUSTOM_MEM_POOL environment variable and creating the custom memory pool. This logic is repeated in:

  • python/sglang/srt/disaggregation/mooncake/conn.py (L206-215)
  • python/sglang/srt/mem_cache/memory_pool.py in MambaPool (L152-181)
  • python/sglang/srt/mem_cache/memory_pool.py in KVCache (L454-481)
  • python/sglang/srt/mem_cache/memory_pool.py in SWAKVPool (L980-1007)

To improve maintainability, I recommend refactoring this into utility functions in a shared module like sglang.srt.utils.

One function to get the pool info:

def get_custom_mem_pool_info() -> (bool, Optional[str]):
    custom_mem_pool_type = os.getenv("SGLANG_MOONCAKE_CUSTOM_MEM_POOL")
    if custom_mem_pool_type is None:
        return False, None

    if custom_mem_pool_type.lower() == "true":
        custom_mem_pool_type = "NVLINK"

    if custom_mem_pool_type not in SUPPORTED_CUSTOM_MEM_POOL_TYPES:
        return False, None
    
    return True, custom_mem_pool_type

And another to create the pool:

def create_custom_mem_pool(pool_type: str, device: str) -> torch.cuda.MemPool:
    if pool_type == "NVLINK":
        from mooncake.allocator import NVLinkAllocator
        allocator = NVLinkAllocator.get_allocator(device)
    elif pool_type == "BAREX":
        from mooncake.allocator import BarexAllocator
        allocator = BarexAllocator.get_allocator(device)
    else:
        raise ValueError(f"Unsupported custom mem pool type: {pool_type}")
    return torch.cuda.MemPool(allocator.allocator())

This would centralize the logic and make future changes much easier.


GB = 1024 * 1024 * 1024

SUPPORTED_CUSTOM_MEM_POOL_TYPES = ["NVLINK", "BAREX"]
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This constant SUPPORTED_CUSTOM_MEM_POOL_TYPES is duplicated from python/sglang/srt/disaggregation/mooncake/conn.py. It should be defined in a single shared module (e.g., python/sglang/srt/constants.py) to avoid inconsistencies.

Copy link
Collaborator

Choose a reason for hiding this comment

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

These lines should not be placed in memory_pool this file.

stmatengss and others added 2 commits October 29, 2025 16:58
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@stmatengss
Copy link
Collaborator Author

@ShangmingCai All these changes are similar to NVLinkAllocator. PTAL.

Comment on lines 152 to 162
custom_mem_pool_type = os.getenv("SGLANG_MOONCAKE_CUSTOM_MEM_POOL")
if custom_mem_pool_type is not None:
# Handle boolean True as NVLINK
if custom_mem_pool_type.lower() == "true":
custom_mem_pool_type = "NVLINK"
self.enable_custom_mem_pool = (
custom_mem_pool_type in SUPPORTED_CUSTOM_MEM_POOL_TYPES
)
else:
self.enable_custom_mem_pool = False

Copy link
Collaborator

Choose a reason for hiding this comment

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

Try using the attributes of Envs.SGLANG_MOONCAKE_CUSTOM_MEM_POOL instead of os.getenv.

Comment on lines 431 to 462
self.enable_custom_mem_pool = get_bool_env_var(
"SGLANG_MOONCAKE_CUSTOM_MEM_POOL", "false"
)
custom_mem_pool_type = os.getenv("SGLANG_MOONCAKE_CUSTOM_MEM_POOL")
if custom_mem_pool_type is not None:
# Handle boolean True as NVLINK
if custom_mem_pool_type.lower() == "true":
custom_mem_pool_type = "NVLINK"
self.enable_custom_mem_pool = custom_mem_pool_type in SUPPORTED_CUSTOM_MEM_POOL_TYPES
else:
self.enable_custom_mem_pool = False

Copy link
Collaborator

Choose a reason for hiding this comment

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

ditto

Comment on lines 940 to 988
self.enable_custom_mem_pool = get_bool_env_var(
"SGLANG_MOONCAKE_CUSTOM_MEM_POOL", "false"
)
custom_mem_pool_type = os.getenv("SGLANG_MOONCAKE_CUSTOM_MEM_POOL")
if custom_mem_pool_type is not None:
# Handle boolean True as NVLINK
if custom_mem_pool_type.lower() == "true":
custom_mem_pool_type = "NVLINK"
self.enable_custom_mem_pool = custom_mem_pool_type in SUPPORTED_CUSTOM_MEM_POOL_TYPES
else:
self.enable_custom_mem_pool = False

Copy link
Collaborator

Choose a reason for hiding this comment

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

ditto

Copy link
Collaborator

@ShangmingCai ShangmingCai left a comment

Choose a reason for hiding this comment

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

Maybe I should abstract custom allocator class first, so that we don't need to replicate the code if custom_mem_pool_type == xxxx: in every memory pool.

@stmatengss
Copy link
Collaborator Author

Maybe I should abstract custom allocator class first, so that we don't need to replicate the code if custom_mem_pool_type == xxxx: in every memory pool.

Sure. We can abstract the allocator class to support more in-house GPU link protocols. Should this be implemented in Mooncake or SGLang?

@ShangmingCai
Copy link
Collaborator

Maybe I should abstract custom allocator class first, so that we don't need to replicate the code if custom_mem_pool_type == xxxx: in every memory pool.

Sure. We can abstract the allocator class to support more in-house GPU link protocols. Should this be implemented in Mooncake or SGLang?

We better put it in the Mooncake side, and use env var to switch allocator at the mooncake side with the default value set to nvlink. Then we can unified the code in the sglang.

@stmatengss stmatengss changed the title [PD] feat: add barex pd support [PD] feat: refactor custom mem pool and add barex pd support Nov 3, 2025
@stmatengss
Copy link
Collaborator Author

Maybe I should abstract custom allocator class first, so that we don't need to replicate the code if custom_mem_pool_type == xxxx: in every memory pool.

Sure. We can abstract the allocator class to support more in-house GPU link protocols. Should this be implemented in Mooncake or SGLang?

We better put it in the Mooncake side, and use env var to switch allocator at the mooncake side with the default value set to nvlink. Then we can unified the code in the sglang.

I believe some logic isn't common on the mooncake side. Therefore, I've extracted the switching allocator's logic into utils and created two general APIs. PTAL, thx @ShangmingCai

import triton.language as tl

from sglang.srt.constants import GPU_MEMORY_TYPE_KV_CACHE
from sglang.srt.disaggregation.mooncake.utils import init_mooncake_custom_mem_pool
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
from sglang.srt.disaggregation.mooncake.utils import init_mooncake_custom_mem_pool
from sglang.srt.utils import maybe_init_custom_mem_pool

Then we define a function in sglang.srt.utils:

def maybe_init_custom_mem_pool(
    device: str,
) -> Tuple[bool, Optional[Any], Optional[str]]:
    # This function can be modified to support more features that require a custom memory pool.
    enable_custom_mem_pool = True if envs.SGLANG_MOONCAKE_CUSTOM_MEM_POOL.get() is not None else False

    if enable_custom_mem_pool:
        # Currently, only mooncake requires a custom mem pool for MNNVL PD disaggregation
        from sglang.srt.disaggregation.mooncake.utils import init_mooncake_custom_mem_pool
        return init_mooncake_custom_mem_pool(device)
    else:
        return False, None, None

Copy link
Collaborator

@ShangmingCai ShangmingCai Nov 4, 2025

Choose a reason for hiding this comment

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

Just this minor suggestion, others LGTM.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Remember to fix lint.

Copy link
Collaborator

@ShangmingCai ShangmingCai left a comment

Choose a reason for hiding this comment

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

LGTM now.

@stmatengss stmatengss added the ready-to-merge The PR is ready to merge after the CI is green. label Nov 4, 2025
@stmatengss
Copy link
Collaborator Author

PTAL when it's convenient. Thanks! @xiezhq-hermann

@xiezhq-hermann xiezhq-hermann self-assigned this Nov 5, 2025
Tuple of (enable_custom_mem_pool, custom_mem_pool, custom_mem_pool_type)
"""
enable_custom_mem_pool = (
True if envs.SGLANG_MOONCAKE_CUSTOM_MEM_POOL.get() is not None else False
Copy link
Collaborator

@xiezhq-hermann xiezhq-hermann Nov 7, 2025

Choose a reason for hiding this comment

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

does this support other transfer engine as well? if so, might be a good practice to have a more general set of statements.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Unsure if other transfer engines support these transports; if so, add them to utils.py.

@ShangmingCai ShangmingCai merged commit b8ac4fc into sgl-project:main Nov 9, 2025
158 of 163 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-to-merge The PR is ready to merge after the CI is green. run-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

Comments