Skip to content

[BugFix][MoE] Share MegaMoE symmetric storage with the DSpark draft - #20234

Closed
linfeng-yuan wants to merge 2 commits into
vllm-project:mainfrom
linfeng-yuan:fix/mega-moe-shared-context-20261029
Closed

linfeng-yuan wants to merge 2 commits into
vllm-project:mainfrom
linfeng-yuan:fix/mega-moe-shared-context-20261029

Conversation

@linfeng-yuan

@linfeng-yuan linfeng-yuan commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

What this PR does / why we need it?

DeepSeek V4.1 with DSpark and CANN MegaMoE can create separate symmetric buffers for the target and draft on the same MC2 group. Their native communication contexts interfere, preventing this configuration from running on Ascend A5.

Keep one target-owned allocation on the MC2 group coordinator. Give the draft a metadata view that shares the target's context and context manager while retaining its own expert count, top-k, intermediate size, and receive-token limit. Calls must remain serialized. Validate communication settings and CANN's required buffer capacity before reusing storage; reject draft-first initialization and incompatible requests without creating another native context.

Identify MRv2 eager DSpark draft communicators from logical expert counts when construction still uses the target configuration, accounting for redundant experts. Equal expert layouts retain the existing shared-communicator behavior. No new module-level mutable state is introduced; the owner follows the MC2 group lifetime.

Does this PR introduce any user-facing change?

Yes. Fixes conflicting target/draft MegaMoE communication storage for DeepSeek V4.1 DSpark on A5. No configuration changes are required. A release note fragment is included.

How was this patch tested?

  • CPU tests using Python 3.12, torch 2.10.0+cpu, and the repository's verified vLLM commit 544f182d9f0c9bfe8bd7645525951d5e3692a542:

    TORCH_DEVICE_BACKEND_AUTOLOAD=0 VLLM_TARGET_DEVICE=empty python -m pytest -q \
      tests/ut/ops/test_mega_moe_context.py \
      tests/ut/ops/test_moe_comm_method.py \
      tests/ut/ops/test_fused_mc2_sleep_state.py

    24 passed. New regression coverage checks a single allocation across target/draft/target calls, shared context identity, independent metadata, separate MC2 group lifetimes, draft-first rejection, incompatible settings, token/CCL capacity bounds, and draft identification with redundant experts.

  • Changed-file pre-commit checks passed: Ruff lint/format, codespell, typos, filename checks, package initialization, forbidden imports, and boolean context managers. Logger, long-function, symbolic-meta, and CRLF-aware whitespace checks also passed when invoked directly.

  • bash format.sh ci was attempted. The complete run could not pass on Windows: the actionlint Go runtime download was reset, /bin/bash and python3 were unavailable to some hooks, and shellcheck was not installed. These tooling limitations are separate from the passing changed-file checks; full CI remains required.

  • The user's earlier A5 run established that sharing the target's communication context resolves the observed failure. This PR ports that approach onto current main. The exact PR branch has not been rerun with a full A5 DeepSeek V4.1 + DSpark workload; hardware E2E validation is still required before merge. CPU mocks do not establish native collective correctness or performance.

Checklist

  • Boundary / edge-case coverage

  • Regression test

  • Error / failure path coverage

  • Meaningful & reliable tests

  • Performance impact: A5 E2E and memory validation pending

  • vLLM main: vllm-project/vllm@544f182

Keep one symmetric communication allocation per MC2 group and give each model independent metadata over the shared context. Reject draft-first and incompatible capacity requests before creating another native context.

Signed-off-by: linfeng-yuan <1102311262@qq.com>
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, 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 addresses a critical conflict in MegaMoE communication storage for DeepSeek V4.1 with DSpark on Ascend A5. By allowing the draft model to share the target's communication context while maintaining independent metadata, the changes resolve native communication context interference. The implementation ensures that the target model remains the owner of the allocation and enforces strict serialization and compatibility checks for all shared resources.

Highlights

  • Shared MegaMoE Storage: Implemented a mechanism to share symmetric storage between target and draft models in MegaMoE, preventing communication context interference on Ascend A5 hardware.
  • Draft Identification: Added logic to correctly identify draft communicators even when constructed under target configurations, ensuring proper metadata handling.
  • Safety Validations: Introduced strict validation for communication settings, buffer capacity, and initialization order to ensure safe memory reuse.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

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 the 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 counterproductive. 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.

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. ↩

Signed-off-by: linfeng-yuan <1102311262@qq.com>
@github-actions

Copy link
Copy Markdown
Contributor

👋 Hi! Thank you for contributing to the vLLM Ascend project. The following points will speed up your PR merge:‌‌

  • A PR should do only one thing, smaller PRs enable faster reviews.
  • Every PR should include unit tests and end-to-end tests ‌to ensure it works and is not broken by other future PRs.
  • Write the commit message by fulfilling the PR description to help reviewer and future developers understand.

If CI fails, you can run linting and testing checks locally according Contributing and Testing.


Tip

💡 Consider Linking a Related Issue or RFC

Your PR title contains the [BugFix] tag, indicating a bug fix or new feature.

Linking a related issue or RFC in the PR description is strongly encouraged — it gives reviewers helpful context and speeds up the review. You can use any of these keywords:

  • Fixes #<issue_number>
  • Closes #<issue_number>
  • Resolves #<issue_number>
  • Refs #<rfc_or_issue_number> (for RFCs)

🙏 Thanks for helping us keep the project well-organized!

@gemini-code-assist gemini-code-assist 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.

Code Review

What this PR does / why we need it? This PR implements a shared buffer management system for MegaMoe communication in the Ascend backend. It allows target and draft models to share a single communication buffer, reducing memory overhead and ensuring serialized execution. New utilities is_draft_moe_config and get_main_owned_buffer are introduced to manage buffer ownership and lifecycle. ### Does this PR introduce any user-facing change? No, this is an internal optimization for MoE communication. ### How was this patch tested? New unit tests were added in tests/ut/ops/test_mega_moe_context.py and existing tests in tests/ut/ops/test_moe_comm_method.py were updated to cover the new buffer management logic. ### Review Feedback I have provided feedback to improve robustness: 1. Added defensive checks for vllm_config to prevent AttributeError. 2. Suggested a more robust expert count retrieval method to ensure compatibility. 3. Recommended using weakref for buffer association to avoid risky monkey-patching of C++ objects. 4. Advised using a delegating wrapper class for buffer views to ensure compatibility with objects using __slots__ or C++ extensions.

target/draft model descriptors still distinguish their logical expert
counts; redundant target slots must not turn a target into a draft.
"""
is_draft_runner = getattr(vllm_config.model_config, "runner_type", None) == "draft"

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.

high

If vllm_config is None (which can happen when called outside of an active engine/worker context, such as during offline testing or initialization), accessing vllm_config.model_config will raise an AttributeError. A defensive None check should be added at the beginning of the function.

Suggested change
is_draft_runner = getattr(vllm_config.model_config, "runner_type", None) == "draft"
if vllm_config is None:
return False
is_draft_runner = getattr(vllm_config.model_config, "runner_type", None) == "draft"

Comment on lines +23 to +24
target_experts = int(vllm_config.model_config.get_num_experts())
draft_experts = int(draft_config.get_num_experts())

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.

high

The code calls vllm_config.model_config.get_num_experts() and draft_config.get_num_experts(). However, in standard vLLM, ModelConfig does not have a get_num_experts() method. This will raise an AttributeError at runtime during E2E execution. To ensure compatibility and robustness, we should safely retrieve the number of experts from hf_config or check if the method exists before calling it.

    def _get_experts(cfg: Any) -> int:
        if hasattr(cfg, "get_num_experts"):
            return int(cfg.get_num_experts())
        hf_cfg = getattr(cfg, "hf_config", None)
        if hf_cfg is not None:
            for attr in ("num_experts", "n_routed_experts", "num_local_experts"):
                if hasattr(hf_cfg, attr):
                    return int(getattr(hf_cfg, attr))
        return 0

    target_experts = _get_experts(vllm_config.model_config)
    draft_experts = _get_experts(draft_config)

Comment on lines +53 to +59
owner = getattr(scope, "_main_mega_moe_symm_buffer", None)
if owner is None:
if is_draft:
raise RuntimeError("Main must initialize MegaMoe before the draft")
owner = factory(*bound.args, **bound.kwargs)
scope._main_mega_moe_symm_buffer = owner
return owner

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.

high

Monkey-patching the scope object (which is the MC2 process group or its wrapper) with _main_mega_moe_symm_buffer is risky. If scope is a C++ extension object (such as PyTorch's native ProcessGroup or a class without a dynamic __dict__ or using __slots__), setting arbitrary attributes on it will raise an AttributeError. To safely associate the buffer with the group's lifetime without monkey-patching, we can use a module-level weakref.WeakKeyDictionary.

    if not hasattr(get_main_owned_buffer, "_group_buffers"):
        import weakref
        get_main_owned_buffer._group_buffers = weakref.WeakKeyDictionary()
    group_buffers = get_main_owned_buffer._group_buffers

    owner = group_buffers.get(scope)
    if owner is None:
        if is_draft:
            raise RuntimeError("Main must initialize MegaMoe before the draft")
        owner = factory(*bound.args, **bound.kwargs)
        group_buffers[scope] = owner
        return owner

Comment on lines +91 to +96
view = SimpleNamespace(**vars(owner))
for name, value in params.items():
setattr(view, name, value)
assert view.context is owner.context
assert view._ctx_manager is owner._ctx_manager
return view

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.

high

Using SimpleNamespace(**vars(owner)) to create a view of owner is fragile. If owner is a C++ extension object or uses __slots__, vars(owner) will raise a TypeError. Furthermore, vars(owner) only copies instance attributes from __dict__, meaning any class-level attributes, properties, or methods defined on owner's class will be completely missing from the SimpleNamespace view. To ensure robustness and preserve all methods and properties, we should use a delegating wrapper class instead.

Suggested change
view = SimpleNamespace(**vars(owner))
for name, value in params.items():
setattr(view, name, value)
assert view.context is owner.context
assert view._ctx_manager is owner._ctx_manager
return view
class SymmBufferView:
def __init__(self, owner, params):
self.__dict__["_owner"] = owner
self.__dict__["_params"] = params
def __getattr__(self, name):
if name in self._params:
return self._params[name]
return getattr(self._owner, name)
def __setattr__(self, name, value):
self._params[name] = value
view = SymmBufferView(owner, params)
assert view.context is owner.context
assert view._ctx_manager is owner._ctx_manager
return view

rikakuhi added a commit to rikakuhi/vllm-ascend that referenced this pull request Nov 12, 2026
Keep one target-owned MC2 allocation and independent draft metadata. Bind capacity queries by name for legacy and current CANN interfaces, including intermediate width, combine communication mode, and topology. Adapt the shared-context approach from PR vllm-project#20234 to current main.

Signed-off-by: rikakuhi <942697235@qq.com>
linfeng-yuan pushed a commit that referenced this pull request Nov 23, 2026
…21727)

### What this PR does / why we need it?

DeepSeek V4.1 with DSpark and CANN MegaMoE creates separate target and
draft buffers on the same MC2 group. On A5, the second native context
can contain zero peer-buffer addresses, causing MegaMoE to fail during
startup profiling.

Keep one target-owned allocation on the MC2 group coordinator and give
the draft an independent metadata view over the same context and context
manager. Validate communication settings and capacity before sharing.
Identify MRv2 eager drafts by logical expert counts, including redundant
experts.

Bind CANN capacity queries by parameter name to support both the legacy
interface and the current interface with `intermediate_hidden`,
`combine_comm_mode`, and topology-dependent `server_num`. This updates
the approach in #20234 for current main and CANN 9.2.1 while preserving
main's buffer-sizing policy. Target and draft calls remain serialized.

During wake-up, the first stale model view rebinds the group-owned CANN
context and runs a barrier. Target and draft both refresh their own
runtime metadata from that context. The packaged MLA stream-lifetime
change is tracked in #22592.

### Does this PR introduce _any_ user-facing change?

Fixes conflicting MegaMoE communication contexts for DeepSeek V4.1
DSpark on A5. No additional configuration is required. Includes a
release note fragment.

### How was this patch tested?

- Focused CPU regression and lifecycle tests: **17 passed** with Python
3.12, torch 2.10.0, and vLLM `24420b7a341af37a9bc3186e6fc6062512e0aa58`:

  ```bash
TORCH_DEVICE_BACKEND_AUTOLOAD=0 VLLM_TARGET_DEVICE=empty python3 -m
pytest -q \
    --confcutdir=tests/ut/ops \
    tests/ut/ops/test_mega_moe_context.py \
    tests/ut/ops/test_fused_mc2_sleep_state.py
  ```

- The deployment backport passed **26 CPU tests**, including
`test_moe_comm_method.py`.
- A smoke check against the installed CANN 9.2.1 native capacity-query
API passed for target 384 experts/top-k 6 and draft 128 experts/top-k 3
with P and D capacity settings. Each pair used one mocked allocation and
shared context identity.
- Ruff lint/format, codespell, typos, Python package initialization,
forbidden-import, and boolean-context checks passed.

- Review follow-up: **30 CPU unit tests passed** on Linux AArch64 with
Python 3.12.13, PyTorch `2.10.0+cpu`, pytest 8.4.2 and vLLM
`24420b7a341af37a9bc3186e6fc6062512e0aa58`. Ran `python3 -m pytest -q
-ra` on `test_mega_moe_context.py`, `test_moe_comm_method.py` and
`test_fused_mc2_sleep_state.py` with the repository CPU mocks. The new
sleep/wake-up case covers both target-first and draft-first recovery. A5
hardware coverage remains pending.

### Checklist

- [x] Boundary / edge-case coverage
- [x] Regression test
- [x] Error / failure path coverage
- [x] Meaningful & reliable tests

- vLLM main:
vllm-project/vllm@c410543

---------

Signed-off-by: rikakuhi <942697235@qq.com>
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has conflicts, please resolve those before we can evaluate the pull request.

ningjingbengxiaohai pushed a commit that referenced this pull request Nov 23, 2026
…ANN buffer APIs" (#21727) (#22964)

Revert of PR #21727 (merged onto `main`).

Original PR: #21727
Original author: @rikakuhi
Merge commit: `96ce11dc669b167d04402e94fc0fada32499a6b4`

---
### What this PR does / why we need it?

DeepSeek V4.1 with DSpark and CANN MegaMoE creates separate target and
draft buffers on the same MC2 group. On A5, the second native context
can contain zero peer-buffer addresses, causing MegaMoE to fail during
startup profiling.

Keep one target-owned allocation on the MC2 group coordinator and give
the draft an independent metadata view over the same context and context
manager. Validate communication settings and capacity before sharing.
Identify MRv2 eager drafts by logical expert counts, including redundant
experts.

Bind CANN capacity queries by parameter name to support both the legacy
interface and the current interface with `intermediate_hidden`,
`combine_comm_mode`, and topology-dependent `server_num`. This updates
the approach in #20234 for current main and CANN 9.2.1 while preserving
main's buffer-sizing policy. Target and draft calls remain serialized.

During wake-up, the first stale model view rebinds the group-owned CANN
context and runs a barrier. Target and draft both refresh their own
runtime metadata from that context. The packaged MLA stream-lifetime
change is tracked in #22592.

### Does this PR introduce _any_ user-facing change?

Fixes conflicting MegaMoE communication contexts for DeepSeek V4.1
DSpark on A5. No additional configuration is required. Includes a
release note fragment.

### How was this patch tested?

- Focused CPU regression and lifecycle tests: **17 passed** with Python
3.12, torch 2.10.0, and vLLM `24420b7a341af37a9bc3186e6fc6062512e0aa58`:

  ```bash
TORCH_DEVICE_BACKEND_AUTOLOAD=0 VLLM_TARGET_DEVICE=empty python3 -m
pytest -q \
    --confcutdir=tests/ut/ops \
    tests/ut/ops/test_mega_moe_context.py \
    tests/ut/ops/test_fused_mc2_sleep_state.py
  ```

- The deployment backport passed **26 CPU tests**, including
`test_moe_comm_method.py`.
- A smoke check against the installed CANN 9.2.1 native capacity-query
API passed for target 384 experts/top-k 6 and draft 128 experts/top-k 3
with P and D capacity settings. Each pair used one mocked allocation and
shared context identity.
- Ruff lint/format, codespell, typos, Python package initialization,
forbidden-import, and boolean-context checks passed.

- Review follow-up: **30 CPU unit tests passed** on Linux AArch64 with
Python 3.12.13, PyTorch `2.10.0+cpu`, pytest 8.4.2 and vLLM
`24420b7a341af37a9bc3186e6fc6062512e0aa58`. Ran `python3 -m pytest -q
-ra` on `test_mega_moe_context.py`, `test_moe_comm_method.py` and
`test_fused_mc2_sleep_state.py` with the repository CPU mocks. The new
sleep/wake-up case covers both target-first and draft-first recovery. A5
hardware coverage remains pending.

### Checklist

- [x] Boundary / edge-case coverage
- [x] Regression test
- [x] Error / failure path coverage
- [x] Meaningful & reliable tests

- vLLM main:
vllm-project/vllm@c410543

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has conflicts, please resolve those before we can evaluate the pull request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant