Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
910 changes: 910 additions & 0 deletions docs/fe-oss-apis/moe_ep.md

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions docs/fe-oss-apis/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ This folder documents the Python FE APIs implemented under `python/cudnn`. For d
- [SDPA Forward FE OSS API (SM100, D=256)](https://docs.nvidia.com/deeplearning/cudnn/frontend/latest/operations/Attention.html#sdpa-forward-fe-oss-sm100-d256)
- [SDPA Backward FE OSS API (SM100, D=256)](https://docs.nvidia.com/deeplearning/cudnn/frontend/latest/operations/Attention.html#sdpa-backward-fe-oss-sm100-d256)
- [RMSNorm + SiLU](rmsnorm_silu.md)
- [MoE + Expert Parallel API](moe_ep.md)

## Installation and setup

Expand All @@ -36,6 +37,11 @@ All Frontend OSS APIs come installed with the `nvidia-cudnn-frontend` package. H
pip install nvidia-cudnn-frontend[cutedsl]
```

MoE + Expert Parallel requires its dedicated optional dependencies:
```bash
pip install nvidia-cudnn-frontend[moe_ep]
```

After installation, you can import the APIs directly from the `cudnn` package, i.e. `from cudnn import {your_operation}`

## API Usage
Expand Down
17 changes: 15 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[project]
name = "nvidia-cudnn-frontend"
dynamic = ["version"]
description = "NVIDIA cuDNN Frontend — Python and C++ Graph API with SOTA attention (SDPA / Flash Attention), MoE grouped GEMM fusions, and FP8/MXFP8 kernels for Hopper and Blackwell GPUs."
description = "NVIDIA cuDNN Frontend — Python and C++ Graph API with SOTA attention (SDPA / Flash Attention), MoE grouped GEMM fusions, and FP8/MXFP8 kernels for Hopper, Blackwell, and Rubin GPUs."
readme = "README.md"
requires-python = ">=3.9"
license = {text = "Apache-2.0 AND MIT"}
Expand All @@ -21,6 +21,7 @@ keywords = [
"fp8",
"mxfp8",
"blackwell",
"rubin",
"hopper",
"pytorch",
"kernel",
Expand Down Expand Up @@ -56,7 +57,15 @@ classifiers = [

[project.optional-dependencies]
cutedsl = [
"nvidia-cutlass-dsl[cu13]>=4.5.0",
"nvidia-cutlass-dsl[cu13]>=4.8.0",

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This should be 4.5.0. Rather the kernel should error out if the cutlass-dsl version < 4.8.0

"cuda-python",
"torch",

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Please remove torch. And rebase with develop branch

"apache-tvm-ffi>=0.1.11",
"torch-c-dlpack-ext",
]
moe_ep = [

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Do not recreate another group for moe_ep

"nvidia-cutlass-dsl[cu13]>=4.8.0",
"nvshmem4py-cu13>=0.3.1",
"cuda-python",
"torch",
"apache-tvm-ffi>=0.1.11",
Expand Down Expand Up @@ -89,3 +98,7 @@ version = {attr = "cudnn.__version__"}

[tool.setuptools.package-data]
include = ["**/*"]
"cudnn.moe_ep._megamoe_backend.cutedsl_src" = [
"LICENSE.Apache-2.0",
"VENDOR_INFO.md",
]
34 changes: 32 additions & 2 deletions python/cudnn/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,9 +303,32 @@ def _dlopen_cudnn():
)
__all__ = [*_EAGER_PUBLIC_NAMES, "Graph", "wrapper"]

_OPTIONAL_DEPENDENCY_INSTALL_HINT = "Install with 'pip install nvidia-cudnn-frontend[cutedsl]'"
_CUTEDSL_INSTALL_HINT = (
"Install with 'pip install nvidia-cudnn-frontend[cutedsl]'"
)
_MOE_EP_INSTALL_HINT = (
"Install with 'pip install nvidia-cudnn-frontend[moe_ep]'"
)
_MOE_EP_OPTIONAL_IMPORTS = {
"moe_ep",
"BlockScaledTensor",
"MoeEp",
"MoeEpTuningConfig",
"MoeEpWgradForwardStash",
"MoeEpWgradOperands",
"MoeFormat",
"MoeTensor",
}

_LAZY_OPTIONAL_IMPORTS = {
"moe_ep": (".moe_ep", None),
"BlockScaledTensor": (".moe_ep", "BlockScaledTensor"),
"MoeEp": (".moe_ep", "MoeEp"),
"MoeEpTuningConfig": (".moe_ep", "MoeEpTuningConfig"),
"MoeEpWgradForwardStash": (".moe_ep", "MoeEpWgradForwardStash"),
"MoeEpWgradOperands": (".moe_ep", "MoeEpWgradOperands"),
"MoeFormat": (".moe_ep", "MoeFormat"),
"MoeTensor": (".moe_ep", "MoeTensor"),
"BSA": (".block_sparse_attention", "BSA"),
"block_sparse_attention_forward": (".block_sparse_attention", "block_sparse_attention_forward"),
"block_sparse_attention_backward": (".block_sparse_attention", "block_sparse_attention_backward"),
Expand Down Expand Up @@ -368,7 +391,14 @@ def _load_optional_symbol(name: str) -> Any:
module = importlib.import_module(module_name, package=__name__)
value = module if attr_name is None else getattr(module, attr_name)
except Exception as e:
raise ImportError(f"{name} requires optional dependencies. {_OPTIONAL_DEPENDENCY_INSTALL_HINT}: {e}") from e
install_hint = (
_MOE_EP_INSTALL_HINT
if name in _MOE_EP_OPTIONAL_IMPORTS
else _CUTEDSL_INSTALL_HINT
)
raise ImportError(
f"{name} requires optional dependencies. {install_hint}: {e}"
) from e

globals()[name] = value
return value
Expand Down
22 changes: 22 additions & 0 deletions python/cudnn/moe_ep/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: MIT

from ._tuning import MoeEpTuningConfig
from ._types import (
BlockScaledTensor,
MoeEpWgradForwardStash,
MoeEpWgradOperands,
MoeFormat,
MoeTensor,
)
from .api import MoeEp

__all__ = [
"BlockScaledTensor",
"MoeEp",
"MoeEpTuningConfig",
"MoeEpWgradForwardStash",
"MoeEpWgradOperands",
"MoeFormat",
"MoeTensor",
]
104 changes: 104 additions & 0 deletions python/cudnn/moe_ep/_backend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: MIT

"""Lightweight private backend seam for :class:`cudnn.moe_ep.MoeEp`.

Capability policy and the executable factory are imported lazily through this
backend-neutral seam. Importing :mod:`cudnn` still does not load CuTeDSL or
initialize CUDA.
"""

from __future__ import annotations

from typing import Protocol, Tuple, Union

import torch

from ._contracts import (
ForwardConfig,
ValidatedBackwardRequest,
ValidatedForwardRequest,
)
from ._types import MoeEpWgradForwardStash, MoeEpWgradOperands, MoeTensor


ForwardResult = Union[
MoeTensor,
Tuple[MoeTensor, torch.Tensor, torch.Tensor],
Tuple[
MoeTensor,
torch.Tensor,
torch.Tensor,
MoeEpWgradForwardStash,
],
]
BackwardResult = Union[
Tuple[torch.Tensor, torch.Tensor],
Tuple[torch.Tensor, torch.Tensor, MoeEpWgradOperands],
]


class MoeEpBackend(Protocol):
"""Instance-local backend created lazily for one static ``MoeEp`` config."""

def forward(self, request: ValidatedForwardRequest) -> ForwardResult:
"""Execute one already-validated forward request."""

def backward(self, request: ValidatedBackwardRequest) -> BackwardResult:
"""Execute one already-validated backward request."""

def close(self) -> None:
"""Release backend-owned resources."""


class BackendUnavailableError(RuntimeError):
"""The requested supported path has no executable runtime backend yet."""


def validate_config(config: ForwardConfig) -> None:
"""Run the selected backend's static capability gate lazily."""

from ._megamoe_backend._capability import validate_config as validate

validate(config)


def validate_request(request: ValidatedForwardRequest) -> None:
"""Run the selected backend's per-request capability gate lazily."""

from ._megamoe_backend._capability import validate_request as validate

validate(request)


def validate_backward_request(request: ValidatedBackwardRequest) -> None:
"""Run the selected backend's backward capability gate lazily."""

from ._megamoe_backend._capability import (
validate_backward_request as validate,
)

validate(request)


def create_backend(
config: ForwardConfig,
device: torch.device,
) -> MoeEpBackend:
"""Create the default backend without an allocation-only fallback."""

from ._megamoe_backend.mxfp8._backend import Mxfp8Backend

return Mxfp8Backend(config, device)


__all__ = [
"BackwardResult",
"BackendUnavailableError",
"MoeEpBackend",
"ForwardResult",
"create_backend",
"validate_config",
"validate_backward_request",
"validate_request",
]
78 changes: 78 additions & 0 deletions python/cudnn/moe_ep/_contracts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: MIT

"""Private data contracts shared by the MoE EP API, validation, and backend."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Literal, Optional

import torch

from ._tuning import MoeEpTuningConfig
from ._types import MoeEpWgradForwardStash, MoeTensor


@dataclass(frozen=True)
class ForwardConfig:
"""Static configuration snapshot for one ``MoeEp`` instance."""

num_experts: int
hidden_size: int
intermediate_size: int
top_k: int
experts_per_rank: int
ep_size: int
ep_rank: int
ep_group: Any
ep_global_ranks: tuple[int, ...]
max_tokens_per_rank: Optional[int]
output_format: str
combine_format: str
apply_topk_in_fc1: bool
gate_up_clamp: Optional[float]
generate_c: bool
token_padding_size: int
sf_padding_size: int
tuning: MoeEpTuningConfig
backward_wgrad_mode: Literal["none", "operands"] = "none"


@dataclass(frozen=True)
class ValidatedForwardRequest:
"""Runtime inputs that have passed the public forward contract."""

config: ForwardConfig
activation: MoeTensor
fc1_weight: MoeTensor
fc2_weight: MoeTensor
topk_idx: torch.Tensor
topk_weights: torch.Tensor
token_count: int
device: torch.device


@dataclass(frozen=True)
class ValidatedBackwardRequest:
"""Runtime inputs that have passed the public backward contract."""

config: ForwardConfig
grad_output: torch.Tensor
fc1_weight: MoeTensor
fc2_weight: MoeTensor
topk_idx: torch.Tensor
topk_weights: torch.Tensor
fc1_c: torch.Tensor
route_metadata: torch.Tensor
token_count: int
local_routes: int
device: torch.device
wgrad_forward_stash: Optional[MoeEpWgradForwardStash] = None


__all__ = [
"ForwardConfig",
"ValidatedBackwardRequest",
"ValidatedForwardRequest",
]
Loading
Loading