fix(mega-moe): default NCCL_MAX_CTAS to half the reserved SMs (#4188)
FSDP can run an all-gather and a reduce-scatter at once next to a persistent Mega MoE grid, so both NCCL kernels have to fit in the SMs Mega MoE leaves free. With NCCL_MAX_CTAS equal to num_reserved_sms (the documented 16/16), the two kernels overflow the reservation and deadlock against the Mega MoE grids under full activation checkpointing. The trainer now sets NCCL_MAX_CTAS to num_reserved_sms // 2 (8 by default) before initializing torch distributed when it is unset, and refuses to start when it is set above that. num_reserved_sms must be at least 2. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes distributed startup env and validation for Mega MoE training; mis-set NCCL_MAX_CTAS still fails fast, but default behavior shifts from 16 to 8 CTAs (5 under HSDP). > > **Overview** > Fixes Mega MoE deadlocks when FSDP runs **two** NCCL collectives (all-gather + reduce-scatter) alongside the persistent MoE grids, and **three** under HSDP (`dp_replicate > 1`). > > **`NCCL_MAX_CTAS`** is now derived from how many kernels must fit in `num_reserved_sms`: the trainer calls `default_nccl_max_ctas` via `setup_moe_comm_env` **before** `setup_torch_distributed` in RL and SFT when dispatch is `mega_moe`. If unset, it sets `NCCL_MAX_CTAS` to `num_reserved_sms // 2` (or `// 3` under HSDP); startup fails if the env var is above that cap. `reserve_sms_for_comm` and config/docs/benchmark are aligned with the same concurrent-kernel model; `num_reserved_sms` must be at least **2**. Manual `NCCL_MAX_CTAS=16` in docs/examples is dropped in favor of the default. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 29a7a816fc025b3e35a37960d203771e6683b0d6. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
This commit is contained in:
@@ -3,12 +3,12 @@ bf16 EP path (``TorchTokenDispatcher`` + ``BF16ExpertCompute``) for the same rou
|
||||
workload, weights, and token counts, and check the gradients agree.
|
||||
|
||||
Requires >=2 SM90+ GPUs, PyTorch >= 2.9 (CUDA symmetric memory), and the prime-mega-moe
|
||||
``deep_gemm`` wheel from Prime Intellect installed over the public one. ``NCCL_MAX_CTAS`` must be
|
||||
set to at most the SMs Mega MoE reserves for NCCL (16). ``--hidden`` must be a multiple of 256 and
|
||||
``--intermediate`` a multiple of 128.
|
||||
``deep_gemm`` wheel from Prime Intellect installed over the public one. ``NCCL_MAX_CTAS`` defaults to half
|
||||
the SMs Mega MoE reserves for NCCL (16). ``--hidden`` must be a multiple of 256 and ``--intermediate`` a
|
||||
multiple of 128.
|
||||
|
||||
Usage:
|
||||
NCCL_MAX_CTAS=16 torchrun --nproc_per_node=8 benchmarks/mega_moe/bench_mega_moe.py \
|
||||
torchrun --nproc_per_node=8 benchmarks/mega_moe/bench_mega_moe.py \
|
||||
--num-experts 128 --top-k 8 --hidden 2048 --intermediate 1024 --tokens-per-rank 2048
|
||||
"""
|
||||
|
||||
@@ -20,7 +20,12 @@ import torch.distributed as dist
|
||||
|
||||
from prime_rl.trainer.distributed.token_dispatcher import FusedTokenDispatcher, TorchTokenDispatcher
|
||||
from prime_rl.trainer.models.layers.expert_compute import BF16ExpertCompute
|
||||
from prime_rl.trainer.models.layers.mega_moe import MegaMoEExpertCompute, mega_moe_available, reserve_sms_for_comm
|
||||
from prime_rl.trainer.models.layers.mega_moe import (
|
||||
MegaMoEExpertCompute,
|
||||
default_nccl_max_ctas,
|
||||
mega_moe_available,
|
||||
reserve_sms_for_comm,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts
|
||||
|
||||
|
||||
@@ -58,6 +63,7 @@ def main() -> None:
|
||||
args = parse_args()
|
||||
local_rank = int(os.environ["LOCAL_RANK"])
|
||||
torch.cuda.set_device(local_rank)
|
||||
default_nccl_max_ctas(16, num_concurrent=2)
|
||||
dist.init_process_group(backend="nccl", device_id=torch.device("cuda", local_rank))
|
||||
rank, world_size = dist.get_rank(), dist.get_world_size()
|
||||
group = dist.group.WORLD
|
||||
@@ -108,7 +114,7 @@ def main() -> None:
|
||||
intermediate_hidden=args.intermediate,
|
||||
group=group,
|
||||
max_tokens_per_rank=args.tokens_per_rank,
|
||||
num_sms=reserve_sms_for_comm(16),
|
||||
num_sms=reserve_sms_for_comm(16, num_concurrent=2),
|
||||
)
|
||||
mega = (FusedTokenDispatcher(), mega_compute)
|
||||
|
||||
|
||||
+2
-3
@@ -108,16 +108,15 @@ For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_
|
||||
|
||||
Mega MoE (`type = "mega_moe"`) fuses dispatch, the SwiGLU expert MLP, and combine into one persistent kernel per direction, overlapping the expert-parallel communication with the GEMMs. `precision` selects the expert GEMMs: `bf16` (default, SM90+), `mxfp8` (SM100), `fp8` (blockwise FP8 forward and backward, SM90), or `fp8_bwd` (BF16 forward, blockwise FP8 backward, SM90); `[trainer.model.moe.compute]` does not apply to those layers. The kernels come from prime-mega-moe, Prime Intellect's closed-source DeepGEMM fork, built as a `deep_gemm` wheel that replaces the public one (`uv pip install --no-deps <wheel>` after syncing). Without it, selecting `mega_moe` fails at startup with a message naming the missing kernels. Mega MoE needs EP > 1, nvcc 13 on `CUDA_HOME` for the runtime JIT, gated experts without biases, `hidden_size` divisible by 256 and `moe_intermediate_size` by 128.
|
||||
|
||||
The kernels are persistent grids that synchronize across ranks, so an NCCL kernel on another stream (FSDP all-gathers, gradient reductions) has to fit in the SMs they leave free, or the two deadlock. `num_reserved_sms` is how many SMs they leave free. `NCCL_MAX_CTAS` caps the CTAs (one per SM) a NCCL kernel launches, so the trainer refuses to start unless it is set to at most `num_reserved_sms`. 16 is enough for FSDP's collectives; every reserved SM is taken from the GEMMs, so match the two rather than over-reserving. The symmetric buffer is sized once at startup from `max_tokens_per_rank`, which defaults to the micro batch (`model.seq_len` for RL, `data.micro_batch_size * data.seq_len` for SFT); a smaller value is rejected at startup.
|
||||
The kernels are persistent grids that synchronize across ranks, so an NCCL kernel on another stream (FSDP all-gathers, gradient reductions) has to fit in the SMs they leave free, or the two deadlock. `num_reserved_sms` is how many SMs they leave free. `NCCL_MAX_CTAS` caps the CTAs (one per SM) a NCCL kernel launches. In the worst case each NCCL kernel uses all `NCCL_MAX_CTAS`, so at most `num_reserved_sms // NCCL_MAX_CTAS` NCCL kernels can run concurrently. FSDP overlaps an all-gather and a reduce-scatter, and HSDP (`dp_replicate > 1`) adds an all-reduce, so the trainer sets `NCCL_MAX_CTAS` to `num_reserved_sms // 2` (`// 3` under HSDP) when it is unset, and refuses to start if it is set higher than that. The default 16 reserved SMs (8 CTAs, 5 under HSDP) are enough for FSDP's collectives; every reserved SM is taken from the GEMMs, so raise `num_reserved_sms` only if NCCL needs more. The symmetric buffer is sized once at startup from `max_tokens_per_rank`, which defaults to the micro batch (`model.seq_len` for RL, `data.micro_batch_size * data.seq_len` for SFT); a smaller value is rejected at startup.
|
||||
|
||||
```toml
|
||||
[trainer.model.moe.dispatch]
|
||||
type = "mega_moe"
|
||||
precision = "bf16" # or "mxfp8" (SM100), "fp8" / "fp8_bwd" (SM90)
|
||||
num_reserved_sms = 16 # SMs left free for NCCL; NCCL_MAX_CTAS must be <= this
|
||||
num_reserved_sms = 16 # SMs left free for NCCL; NCCL_MAX_CTAS defaults to this // 2 (// 3 under HSDP)
|
||||
|
||||
[trainer.env_vars]
|
||||
NCCL_MAX_CTAS = "16"
|
||||
CUDA_HOME = "/usr/local/cuda-13.0"
|
||||
PATH = "/usr/local/cuda-13.0/bin:${PATH}"
|
||||
```
|
||||
|
||||
@@ -227,8 +227,11 @@ class MegaMoeMoEDispatchConfig(BaseConfig):
|
||||
"""Tokens per rank per MoE call that the symmetric buffer is sized for. Defaults to the micro batch
|
||||
(``model.seq_len`` for RL, ``data.micro_batch_size * data.seq_len`` for SFT) and cannot be smaller."""
|
||||
|
||||
num_reserved_sms: int = Field(16, ge=1)
|
||||
"""SMs left free for concurrent NCCL kernels. ``NCCL_MAX_CTAS`` must be set to at most this value."""
|
||||
num_reserved_sms: int = Field(16, ge=2)
|
||||
"""SMs left free for concurrent NCCL kernels. In the worst case each NCCL kernel uses all ``NCCL_MAX_CTAS``, so
|
||||
at most ``num_reserved_sms // NCCL_MAX_CTAS`` NCCL kernels can run concurrently. FSDP overlaps an all-gather and
|
||||
a reduce-scatter, and HSDP (``dp_replicate > 1``) adds an all-reduce, so the trainer sets ``NCCL_MAX_CTAS`` to
|
||||
this value divided by 2 (3 under HSDP) when it is unset and requires it to be at most that."""
|
||||
|
||||
|
||||
def mega_moe_max_tokens_per_rank(max_tokens_per_rank: int | None, micro_batch_tokens: int) -> int:
|
||||
|
||||
@@ -63,14 +63,34 @@ def check_mega_moe_dims(hidden: int, intermediate_hidden: int) -> None:
|
||||
)
|
||||
|
||||
|
||||
def reserve_sms_for_comm(num_reserved_sms: int) -> int:
|
||||
"""SMs the Mega MoE grids run on: ``total - num_reserved_sms``"""
|
||||
def num_concurrent_nccl_kernels(dp_replicate: int) -> int:
|
||||
"""NCCL kernels FSDP can run at once: an all-gather and a reduce-scatter, plus an all-reduce under HSDP."""
|
||||
return 3 if dp_replicate > 1 else 2
|
||||
|
||||
|
||||
def default_nccl_max_ctas(num_reserved_sms: int, num_concurrent: int) -> None:
|
||||
"""Set ``NCCL_MAX_CTAS`` to ``num_reserved_sms // num_concurrent`` unless it is already set, then check it. In the
|
||||
worst case each NCCL kernel uses all ``NCCL_MAX_CTAS``, so at most ``num_reserved_sms // NCCL_MAX_CTAS`` can run
|
||||
next to a Mega MoE grid."""
|
||||
os.environ.setdefault("NCCL_MAX_CTAS", str(max(num_reserved_sms // num_concurrent, 1)))
|
||||
check_nccl_max_ctas(num_reserved_sms, num_concurrent)
|
||||
|
||||
|
||||
def check_nccl_max_ctas(num_reserved_sms: int, num_concurrent: int) -> None:
|
||||
"""Raise unless ``num_concurrent`` NCCL kernels of ``NCCL_MAX_CTAS`` CTAs fit in the reserved SMs."""
|
||||
nccl_max_ctas = os.environ.get("NCCL_MAX_CTAS")
|
||||
if nccl_max_ctas is None or int(nccl_max_ctas) > num_reserved_sms:
|
||||
max_ctas = num_reserved_sms // num_concurrent
|
||||
if max_ctas < 1 or nccl_max_ctas is None or not nccl_max_ctas.isdigit() or not 1 <= int(nccl_max_ctas) <= max_ctas:
|
||||
raise ValueError(
|
||||
f"Mega MoE reserves {num_reserved_sms} SMs for NCCL, so `NCCL_MAX_CTAS` must be set to at most "
|
||||
f"{num_reserved_sms} (got {nccl_max_ctas!r}); set it in `env_vars` or raise `num_reserved_sms`."
|
||||
f"Mega MoE reserves {num_reserved_sms} SMs for NCCL, which must fit {num_concurrent} concurrent NCCL "
|
||||
f"kernels, so `NCCL_MAX_CTAS` must be an integer in [1, {max_ctas}] (got {nccl_max_ctas!r}); unset it "
|
||||
f"to use {max_ctas} or raise `num_reserved_sms`."
|
||||
)
|
||||
|
||||
|
||||
def reserve_sms_for_comm(num_reserved_sms: int, num_concurrent: int) -> int:
|
||||
"""SMs the Mega MoE grids run on: ``total - num_reserved_sms``"""
|
||||
check_nccl_max_ctas(num_reserved_sms, num_concurrent)
|
||||
total = torch.cuda.get_device_properties(torch.cuda.current_device()).multi_processor_count
|
||||
return max(total - num_reserved_sms, 1)
|
||||
|
||||
|
||||
@@ -28,13 +28,25 @@ from prime_rl.trainer.models.layers.expert_compute import (
|
||||
ExpertCompute,
|
||||
MXFP8ExpertCompute,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.mega_moe import MegaMoEExpertCompute, reserve_sms_for_comm
|
||||
from prime_rl.trainer.models.layers.mega_moe import (
|
||||
MegaMoEExpertCompute,
|
||||
default_nccl_max_ctas,
|
||||
num_concurrent_nccl_kernels,
|
||||
reserve_sms_for_comm,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.moe import MoE
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.vlm import get_language_model
|
||||
|
||||
|
||||
def setup_moe_comm_env(config: ModelConfig) -> None:
|
||||
"""Environment the MoE dispatch needs before torch distributed creates NCCL communicators."""
|
||||
dispatch = config.moe.dispatch
|
||||
if isinstance(dispatch, MegaMoeMoEDispatchConfig):
|
||||
default_nccl_max_ctas(dispatch.num_reserved_sms, num_concurrent_nccl_kernels(config.dp_replicate))
|
||||
|
||||
|
||||
def _resolve_expert_compute(config: ModelConfig) -> ExpertCompute:
|
||||
compute = config.moe.compute
|
||||
if isinstance(compute, BF16MoEComputeConfig):
|
||||
@@ -64,7 +76,7 @@ def _resolve_expert_compute(config: ModelConfig) -> ExpertCompute:
|
||||
|
||||
|
||||
def _resolve_mega_moe_compute(
|
||||
moe: MoE, dispatch: MegaMoeMoEDispatchConfig, group: ProcessGroup
|
||||
moe: MoE, dispatch: MegaMoeMoEDispatchConfig, group: ProcessGroup, dp_replicate: int
|
||||
) -> MegaMoEExpertCompute:
|
||||
if dispatch.max_tokens_per_rank is None:
|
||||
raise ValueError(
|
||||
@@ -78,7 +90,7 @@ def _resolve_mega_moe_compute(
|
||||
intermediate_hidden=moe.experts.hidden_dim,
|
||||
group=group,
|
||||
max_tokens_per_rank=dispatch.max_tokens_per_rank,
|
||||
num_sms=reserve_sms_for_comm(dispatch.num_reserved_sms),
|
||||
num_sms=reserve_sms_for_comm(dispatch.num_reserved_sms, num_concurrent_nccl_kernels(dp_replicate)),
|
||||
precision=dispatch.precision,
|
||||
)
|
||||
|
||||
@@ -115,7 +127,7 @@ def configure_moe_runtime(model: nn.Module, config: ModelConfig, parallel_dims:
|
||||
)
|
||||
# Mega MoE fuses the expert compute into dispatch, so `model.moe.compute` does not apply to it.
|
||||
selected_moes = set(moe_layers)
|
||||
selected_compute = _resolve_mega_moe_compute(moe_layers[0], dispatch, ep_mesh.get_group())
|
||||
selected_compute = _resolve_mega_moe_compute(moe_layers[0], dispatch, ep_mesh.get_group(), config.dp_replicate)
|
||||
else:
|
||||
selected_compute = _resolve_expert_compute(config) if selected_moes else bf16_compute
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ from prime_rl.trainer.model import (
|
||||
setup_model,
|
||||
setup_processor,
|
||||
)
|
||||
from prime_rl.trainer.moe_runtime import setup_moe_comm_env
|
||||
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
|
||||
from prime_rl.trainer.perf import get_perf_counter
|
||||
from prime_rl.trainer.utils import (
|
||||
@@ -111,6 +112,7 @@ def train(config: TrainerConfig):
|
||||
heart = Heartbeat(config.heartbeat)
|
||||
|
||||
# Set precision
|
||||
setup_moe_comm_env(config.model)
|
||||
setup_torch_distributed(
|
||||
timeout=timedelta(seconds=config.dist_timeout_seconds),
|
||||
enable_gloo=config.model.offload == "full",
|
||||
|
||||
@@ -35,6 +35,7 @@ from prime_rl.trainer.model import (
|
||||
setup_tokenizer,
|
||||
setup_model,
|
||||
)
|
||||
from prime_rl.trainer.moe_runtime import setup_moe_comm_env
|
||||
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
|
||||
from prime_rl.trainer.perf import get_perf_counter
|
||||
from prime_rl.trainer.sft.data import (
|
||||
@@ -100,6 +101,7 @@ def train(config: SFTConfig):
|
||||
heart = Heartbeat(config.heartbeat)
|
||||
|
||||
# Set precision
|
||||
setup_moe_comm_env(config.model)
|
||||
setup_torch_distributed(
|
||||
timeout=timedelta(seconds=config.dist_timeout_seconds),
|
||||
enable_gloo=config.model.offload == "full",
|
||||
|
||||
Reference in New Issue
Block a user