Draft
[WIP]dev_npu_async #3
&NewgateAdd on 22 days ago
[WIP]dev_npu_async #3
Draft
&NewgateAdd on 22 days ago
Total: 51 files changed+6580-349
@@ -1,64 +1,83 @@
1# Copyright (c) 2025; NVIDIA CORPORATION. All rights reserved.1# Copyright (c) 2025; NVIDIA CORPORATION. All rights reserved.
2# Copyright (c) 2025, Huawei Technologies Co., Ltd. All rights reserved.2# Copyright (c) 2025, Huawei Technologies Co., Ltd. All rights reserved.
3 3 
4-# ruff: noqa4+"""Preserve shared MoE exports without loading training backends on package import."""
5-from megatron.core import parallel_state, tensor_parallel, InferenceParams
6-from megatron.core.transformer.moe.moe_utils import MoEAuxLossAutoScaler
7-from megatron.core.transformer.moe.router import TopKRouter
8-from megatron.core.transformer.module import MegatronModule
9-from megatron.core.transformer.mlp import MLPSubmodules, MLP
10-from megatron.core.transformer.transformer_config import TransformerConfig
11-from megatron.core.transformer.spec_utils import build_module, ModuleSpec
12-from megatron.core.transformer.moe.moe_utils import (
13- permute,
14- unpermute,
15- save_to_aux_losses_tracker,
16- sort_chunks_by_idxs,
17- get_capacity,
18- maybe_move_tensor_to_cpu,
19-)
20-from megatron.core.tensor_parallel.layers import (
21- _initialize_affine_weight_cpu,
22- _initialize_affine_weight_gpu,
23- linear_with_grad_accumulation_and_async_allreduce,
24- linear_with_frozen_weight,
25-)
26-from megatron.core.tensor_parallel.mappings import (
27- copy_to_tensor_model_parallel_region,
28- gather_from_tensor_model_parallel_region,
29- reduce_from_tensor_model_parallel_region,
30- reduce_scatter_to_sequence_parallel_region,
31- scatter_to_tensor_model_parallel_region,
32- _reduce_scatter_along_first_dim,
33- _gather_along_first_dim,
34- _split_along_first_dim,
35- scatter_to_sequence_parallel_region,
36- all_gather_last_dim_from_tensor_parallel_region,
37-)
38-from megatron.core.tensor_parallel.utils import VocabUtility, divide, split_tensor_along_last_dim
39-from megatron.core.utils import make_tp_sharded_tensor_for_checkpoint, prepare_input_tensors_for_wgrad_compute
40-from megatron.core.transformer.utils import make_sharded_tensors_for_checkpoint
41-from megatron.core.model_parallel_config import ModelParallelConfig
42-from megatron.core.parallel_state import (
43- get_global_memory_buffer,
44- get_tensor_model_parallel_group,
45- get_tensor_model_parallel_rank,
46- get_tensor_model_parallel_world_size,
47-)
48-from megatron.core.tensor_parallel import gather_from_sequence_parallel_region
49-from megatron.core.transformer.multi_token_prediction import MultiTokenPredictionBlockSubmodules
50-from megatron.core.transformer.moe.moe_layer import MoELayer, BaseMoELayer as MegatronBaseMoeLayer
51-from megatron.core.transformer.moe.shared_experts import SharedExpertMLP, set_tensor_grad_fn_sequence_sr
52-from megatron.core.transformer.moe.token_dispatcher import MoEAlltoAllTokenDispatcher
53-from megatron.core.transformer.moe.token_dispatcher import MoEAllGatherTokenDispatcher
54-from megatron.core.packed_seq_params import PackedSeqParams
55-from megatron.core.utils import make_viewless_tensor
56-from megatron.core.inference.contexts import BaseInferenceContext
57-from megatron.core.fusions.fused_bias_geglu import bias_geglu_impl
58-from megatron.core.fusions.fused_bias_gelu import bias_gelu_impl
59-from megatron.core.fusions.fused_bias_swiglu import bias_swiglu_impl
60 5 
61-from mindspeed.core.transformer.moe import grouped_gemm_util6+# MoonEP contract/config imports must remain usable before Megatron/NPU bootstrap.
62-from mindspeed.core.transformer.moe.grouped_mlp import GroupedMLP7+_EXPORTS = {
63-from mindspeed.core.transformer.moe.moe_utils import topk_softmax_with_capacity8+ 'parallel_state': ('megatron.core', 'parallel_state'),
64-from mindspeed.args_utils import get_full_args as get_args9+ 'tensor_parallel': ('megatron.core', 'tensor_parallel'),
10+ 'InferenceParams': ('megatron.core', 'InferenceParams'),
11+ 'MoEAuxLossAutoScaler': ('megatron.core.transformer.moe.moe_utils', 'MoEAuxLossAutoScaler'),
12+ 'TopKRouter': ('megatron.core.transformer.moe.router', 'TopKRouter'),
13+ 'MegatronModule': ('megatron.core.transformer.module', 'MegatronModule'),
14+ 'MLPSubmodules': ('megatron.core.transformer.mlp', 'MLPSubmodules'),
15+ 'MLP': ('megatron.core.transformer.mlp', 'MLP'),
16+ 'TransformerConfig': ('megatron.core.transformer.transformer_config', 'TransformerConfig'),
17+ 'build_module': ('megatron.core.transformer.spec_utils', 'build_module'),
18+ 'ModuleSpec': ('megatron.core.transformer.spec_utils', 'ModuleSpec'),
19+ 'permute': ('megatron.core.transformer.moe.moe_utils', 'permute'),
20+ 'unpermute': ('megatron.core.transformer.moe.moe_utils', 'unpermute'),
21+ 'save_to_aux_losses_tracker': ('megatron.core.transformer.moe.moe_utils', 'save_to_aux_losses_tracker'),
22+ 'sort_chunks_by_idxs': ('megatron.core.transformer.moe.moe_utils', 'sort_chunks_by_idxs'),
23+ 'get_capacity': ('megatron.core.transformer.moe.moe_utils', 'get_capacity'),
24+ 'maybe_move_tensor_to_cpu': ('megatron.core.transformer.moe.moe_utils', 'maybe_move_tensor_to_cpu'),
25+ '_initialize_affine_weight_cpu': ('megatron.core.tensor_parallel.layers', '_initialize_affine_weight_cpu'),
26+ '_initialize_affine_weight_gpu': ('megatron.core.tensor_parallel.layers', '_initialize_affine_weight_gpu'),
27+ 'linear_with_grad_accumulation_and_async_allreduce': ('megatron.core.tensor_parallel.layers', 'linear_with_grad_accumulation_and_async_allreduce'),
28+ 'linear_with_frozen_weight': ('megatron.core.tensor_parallel.layers', 'linear_with_frozen_weight'),
29+ 'copy_to_tensor_model_parallel_region': ('megatron.core.tensor_parallel.mappings', 'copy_to_tensor_model_parallel_region'),
30+ 'gather_from_tensor_model_parallel_region': ('megatron.core.tensor_parallel.mappings', 'gather_from_tensor_model_parallel_region'),
31+ 'reduce_from_tensor_model_parallel_region': ('megatron.core.tensor_parallel.mappings', 'reduce_from_tensor_model_parallel_region'),
32+ 'reduce_scatter_to_sequence_parallel_region': ('megatron.core.tensor_parallel.mappings', 'reduce_scatter_to_sequence_parallel_region'),
33+ 'scatter_to_tensor_model_parallel_region': ('megatron.core.tensor_parallel.mappings', 'scatter_to_tensor_model_parallel_region'),
34+ '_reduce_scatter_along_first_dim': ('megatron.core.tensor_parallel.mappings', '_reduce_scatter_along_first_dim'),
35+ '_gather_along_first_dim': ('megatron.core.tensor_parallel.mappings', '_gather_along_first_dim'),
36+ '_split_along_first_dim': ('megatron.core.tensor_parallel.mappings', '_split_along_first_dim'),
37+ 'scatter_to_sequence_parallel_region': ('megatron.core.tensor_parallel.mappings', 'scatter_to_sequence_parallel_region'),
38+ 'all_gather_last_dim_from_tensor_parallel_region': ('megatron.core.tensor_parallel.mappings', 'all_gather_last_dim_from_tensor_parallel_region'),
39+ 'VocabUtility': ('megatron.core.tensor_parallel.utils', 'VocabUtility'),
40+ 'divide': ('megatron.core.tensor_parallel.utils', 'divide'),
41+ 'split_tensor_along_last_dim': ('megatron.core.tensor_parallel.utils', 'split_tensor_along_last_dim'),
42+ 'make_tp_sharded_tensor_for_checkpoint': ('megatron.core.utils', 'make_tp_sharded_tensor_for_checkpoint'),
43+ 'prepare_input_tensors_for_wgrad_compute': ('megatron.core.utils', 'prepare_input_tensors_for_wgrad_compute'),
44+ 'make_sharded_tensors_for_checkpoint': ('megatron.core.transformer.utils', 'make_sharded_tensors_for_checkpoint'),
45+ 'ModelParallelConfig': ('megatron.core.model_parallel_config', 'ModelParallelConfig'),
46+ 'get_global_memory_buffer': ('megatron.core.parallel_state', 'get_global_memory_buffer'),
47+ 'get_tensor_model_parallel_group': ('megatron.core.parallel_state', 'get_tensor_model_parallel_group'),
48+ 'get_tensor_model_parallel_rank': ('megatron.core.parallel_state', 'get_tensor_model_parallel_rank'),
49+ 'get_tensor_model_parallel_world_size': ('megatron.core.parallel_state', 'get_tensor_model_parallel_world_size'),
50+ 'gather_from_sequence_parallel_region': ('megatron.core.tensor_parallel', 'gather_from_sequence_parallel_region'),
51+ 'MultiTokenPredictionBlockSubmodules': ('megatron.core.transformer.multi_token_prediction', 'MultiTokenPredictionBlockSubmodules'),
52+ 'MoELayer': ('megatron.core.transformer.moe.moe_layer', 'MoELayer'),
53+ 'MegatronBaseMoeLayer': ('megatron.core.transformer.moe.moe_layer', 'BaseMoELayer'),
54+ 'SharedExpertMLP': ('megatron.core.transformer.moe.shared_experts', 'SharedExpertMLP'),
55+ 'set_tensor_grad_fn_sequence_sr': ('megatron.core.transformer.moe.shared_experts', 'set_tensor_grad_fn_sequence_sr'),
56+ 'MoEAlltoAllTokenDispatcher': ('megatron.core.transformer.moe.token_dispatcher', 'MoEAlltoAllTokenDispatcher'),
57+ 'MoEAllGatherTokenDispatcher': ('megatron.core.transformer.moe.token_dispatcher', 'MoEAllGatherTokenDispatcher'),
58+ 'PackedSeqParams': ('megatron.core.packed_seq_params', 'PackedSeqParams'),
59+ 'make_viewless_tensor': ('megatron.core.utils', 'make_viewless_tensor'),
60+ 'BaseInferenceContext': ('megatron.core.inference.contexts', 'BaseInferenceContext'),
61+ 'bias_geglu_impl': ('megatron.core.fusions.fused_bias_geglu', 'bias_geglu_impl'),
62+ 'bias_gelu_impl': ('megatron.core.fusions.fused_bias_gelu', 'bias_gelu_impl'),
63+ 'bias_swiglu_impl': ('megatron.core.fusions.fused_bias_swiglu', 'bias_swiglu_impl'),
64+ 'grouped_gemm_util': ('mindspeed.core.transformer.moe', 'grouped_gemm_util'),
65+ 'GroupedMLP': ('mindspeed.core.transformer.moe.grouped_mlp', 'GroupedMLP'),
66+ 'topk_softmax_with_capacity': ('mindspeed.core.transformer.moe.moe_utils', 'topk_softmax_with_capacity'),
67+ 'get_args': ('mindspeed.args_utils', 'get_full_args'),
68+}
69+ 
70+__all__ = tuple(name for name in _EXPORTS if not name.startswith('_'))
71+ 
72+ 
73+def __getattr__(name):
74+ if name not in _EXPORTS:
75+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
76+ module, attribute = _EXPORTS[name]
77+ value = getattr(__import__(module, fromlist=[attribute]), attribute)
78+ globals()[name] = value
79+ return value
80+ 
81+ 
82+def __dir__():
83+ return sorted(set(globals()) | set(_EXPORTS))
@@ -1,4 +1,20 @@
1-from .modules.layers import linear_backward_wgrad_detach1+"""Lazy original FB exports; shared helpers do not bootstrap a scheduler."""
2-from .transformer_layer import transformer_layer_forward_backward_overlaping, dualpipev_fb_overlap_mtp_layer_forward2+from importlib import import_module as _import_module
3-from .transformer_block import transformer_block_fb_overlap_init_wrapper, mtp_block_fb_overlap_forward_wrapper3+ 
4-from .vpp_schedules import forward_backward_pipelining_with_interleaving4+_EXPORTS = {
5+ 'linear_backward_wgrad_detach': ('.modules.layers', 'linear_backward_wgrad_detach'),
6+ 'transformer_layer_forward_backward_overlaping': ('.transformer_layer', 'transformer_layer_forward_backward_overlaping'),
7+ 'dualpipev_fb_overlap_mtp_layer_forward': ('.transformer_layer', 'dualpipev_fb_overlap_mtp_layer_forward'),
8+ 'transformer_block_fb_overlap_init_wrapper': ('.transformer_block', 'transformer_block_fb_overlap_init_wrapper'),
9+ 'mtp_block_fb_overlap_forward_wrapper': ('.transformer_block', 'mtp_block_fb_overlap_forward_wrapper'),
10+ 'forward_backward_pipelining_with_interleaving': ('.vpp_schedules', 'forward_backward_pipelining_with_interleaving'),
11+}
12+__all__ = tuple(_EXPORTS)
13+ 
14+def __getattr__(name):
15+ if name not in _EXPORTS:
16+ raise AttributeError(name)
17+ module, attribute = _EXPORTS[name]
18+ value = getattr(_import_module(module, __name__), attribute)
19+ globals()[name] = value
20+ return value
@@ -30,6 +30,13 @@ def launch_async_all2all_hook(_):
30 launch_async_all2all()30 launch_async_all2all()
31 31 
32 32 
33+def has_standalone_norm(norm):
34+ from megatron.core.transformer.identity_op import IdentityOp
35+ from torch.nn import Identity
36+ 
37+ return not isinstance(norm, (Identity, IdentityOp))
38+ 
39+ 
33def attention_forward(40def attention_forward(
34 self,41 self,
35 hidden_states,42 hidden_states,
@@ -59,6 +66,8 @@ def attention_forward(
59 input_layernorm_output = input_layernorm_output.float()66 input_layernorm_output = input_layernorm_output.float()
60 return input_layernorm_output67 return input_layernorm_output
61 68 
69+ # An identity norm aliases the live residual, so its storage cannot be discarded.
70+ recompute_norm = recompute_norm and has_standalone_norm(self.input_layernorm)
62 if recompute_norm:71 if recompute_norm:
63 self.norm_ckpt1 = CheckpointWithoutOutput()72 self.norm_ckpt1 = CheckpointWithoutOutput()
64 input_layernorm_output = self.norm_ckpt1.checkpoint(pre_norm, False, hidden_states)73 input_layernorm_output = self.norm_ckpt1.checkpoint(pre_norm, False, hidden_states)
@@ -16,6 +16,16 @@ from mindspeed.core.transformer.moe.comm_utils import async_all_to_all, async_al
16PREMUTE_FINISH_EVENT = None16PREMUTE_FINISH_EVENT = None
17 17 
18 18 
19+def _unpermute_expert_outputs(tokens, indices, *, restore_shape, routing_map, fused, drop_and_pad):
20+ """Restore the already-weighted expert rows returned by the FB combine communication."""
21+ if fused:
22+ return unpermute(
23+ tokens, indices, restore_shape=restore_shape, routing_map=routing_map, fused=True, drop_and_pad=drop_and_pad
24+ )
25+ output = tokens.new_zeros(restore_shape)
26+ return output.scatter_add_(0, indices.unsqueeze(1).expand_as(tokens), tokens)
27+ 
28+ 
19class MindSpeedMOEAlltoAllFbOverlapTokenDispatcher(MoEAlltoAllTokenDispatcher):29class MindSpeedMOEAlltoAllFbOverlapTokenDispatcher(MoEAlltoAllTokenDispatcher):
20 OVERLAP_STREAM = None30 OVERLAP_STREAM = None
21 31 
@@ -490,7 +500,7 @@ class MindSpeedMOEAlltoAllFbOverlapTokenDispatcher(MoEAlltoAllTokenDispatcher):
490 500 
491 def token_unpermute2(self, permutated_local_input_tokens):501 def token_unpermute2(self, permutated_local_input_tokens):
492 # Unpermutation 1: AlltoAll output to output502 # Unpermutation 1: AlltoAll output to output
493- output = unpermute(503+ output = _unpermute_expert_outputs(
494 permutated_local_input_tokens,504 permutated_local_input_tokens,
495 self.reversed_local_input_permutation_mapping,505 self.reversed_local_input_permutation_mapping,
496 restore_shape=self.hidden_shape_before_permute,506 restore_shape=self.hidden_shape_before_permute,
@@ -72,6 +72,12 @@ class NoopLayerGraph:
72 self.is_moe_layer = False72 self.is_moe_layer = False
73 self.layer = layer73 self.layer = layer
74 74 
75+ def set_output_boundary(self, detached_output):
76+ self.unperm2_graph = (self.unperm2_graph[0], detached_output)
77+ 
78+ def get_output_boundary(self):
79+ return self.unperm2_graph[1]
80+ 
75 def record_layer_inputs(self, *args):81 def record_layer_inputs(self, *args):
76 self.layer_inputs = args82 self.layer_inputs = args
77 83 
@@ -87,6 +93,7 @@ class LayerGraph:
87 hot_expert_inter_ep_grad_reduce_handles=None,93 hot_expert_inter_ep_grad_reduce_handles=None,
88 params=None,94 params=None,
89 ):95 ):
96+ self.backend = 'a2a'
90 args = get_full_args()97 args = get_full_args()
91 if not checkpointed:98 if not checkpointed:
92 self.attn_graph = saved_graph_and_graph_inputs[0]99 self.attn_graph = saved_graph_and_graph_inputs[0]
@@ -133,6 +140,12 @@ class LayerGraph:
133 self.act_ckpt_manager = None140 self.act_ckpt_manager = None
134 self.remote_hot_act_ckpt_manager = None141 self.remote_hot_act_ckpt_manager = None
135 142 
143+ def set_output_boundary(self, detached_output):
144+ self.unperm2_graph = (self.unperm2_graph[0], detached_output)
145+ 
146+ def get_output_boundary(self):
147+ return self.unperm2_graph[1]
148+ 
136 def record_layer_inputs(self, *args):149 def record_layer_inputs(self, *args):
137 self.layer_inputs = args150 self.layer_inputs = args
138 151 
@@ -167,7 +167,7 @@ class WeightGradStore:
167 cls._pop_te_linears()167 cls._pop_te_linears()
168 return168 return
169 169 
170- if cls.gather_stream is None:170+ if cls.gather_stream is None and any(row[3] for row in cls.cache):
171 cls.gather_stream = torch_npu.npu.Stream(device=torch.npu.current_device())171 cls.gather_stream = torch_npu.npu.Stream(device=torch.npu.current_device())
172 172 
173 (input_, grad_output_slice, weight, sequence_parallel, in_row), handle = cls.overlap_all_gather()173 (input_, grad_output_slice, weight, sequence_parallel, in_row), handle = cls.overlap_all_gather()
@@ -94,7 +94,7 @@ def forward_backward_no_pipelining(
94 model_graph[-1].mlp_mhc_post_graph[1].grad94 model_graph[-1].mlp_mhc_post_graph[1].grad
95 ) # get final_layernorm input_tensor.grad95 ) # get final_layernorm input_tensor.grad
96 else:96 else:
97- output_tensor_grad = model_graph[-1].unperm2_graph[1].grad # get final_layernorm input_tensor.grad97+ output_tensor_grad = model_graph[-1].get_output_boundary().grad # get final_layernorm input_tensor.grad
98 98 
99 # prepare FBOverlap kwargs for next forward_step99 # prepare FBOverlap kwargs for next forward_step
100 fb_overlap_kwargs = {100 fb_overlap_kwargs = {
@@ -132,7 +132,7 @@ def forward_backward_no_pipelining(
132 if getattr(args, 'enable_mhc', False):132 if getattr(args, 'enable_mhc', False):
133 output_tensor_grad = model_graph[-1].mlp_mhc_post_graph[1].grad # get final_layernorm input_tensor.grad133 output_tensor_grad = model_graph[-1].mlp_mhc_post_graph[1].grad # get final_layernorm input_tensor.grad
134 else:134 else:
135- output_tensor_grad = model_graph[-1].unperm2_graph[1].grad # get final_layernorm input_tensor.grad135+ output_tensor_grad = model_graph[-1].get_output_boundary().grad # get final_layernorm input_tensor.grad
136 136 
137 backward_step(input_tensor, output_tensor, output_tensor_grad, config, model_graph)137 backward_step(input_tensor, output_tensor, output_tensor_grad, config, model_graph)
138 138 
@@ -7,7 +7,7 @@ from torch import Tensor
7from megatron.core.utils import make_viewless_tensor7from megatron.core.utils import make_viewless_tensor
8from mindspeed.args_utils import get_full_args8from mindspeed.args_utils import get_full_args
9from mindspeed.core.tensor_parallel.random import CheckpointWithoutOutput9from mindspeed.core.tensor_parallel.random import CheckpointWithoutOutput
10-from ..modules.attention import attention_forward10+from ..modules.attention import attention_forward, has_standalone_norm
11from ..modules.utils import (11from ..modules.utils import (
12 detach_tensor,12 detach_tensor,
13 NoopLayerGraph,13 NoopLayerGraph,
@@ -299,7 +299,7 @@ def transformer_layer_forward_dense(
299):299):
300 # hidden_states: [s, b, h]300 # hidden_states: [s, b, h]
301 args = get_full_args()301 args = get_full_args()
302- recomp_norm = getattr(args, 'recompute_norm', False)302+ recomp_norm = not checkpoint and torch.is_grad_enabled() and getattr(args, 'recompute_norm', False)
303 303 
304 detached_layer_input = hidden_states304 detached_layer_input = hidden_states
305 305 
@@ -326,7 +326,8 @@ def transformer_layer_forward_dense(
326 # Residual connection.326 # Residual connection.
327 residual2 = detached_attention_out327 residual2 = detached_attention_out
328 328 
329- if recomp_norm:329+ recomp_mlp_norm = recomp_norm and has_standalone_norm(self.pre_mlp_layernorm)
330+ if recomp_mlp_norm:
330 self.norm_ckpt2 = CheckpointWithoutOutput()331 self.norm_ckpt2 = CheckpointWithoutOutput()
331 pre_mlp_layernorm_output = self.norm_ckpt2.checkpoint(self.pre_mlp_layernorm, False, detached_attention_out)332 pre_mlp_layernorm_output = self.norm_ckpt2.checkpoint(self.pre_mlp_layernorm, False, detached_attention_out)
332 else:333 else:
@@ -336,7 +337,7 @@ def transformer_layer_forward_dense(
336 detached_mlp_input = detach_tensor(pre_mlp_layernorm_output, checkpoint_forward=checkpoint)337 detached_mlp_input = detach_tensor(pre_mlp_layernorm_output, checkpoint_forward=checkpoint)
337 mlp_output_with_bias = self.mlp(detached_mlp_input)338 mlp_output_with_bias = self.mlp(detached_mlp_input)
338 339 
339- if recomp_norm:340+ if recomp_mlp_norm:
340 self.norm_ckpt2.discard_output()341 self.norm_ckpt2.discard_output()
341 if mlp_output_with_bias[0].requires_grad:342 if mlp_output_with_bias[0].requires_grad:
342 mlp_output_with_bias[0].register_hook(self.norm_ckpt2.recompute)343 mlp_output_with_bias[0].register_hook(self.norm_ckpt2.recompute)
@@ -13,7 +13,7 @@ from mindspeed.core.transformer.moe.moe_feature import permute
13from mindspeed.core.transformer.moe.comm_utils import async_all_to_all13from mindspeed.core.transformer.moe.comm_utils import async_all_to_all
14from mindspeed.core.tensor_parallel.random import CheckpointWithoutOutput14from mindspeed.core.tensor_parallel.random import CheckpointWithoutOutput
15from ..modules.weight_grad_store import WeightGradStore15from ..modules.weight_grad_store import WeightGradStore
16-from ..modules.attention import attention_forward, set_async_alltoall_inputs, get_async_alltoall_outputs16+from ..modules.attention import attention_forward, has_standalone_norm, set_async_alltoall_inputs, get_async_alltoall_outputs
17from ..modules.utils import (17from ..modules.utils import (
18 detach_tensor,18 detach_tensor,
19 run_graph_backward,19 run_graph_backward,
@@ -713,7 +713,7 @@ def transformer_layer_forward_dense_backward_dense_overlaping(
713 checkpoint_context = nullcontext()713 checkpoint_context = nullcontext()
714 args = get_full_args()714 args = get_full_args()
715 ep_group = parallel_state.get_expert_model_parallel_group()715 ep_group = parallel_state.get_expert_model_parallel_group()
716- recomp_norm = getattr(args, 'recompute_norm', False)716+ recomp_norm = not checkpoint and torch.is_grad_enabled() and getattr(args, 'recompute_norm', False)
717 if bwd_layer_graph.attn_swap_managers:717 if bwd_layer_graph.attn_swap_managers:
718 for manager in bwd_layer_graph.attn_swap_managers:718 for manager in bwd_layer_graph.attn_swap_managers:
719 manager.async_swap_in(wait_stream=torch.npu.current_stream())719 manager.async_swap_in(wait_stream=torch.npu.current_stream())
@@ -744,7 +744,8 @@ def transformer_layer_forward_dense_backward_dense_overlaping(
744 # Residual connection.744 # Residual connection.
745 residual2 = detached_attention_out745 residual2 = detached_attention_out
746 746 
747- if recomp_norm:747+ recomp_mlp_norm = recomp_norm and has_standalone_norm(fwd_layer.pre_mlp_layernorm)
748+ if recomp_mlp_norm:
748 fwd_layer.norm_ckpt2 = CheckpointWithoutOutput()749 fwd_layer.norm_ckpt2 = CheckpointWithoutOutput()
749 pre_mlp_layernorm_output = fwd_layer.norm_ckpt2.checkpoint(750 pre_mlp_layernorm_output = fwd_layer.norm_ckpt2.checkpoint(
750 fwd_layer.pre_mlp_layernorm, False, detached_attention_out751 fwd_layer.pre_mlp_layernorm, False, detached_attention_out
@@ -755,7 +756,7 @@ def transformer_layer_forward_dense_backward_dense_overlaping(
755 # MLP.756 # MLP.
756 detached_mlp_input = detach_tensor(pre_mlp_layernorm_output, checkpoint_forward=checkpoint)757 detached_mlp_input = detach_tensor(pre_mlp_layernorm_output, checkpoint_forward=checkpoint)
757 mlp_output_with_bias = fwd_layer.mlp(detached_mlp_input)758 mlp_output_with_bias = fwd_layer.mlp(detached_mlp_input)
758- if recomp_norm:759+ if recomp_mlp_norm:
759 fwd_layer.norm_ckpt2.discard_output()760 fwd_layer.norm_ckpt2.discard_output()
760 mlp_output_with_bias[0].register_hook(fwd_layer.norm_ckpt2.recompute)761 mlp_output_with_bias[0].register_hook(fwd_layer.norm_ckpt2.recompute)
761 762 
@@ -179,6 +179,7 @@ def transformer_block_forward(
179 padding_mask: Tensor = None,179 padding_mask: Tensor = None,
180 inference_params: Optional[BaseInferenceContext] = None,180 inference_params: Optional[BaseInferenceContext] = None,
181 input_ids: Tensor = None,181 input_ids: Tensor = None,
182+ checkpoint_activations_microbatch: bool = False,
182):183):
183 args = get_args()184 args = get_args()
184 if not self.pre_process:185 if not self.pre_process:
@@ -214,7 +215,7 @@ def transformer_block_forward(
214 215 
215 with rng_context, fp8_context:216 with rng_context, fp8_context:
216 for l_no, layer in enumerate(self.layers):217 for l_no, layer in enumerate(self.layers):
217- checkpoint = False218+ checkpoint = bool(checkpoint_activations_microbatch)
218 if self.config.recompute_granularity == 'full' and self.training:219 if self.config.recompute_granularity == 'full' and self.training:
219 if self.config.recompute_method == 'block':220 if self.config.recompute_method == 'block':
220 recompute_skip_num_layers = 0221 recompute_skip_num_layers = 0
@@ -223,7 +224,7 @@ def transformer_block_forward(
223 if recompute_skip_num_layers <= l_no < self.config.recompute_num_layers + recompute_skip_num_layers:224 if recompute_skip_num_layers <= l_no < self.config.recompute_num_layers + recompute_skip_num_layers:
224 checkpoint = True225 checkpoint = True
225 if self.config.recompute_method == 'uniform':226 if self.config.recompute_method == 'uniform':
226- assert self.config.recompute_num_layers == 1227+ assert self.config.recompute_num_layers > 0
227 checkpoint = True228 checkpoint = True
228 if not (self.pre_process and l_no == 0):229 if not (self.pre_process and l_no == 0):
229 hidden_states = detach_tensor(hidden_states, checkpoint_forward=checkpoint)230 hidden_states = detach_tensor(hidden_states, checkpoint_forward=checkpoint)
@@ -250,7 +251,7 @@ def transformer_block_forward(
250 if getattr(args, 'enable_mhc', False):251 if getattr(args, 'enable_mhc', False):
251 layer_graphs[-1].mlp_mhc_post_graph = (layer_graphs[-1].mlp_mhc_post_graph[0], detached_hidden_states)252 layer_graphs[-1].mlp_mhc_post_graph = (layer_graphs[-1].mlp_mhc_post_graph[0], detached_hidden_states)
252 else:253 else:
253- layer_graphs[-1].unperm2_graph = (layer_graphs[-1].unperm2_graph[0], detached_hidden_states)254+ layer_graphs[-1].set_output_boundary(detached_hidden_states)
254 hidden_states = self.final_layernorm(detached_hidden_states)255 hidden_states = self.final_layernorm(detached_hidden_states)
255 256 
256 if torch.is_grad_enabled() or get_args().schedules_method == 'dualpipev':257 if torch.is_grad_enabled() or get_args().schedules_method == 'dualpipev':
@@ -280,7 +281,10 @@ def transformer_block_forward_backward_overlaping(
280 pp_comm_params: P2PCommParams = None,281 pp_comm_params: P2PCommParams = None,
281 bwd_pp_comm_params: P2PCommParams = None,282 bwd_pp_comm_params: P2PCommParams = None,
282 input_ids: Tensor = None,283 input_ids: Tensor = None,
284+ checkpoint_activations_microbatch: bool = False,
283):285):
286+ if bwd_block_graphs is not None and not isinstance(bwd_block_graphs, list):
287+ bwd_block_graphs = list(bwd_block_graphs)
284 args = get_args()288 args = get_args()
285 if bwd_block_graphs is None:289 if bwd_block_graphs is None:
286 return transformer_block_forward(290 return transformer_block_forward(
@@ -300,10 +304,9 @@ def transformer_block_forward_backward_overlaping(
300 padding_mask=padding_mask,304 padding_mask=padding_mask,
301 inference_params=inference_params,305 inference_params=inference_params,
302 input_ids=input_ids,306 input_ids=input_ids,
307+ checkpoint_activations_microbatch=checkpoint_activations_microbatch,
303 )308 )
304 309 
305- if not isinstance(bwd_block_graphs, list):
306- bwd_block_graphs = list(bwd_block_graphs)
307 unbalanced_block_graphs = len(bwd_block_graphs) != len(self.layers)310 unbalanced_block_graphs = len(bwd_block_graphs) != len(self.layers)
308 pp_comm_output = P2PCommOutput()311 pp_comm_output = P2PCommOutput()
309 312 
@@ -345,7 +348,7 @@ def transformer_block_forward_backward_overlaping(
345 fwd_hidden_states, fwd_context = hidden_states, context348 fwd_hidden_states, fwd_context = hidden_states, context
346 with rng_context, fp8_context:349 with rng_context, fp8_context:
347 for l_no, fwd_layer in enumerate(fwd_block.layers):350 for l_no, fwd_layer in enumerate(fwd_block.layers):
348- checkpoint = False351+ checkpoint = bool(checkpoint_activations_microbatch)
349 if fwd_block.config.recompute_granularity == 'full' and fwd_block.training:352 if fwd_block.config.recompute_granularity == 'full' and fwd_block.training:
350 if fwd_block.config.recompute_method == 'block':353 if fwd_block.config.recompute_method == 'block':
351 recompute_skip_num_layers = 0354 recompute_skip_num_layers = 0
@@ -358,7 +361,7 @@ def transformer_block_forward_backward_overlaping(
358 ):361 ):
359 checkpoint = True362 checkpoint = True
360 if fwd_block.config.recompute_method == 'uniform':363 if fwd_block.config.recompute_method == 'uniform':
361- assert fwd_block.config.recompute_num_layers == 1364+ assert fwd_block.config.recompute_num_layers > 0
362 checkpoint = True365 checkpoint = True
363 bwd_layer_graph = bwd_block_graphs.pop(-1) if bwd_block_graphs else None366 bwd_layer_graph = bwd_block_graphs.pop(-1) if bwd_block_graphs else None
364 cur_p2p_params = pp_comm_params367 cur_p2p_params = pp_comm_params
@@ -425,7 +428,7 @@ def transformer_block_forward_backward_overlaping(
425 detached_hidden_states,428 detached_hidden_states,
426 )429 )
427 else:430 else:
428- fwd_layer_graphs[-1].unperm2_graph = (fwd_layer_graphs[-1].unperm2_graph[0], detached_hidden_states)431+ fwd_layer_graphs[-1].set_output_boundary(detached_hidden_states)
429 432 
430 fwd_hidden_states = fwd_block.final_layernorm(detached_hidden_states)433 fwd_hidden_states = fwd_block.final_layernorm(detached_hidden_states)
431 434 
@@ -453,11 +456,17 @@ def transformer_block_forward_backward_overlaping(
453 return fwd_hidden_states456 return fwd_hidden_states
454 457 
455 458 
456-def transformer_block_backward(block_output_grad, layer_graphs: List[LayerGraph]):459+def transformer_block_backward(
460+ block_output_grad,
461+ layer_graphs: List[LayerGraph],
462+ *,
463+ layer_backward=None,
464+):
465+ layer_backward = transformer_layer_backward if layer_backward is None else layer_backward
457 # should call backward first for final_layernorm and postprocess grad466 # should call backward first for final_layernorm and postprocess grad
458 layer_output_grad = block_output_grad467 layer_output_grad = block_output_grad
459 while len(layer_graphs) > 0:468 while len(layer_graphs) > 0:
460 layer_graph = layer_graphs.pop(-1)469 layer_graph = layer_graphs.pop(-1)
461- layer_output_grad = transformer_layer_backward(layer_output_grad, layer_graph)470+ layer_output_grad = layer_backward(layer_output_grad, layer_graph)
462 471 
463 return layer_output_grad472 return layer_output_grad
@@ -144,10 +144,7 @@ def transformer_layer_backward(
144 layer_graph.mlp_mhc_post_graph[1],144 layer_graph.mlp_mhc_post_graph[1],
145 )145 )
146 else:146 else:
147- restored_layer_graph.unperm2_graph = (147+ restored_layer_graph.set_output_boundary(layer_graph.get_output_boundary())
148- restored_layer_graph.unperm2_graph[0],
149- layer_graph.unperm2_graph[1],
150- )
151 layer_graph = restored_layer_graph148 layer_graph = restored_layer_graph
152 if isinstance(layer_graph, NoopLayerGraph):149 if isinstance(layer_graph, NoopLayerGraph):
153 return transformer_layer_backward_noop(layer_output_grad, layer_graph)150 return transformer_layer_backward_noop(layer_output_grad, layer_graph)
@@ -34,6 +34,23 @@ LOSS_BACKWARD_SCALE = torch.tensor(1.0)
34Shape = Union[List[int], torch.Size]34Shape = Union[List[int], torch.Size]
35 35 
36 36 
37+def get_interleaved_coordinates(iteration, pipeline_size, chunks, *, forward=True):
38+ """The existing regular-layout outer's chunk and logical microbatch IDs."""
39+ chunk = (iteration % (pipeline_size * chunks)) // pipeline_size
40+ if not forward:
41+ chunk = chunks - chunk - 1
42+ microbatch = (iteration // (pipeline_size * chunks)) * pipeline_size + iteration % pipeline_size
43+ return chunk, microbatch
44+ 
45+ 
46+def get_interleaved_warmup(pp_rank, num_microbatches, pipeline_size, chunks):
47+ """Warmup count for the regular FB layout."""
48+ total = num_microbatches * chunks
49+ if num_microbatches == pipeline_size:
50+ return total
51+ return min(total, (pipeline_size - pp_rank - 1) * 2 + (chunks - 1) * pipeline_size + 1)
52+ 
53+ 
37def has_pipeline_model_parallel_layout(config):54def has_pipeline_model_parallel_layout(config):
38 """Return whether custom pipeline layout is active for this model config."""55 """Return whether custom pipeline layout is active for this model config."""
39 if getattr(config, 'pipeline_model_parallel_layout', None) is not None:56 if getattr(config, 'pipeline_model_parallel_layout', None) is not None:
@@ -160,7 +177,7 @@ def forward_step(
160 177 
161 next_info = None178 next_info = None
162 model_graph = block.get_fwd_layer_graphs()179 model_graph = block.get_fwd_layer_graphs()
163- if extra_block_kwargs is not None:180+ if block.pp_comm_output is not None:
164 next_info = block.get_pp_comm_output()181 next_info = block.get_pp_comm_output()
165 output_tensor = (output_tensor, model_graph, next_info) if next_info is not None else (output_tensor, model_graph)182 output_tensor = (output_tensor, model_graph, next_info) if next_info is not None else (output_tensor, model_graph)
166 183 
@@ -275,13 +292,20 @@ def forward_step_func_wrapper(fn):
275 """292 """
276 293 
277 @wraps(fn)294 @wraps(fn)
278- def wrapper(data_iterator, model, extra_block_kwargs=None):295+ def wrapper(data_iterator, model, checkpoint_activations_microbatch=None, extra_block_kwargs=None):
296+ if checkpoint_activations_microbatch is not None:
297+ extra_block_kwargs = dict(extra_block_kwargs or {},
298+ checkpoint_activations_microbatch=checkpoint_activations_microbatch)
299+ had_instance_forward = 'forward' in vars(model)
279 orig_model_forward_func = model.forward300 orig_model_forward_func = model.forward
280- model.forward = partial(model.forward, extra_block_kwargs=extra_block_kwargs)301+ try:
281- out = fn(data_iterator, model)302+ model.forward = partial(orig_model_forward_func, extra_block_kwargs=extra_block_kwargs)
282- model.forward = orig_model_forward_func303+ return fn(data_iterator, model)
283- 304+ finally:
284- return out305+ if had_instance_forward:
306+ model.forward = orig_model_forward_func
307+ else:
308+ vars(model).pop('forward', None)
285 309 
286 return wrapper310 return wrapper
287 311 
@@ -445,11 +469,8 @@ def forward_backward_pipelining_with_interleaving(
445 num_warmup_microbatches = total_num_microbatches469 num_warmup_microbatches = total_num_microbatches
446 all_warmup_microbatches = True470 all_warmup_microbatches = True
447 else:471 else:
448- num_warmup_microbatches = (pipeline_parallel_size - pipeline_parallel_rank - 1) * 2472+ num_warmup_microbatches = get_interleaved_warmup(
449- num_warmup_microbatches += (num_model_chunks - 1) * pipeline_parallel_size473+ pipeline_parallel_rank, num_microbatches, pipeline_parallel_size, num_model_chunks)
450- num_warmup_microbatches = min(num_warmup_microbatches, total_num_microbatches)
451- # add one more warmup microbatches for 1f1b overlaping
452- num_warmup_microbatches += 1
453 num_microbatches_remaining = total_num_microbatches - num_warmup_microbatches474 num_microbatches_remaining = total_num_microbatches - num_warmup_microbatches
454 475 
455 # Checkpoint the activations of partial Transformer layers in a number of micro-batches476 # Checkpoint the activations of partial Transformer layers in a number of micro-batches
@@ -467,7 +488,8 @@ def forward_backward_pipelining_with_interleaving(
467 # Synchronize params for first two model chunks488 # Synchronize params for first two model chunks
468 if config.param_sync_func is not None:489 if config.param_sync_func is not None:
469 config.param_sync_func[0](model[0].parameters())490 config.param_sync_func[0](model[0].parameters())
470- config.param_sync_func[1](model[1].parameters())491+ if num_model_chunks > 1:
492+ config.param_sync_func[1](model[1].parameters())
471 493 
472 if use_pipeline_model_parallel_layout:494 if use_pipeline_model_parallel_layout:
473 schedule_table = get_schedule_table(num_microbatches, num_model_chunks, microbatch_group_size_per_vp_stage)495 schedule_table = get_schedule_table(num_microbatches, num_model_chunks, microbatch_group_size_per_vp_stage)
@@ -482,22 +504,16 @@ def forward_backward_pipelining_with_interleaving(
482 if not forward:504 if not forward:
483 model_chunk_id = num_model_chunks - model_chunk_id - 1505 model_chunk_id = num_model_chunks - model_chunk_id - 1
484 return model_chunk_id506 return model_chunk_id
485- microbatch_id_in_group = microbatch_id % (pipeline_parallel_size * num_model_chunks)507+ return get_interleaved_coordinates(microbatch_id, pipeline_parallel_size,
486- model_chunk_id = microbatch_id_in_group // pipeline_parallel_size508+ num_model_chunks, forward=forward)[0]
487- if not forward:
488- model_chunk_id = num_model_chunks - model_chunk_id - 1
489- return model_chunk_id
490 509 
491 def get_microbatch_id_in_model_chunk(iteration_id, forward):510 def get_microbatch_id_in_model_chunk(iteration_id, forward):
492 """Helper method to get the microbatch_id within model chunk given the iteration number."""511 """Helper method to get the microbatch_id within model chunk given the iteration number."""
493 assert forward512 assert forward
494 if use_pipeline_model_parallel_layout:513 if use_pipeline_model_parallel_layout:
495 return microbatch_id_table[iteration_id]514 return microbatch_id_table[iteration_id]
496- iteration_group_id = iteration_id // (pipeline_parallel_size * num_model_chunks)515+ return get_interleaved_coordinates(iteration_id, pipeline_parallel_size,
497- microbatch_id_in_model_chunk = (iteration_group_id * pipeline_parallel_size) + (516+ num_model_chunks, forward=forward)[1]
498- iteration_id % pipeline_parallel_size
499- )
500- return microbatch_id_in_model_chunk
501 517 
502 def num_released_microbatches(microbatch_id, model_chunk_id):518 def num_released_microbatches(microbatch_id, model_chunk_id):
503 if not use_pipeline_model_parallel_layout:519 if not use_pipeline_model_parallel_layout:
@@ -627,7 +643,7 @@ def forward_backward_pipelining_with_interleaving(
627 if getattr(config, 'enable_mhc', False):643 if getattr(config, 'enable_mhc', False):
628 logits_inputs.append(model_graph[-1].mlp_mhc_post_graph[1])644 logits_inputs.append(model_graph[-1].mlp_mhc_post_graph[1])
629 else:645 else:
630- logits_inputs.append(model_graph[-1].unperm2_graph[1])646+ logits_inputs.append(model_graph[-1].get_output_boundary())
631 model_graphs[model_chunk_id].append(model_graph)647 model_graphs[model_chunk_id].append(model_graph)
632 else:648 else:
633 output_tensor_ = output_tensor649 output_tensor_ = output_tensor
@@ -807,7 +823,7 @@ def forward_backward_pipelining_with_interleaving(
807 input_tensor = p2p_communicator.send_forward_recv_forward(823 input_tensor = p2p_communicator.send_forward_recv_forward(
808 output_tensor, recv_prev=recv_prev, tensor_shape=tensor_shape824 output_tensor, recv_prev=recv_prev, tensor_shape=tensor_shape
809 )825 )
810- if (not use_pipeline_model_parallel_layout) or recv_prev:826+ if (not use_pipeline_model_parallel_layout or recv_prev) and k + 1 < total_num_microbatches:
811 input_tensors[next_forward_model_chunk_id].append(input_tensor)827 input_tensors[next_forward_model_chunk_id].append(input_tensor)
812 else:828 else:
813 input_tensor, fwd_wait_handles = p2p_communicator.send_forward_recv_forward(829 input_tensor, fwd_wait_handles = p2p_communicator.send_forward_recv_forward(
@@ -834,9 +850,12 @@ def forward_backward_pipelining_with_interleaving(
834 )850 )
835 851 
836 output_tensor_grads[num_model_chunks - 1].append(output_tensor_grad)852 output_tensor_grads[num_model_chunks - 1].append(output_tensor_grad)
837- if (not use_pipeline_model_parallel_layout) or recv_prev:853+ if (not use_pipeline_model_parallel_layout or recv_prev) and k + 1 < total_num_microbatches:
838 input_tensors[next_forward_model_chunk_id].append(input_tensor)854 input_tensors[next_forward_model_chunk_id].append(input_tensor)
839 855 
856+ if config.deallocate_pipeline_outputs and fwd_wait_handles:
857+ for handle in fwd_wait_handles.values():
858+ handle.wait()
840 deallocate_output_tensor(output_tensor, config.deallocate_pipeline_outputs)859 deallocate_output_tensor(output_tensor, config.deallocate_pipeline_outputs)
841 # Run 1F1B in steady state.860 # Run 1F1B in steady state.
842 for k in range(num_microbatches_remaining):861 for k in range(num_microbatches_remaining):
@@ -919,6 +938,9 @@ def forward_backward_pipelining_with_interleaving(
919 ):938 ):
920 output_tensor = None939 output_tensor = None
921 940 
941+ if fwd_wait_handles:
942+ for handle in fwd_wait_handles.values():
943+ handle.wait()
922 deallocate_output_tensor(output_tensor, config.deallocate_pipeline_outputs)944 deallocate_output_tensor(output_tensor, config.deallocate_pipeline_outputs)
923 945 
924 # Run cooldown backward passes (flush out pipeline).946 # Run cooldown backward passes (flush out pipeline).
@@ -938,9 +960,9 @@ def forward_backward_pipelining_with_interleaving(
938 if is_pipeline_last_stage_for_chunk(chunk_id, num_model_chunks, use_pipeline_model_parallel_layout):960 if is_pipeline_last_stage_for_chunk(chunk_id, num_model_chunks, use_pipeline_model_parallel_layout):
939 input_tensor_grad = backward_step_helper(k, logits_bwd=True)961 input_tensor_grad = backward_step_helper(k, logits_bwd=True)
940 962 
941- output_tensor_grads[chunk_id].append(input_tensor_grad)963+ output_tensor_grads[chunk_id][0] = input_tensor_grad
942 output_tensors[chunk_id].pop(0)964 output_tensors[chunk_id].pop(0)
943- output_tensors[chunk_id].append(None) # dummy output tensors965+ output_tensors[chunk_id].insert(0, None) # dummy output tensors
944 input_tensor_grad = backward_step_helper(k)966 input_tensor_grad = backward_step_helper(k)
945 967 
946 if use_pipeline_model_parallel_layout:968 if use_pipeline_model_parallel_layout:
@@ -957,7 +979,7 @@ def forward_backward_pipelining_with_interleaving(
957 output_tensor_grad = p2p_communicator.send_backward_recv_backward(979 output_tensor_grad = p2p_communicator.send_backward_recv_backward(
958 input_tensor_grad, recv_next=recv_next, tensor_shape=tensor_shape980 input_tensor_grad, recv_next=recv_next, tensor_shape=tensor_shape
959 )981 )
960- if (not use_pipeline_model_parallel_layout) or recv_next:982+ if recv_next:
961 output_tensor_grads[next_backward_model_chunk_id].append(output_tensor_grad)983 output_tensor_grads[next_backward_model_chunk_id].append(output_tensor_grad)
962 984 
963 # Launch any remaining grad reductions.985 # Launch any remaining grad reductions.
@@ -984,4 +1006,5 @@ def forward_backward_pipelining_with_interleaving(
984 if config.timers is not None:1006 if config.timers is not None:
985 config.timers('forward-backward').stop()1007 config.timers('forward-backward').stop()
986 1008 
1009+ enable_grad_sync()
987 return forward_data_store1010 return forward_data_store
@@ -0,0 +1 @@
1+"""MoonEP feature-local implementation; no eager backend imports."""
@@ -0,0 +1,120 @@
1+"""Device-free configuration for the retained synchronous provider Buffer."""
2+from collections.abc import Mapping
3+import os
4+import re
5+ 
6+OPS = ('planning', 'dispatch', 'combine', 'prefetch', 'grad_reduce')
7+BOOL_ENV = {
8+ 'MOONEP_USE_UDMA': 'use_udma', 'MOONEP_ENABLE_PDL': 'enable_pdl',
9+ **{f'MOONEP_{op.upper()}_USE_UDMA': f'{op}_use_udma' for op in OPS},
10+}
11+INT_ENV = {'MOONEP_NUM_SMS': 'num_sms', 'MOONEP_TOKEN_PADDING': 'token_padding',
12+ 'MOONEP_COMM_STREAM_PRIORITY': 'comm_stream_priority'}
13+MODE_ENV = {'MOONEP_BARRIER_MODE': 'barrier_mode'}
14+ 
15+ 
16+def synchronous_buffer_options(overrides=None, *, environment=None):
17+ """Forward supported non-structural Buffer options; explicit API values win.
18+ 
19+ Shape, EP rank/group and destruction ownership remain runtime-managed.
20+ The provider accepts token_padding/enable_pdl for compatibility; on Ascend
21+ they do not enable padding or CUDA PDL.
22+ """
23+ environment = os.environ if environment is None else environment
24+ options = {}
25+ for name, key in BOOL_ENV.items():
26+ if name in environment:
27+ if environment[name] not in ('0', '1'):
28+ raise ValueError(f'{name} must be 0/1')
29+ options[key] = environment[name] == '1'
30+ # Match the existing overlap launcher's all-ops switch precedence. Planning
31+ # remains MTE unless separately requested (and then capability-checked).
32+ if options.get('use_udma'):
33+ for op in OPS[1:]:
34+ options[f'{op}_use_udma'] = True
35+ for name, key in INT_ENV.items():
36+ if name in environment:
37+ raw = environment[name]
38+ if not re.fullmatch(r'-?[0-9]+', raw):
39+ raise ValueError(f'{name} must be an integer')
40+ options[key] = int(raw)
41+ for name, key in MODE_ENV.items():
42+ if name in environment:
43+ options[key] = environment[name]
44+ if overrides is not None:
45+ if not isinstance(overrides, Mapping):
46+ raise TypeError('buffer_options must be a mapping')
47+ normalized = {}
48+ for name, value in overrides.items():
49+ # Buffer accepts both aliases; freeze one canonical representation.
50+ key = f'{name[9:]}_use_udma' if isinstance(name, str) and name.startswith('use_udma_') else name
51+ if key not in (*BOOL_ENV.values(), *INT_ENV.values(), *MODE_ENV.values()):
52+ raise ValueError(f'unsupported synchronous Buffer option: {name}')
53+ if key in normalized and normalized[key] != value:
54+ raise ValueError(f'conflicting Buffer UDMA aliases: {name}/{key}')
55+ normalized[key] = value
56+ options.update(normalized)
57+ if options.get('num_sms', ...) is None:
58+ # Buffer(num_sms=None) selects the provider default, including an
59+ # explicit API reset of an inherited MOONEP_NUM_SMS setting.
60+ options.pop('num_sms')
61+ for key, value in options.items():
62+ if key in BOOL_ENV.values():
63+ if type(value) is not bool:
64+ raise TypeError(f'{key} must be a bool')
65+ elif key in MODE_ENV.values():
66+ if value not in ('mixed', 'aiv'):
67+ raise ValueError(f'{key} must be mixed or aiv')
68+ elif type(value) is not int or key != 'comm_stream_priority' and value < 1:
69+ raise ValueError(f'{key} must be a positive integer' if key != 'comm_stream_priority'
70+ else 'comm_stream_priority must be an integer')
71+ return options
72+ 
73+ 
74+def synchronous_buffer_receipt(buffer, options):
75+ """Reject a dropped/unsupported request before entering SHMEM setup."""
76+ ctx = buffer._ctx
77+ effective = {op: ctx.get(f'_{op}_use_udma') for op in OPS}
78+ expected = {op: options.get(f'{op}_use_udma', options.get('use_udma', False) if op != 'planning' else False)
79+ for op in OPS}
80+ if any(type(effective[op]) is not bool or effective[op] != expected[op] for op in OPS):
81+ raise RuntimeError(f'synchronous Buffer backend request was not applied: expected={expected}, effective={effective}')
82+ for key in ('num_sms',):
83+ if key in options and ctx.get(key) != options[key]:
84+ raise RuntimeError(f'synchronous Buffer did not apply {key}={options[key]}')
85+ for key in ('comm_stream_priority', 'enable_pdl'):
86+ if key in options and getattr(buffer, key, None) != options[key]:
87+ raise RuntimeError(f'synchronous Buffer did not apply {key}={options[key]}')
88+ barrier = ctx.get('barrier_mode', 'mixed')
89+ expected_barrier = options.get('barrier_mode', os.environ.get('ASCEND_MOONEP_BARRIER_MODE', 'mixed'))
90+ if barrier != expected_barrier:
91+ raise RuntimeError('synchronous Buffer did not apply requested barrier_mode')
92+ return dict(udma_ops=effective, num_sms=ctx.get('num_sms'), barrier_mode=barrier,
93+ comm_stream_priority=getattr(buffer, 'comm_stream_priority', None),
94+ enable_pdl=getattr(buffer, 'enable_pdl', None))
95+ 
96+ 
97+def fb_overlap_core_limit_enabled(*, environment=None):
98+ environment = os.environ if environment is None else environment
99+ value = environment.get('MOONEP_CORE_LIMIT', '0')
100+ if value not in ('0', '1'):
101+ raise ValueError('MOONEP_CORE_LIMIT must be 0/1')
102+ return value == '1'
103+ 
104+ 
105+def fb_overlap_buffer_options(core_limit, overrides=None, *, environment=None):
106+ """Keep the FB transport and its barriers fixed across the two core profiles."""
107+ recipe = dict(use_udma=False, planning_use_udma=False, dispatch_use_udma=False,
108+ combine_use_udma=False, prefetch_use_udma=True, grad_reduce_use_udma=True,
109+ num_sms=8 if core_limit else None,
110+ barrier_mode='aiv')
111+ environment = os.environ if environment is None else environment
112+ controlled_env = {name for name, key in (BOOL_ENV | INT_ENV | MODE_ENV).items() if key in recipe}
113+ environment = {name: environment[name] for name in
114+ (BOOL_ENV | INT_ENV | MODE_ENV).keys() - controlled_env if name in environment}
115+ if overrides is not None and not isinstance(overrides, Mapping):
116+ raise TypeError('buffer_options must be a mapping')
117+ controlled_options = recipe.keys() | {f'use_udma_{op}' for op in OPS}
118+ options = {name: value for name, value in (overrides or {}).items()
119+ if name not in controlled_options}
120+ return synchronous_buffer_options(dict(options, **recipe), environment=environment)
@@ -0,0 +1,138 @@
1+"""Flex dispatcher and synchronous hooks for Ascend MoonEP."""
2+ 
3+from __future__ import annotations
4+ 
5+from functools import wraps
6+ 
7+from mindspeed.core.transformer.moe.moe_feature.moonep import moonep_runtime
8+from mindspeed.core.transformer.moe.moe_feature.moonep.moonep_runtime import close_moonep, initialize_moonep
9+from mindspeed.core.transformer.moe.moe_feature.moonep.virtual_expert_load_balancer import (
10+ VirtualExpertLoadBalancer,
11+)
12+ 
13+ 
14+def build_moonep_flex_token_dispatcher():
15+ """Return the Flex subclass wired to the MoonEP manager."""
16+ from megatron.core.transformer.moe.token_dispatcher import (
17+ MoEFlexTokenDispatcher,
18+ MoETokenDispatcher,
19+ _DispatchManager,
20+ )
21+ 
22+ class _VirtualExpertMoonEPManager(VirtualExpertLoadBalancer, _DispatchManager):
23+ def __init__(self, group, num_local_experts, num_experts, config):
24+ VirtualExpertLoadBalancer.__init__(
25+ self,
26+ group=group,
27+ num_local_experts=num_local_experts,
28+ num_experts=num_experts,
29+ config=config,
30+ )
31+ 
32+ class MoonEPFlexTokenDispatcher(MoEFlexTokenDispatcher):
33+ fb_overlap_backend = 'moonep'
34+ 
35+ def __init__(self, num_local_experts, local_expert_indices, config, pg_collection=None):
36+ # Upstream Flex rejects the private "moonep" backend. Reuse all six
37+ # public stages but construct only the NPU manager here.
38+ MoETokenDispatcher.__init__(self, config=config, pg_collection=pg_collection)
39+ if self.tp_size != 1:
40+ raise ValueError("MoonEP Flex requires expert tensor parallel size 1")
41+ self.num_local_experts = int(num_local_experts)
42+ self.local_expert_indices = tuple(local_expert_indices)
43+ self._comm_manager = _VirtualExpertMoonEPManager(
44+ group=self.tp_ep_group,
45+ num_local_experts=self.num_local_experts,
46+ num_experts=int(config.num_moe_experts),
47+ config=config,
48+ )
49+ self.cudagraph_attrs = []
50+ 
51+ def get_expert_zero_copy_buffers(self):
52+ # The private Experts Autograd boundary supplies Z2/Z4 directly;
53+ # the generic TE op-fuser must not allocate or bind another buffer.
54+ return None, None
55+ 
56+ def wrap_layer_input(self, hidden_states):
57+ """Mirror the PR6892 dispatcher boundary on older Megatron Core."""
58+ return self._comm_manager.wrap_layer_input(hidden_states)
59+ 
60+ def finalize_layer_output(self, output):
61+ """Attach the exact plan after model-specific layer postprocessing."""
62+ return self._comm_manager.finalize_output(output)
63+ 
64+ _VirtualExpertMoonEPManager.__name__ = "_VirtualExpertMoonEPManager"
65+ MoonEPFlexTokenDispatcher.__name__ = "MoonEPFlexTokenDispatcher"
66+ return MoonEPFlexTokenDispatcher
67+ 
68+ 
69+def moonep_moe_layer_init_wrapper(fn):
70+ @wraps(fn)
71+ def wrapper(layer, *args, **kwargs):
72+ result = fn(layer, *args, **kwargs)
73+ dispatcher = getattr(layer, "token_dispatcher", None)
74+ manager = getattr(dispatcher, "_comm_manager", None)
75+ if isinstance(manager, VirtualExpertLoadBalancer):
76+ manager.bind_experts(layer.experts)
77+ return result
78+ 
79+ return wrapper
80+ 
81+ 
82+def moonep_moe_layer_route_wrapper(fn):
83+ """Mirror PR6892's layer-input hook without changing upstream Megatron."""
84+ @wraps(fn)
85+ def wrapper(layer, hidden_states, *args, **kwargs):
86+ dispatcher = getattr(layer, "token_dispatcher", None)
87+ manager = getattr(dispatcher, "_comm_manager", None)
88+ if isinstance(manager, VirtualExpertLoadBalancer):
89+ hidden_states = dispatcher.wrap_layer_input(hidden_states)
90+ return fn(layer, hidden_states, *args, **kwargs)
91+ 
92+ return wrapper
93+ 
94+ 
95+def moonep_moe_layer_postprocess_wrapper(fn):
96+ """Backport PR6892's final layer-output boundary to older Megatron Core."""
97+ @wraps(fn)
98+ def wrapper(layer, *args, **kwargs):
99+ output = fn(layer, *args, **kwargs)
100+ dispatcher = getattr(layer, "token_dispatcher", None)
101+ manager = getattr(dispatcher, "_comm_manager", None)
102+ if isinstance(manager, VirtualExpertLoadBalancer):
103+ output = dispatcher.finalize_layer_output(output)
104+ return output
105+ 
106+ return wrapper
107+ 
108+ 
109+def setup_wrapper(fn):
110+ @wraps(fn)
111+ def wrapper(*args, **kwargs):
112+ result = fn(*args, **kwargs)
113+ initialize_moonep(
114+ result[0] if isinstance(result, tuple) else getattr(result, "model", None)
115+ )
116+ return result
117+ 
118+ return wrapper
119+ 
120+ 
121+def save_checkpoint_wrapper(fn):
122+ @wraps(fn)
123+ def wrapper(*args, **kwargs):
124+ from mindspeed.core.transformer.moe.moe_feature.moonep.moonep_runtime import checkpoint_drain
125+ 
126+ checkpoint_drain()
127+ return fn(*args, **kwargs)
128+ 
129+ return wrapper
130+ 
131+ 
132+def destroy_model_parallel_wrapper(fn):
133+ @wraps(fn)
134+ def wrapper(*args, **kwargs):
135+ close_moonep()
136+ return fn(*args, **kwargs)
137+ 
138+ return wrapper
@@ -0,0 +1,87 @@
1+"""Configuration validation for MoonEP."""
2+ 
3+from __future__ import annotations
4+ 
5+def moonep_enabled(args) -> bool:
6+ return (
7+ getattr(args, "moe_token_dispatcher_type", None) == "flex"
8+ and getattr(args, "moe_flex_dispatcher_backend", None) == "moonep"
9+ )
10+ 
11+ 
12+def _enabled(args, name, default=False):
13+ value = getattr(args, name, default)
14+ if isinstance(value, str):
15+ disabled_values = {"", "disable", "disabled", "false", "none", "off"}
16+ return value.strip().lower() not in disabled_values
17+ return bool(value)
18+ 
19+ 
20+def validate_moonep_args(args) -> None:
21+ if not moonep_enabled(args):
22+ return
23+ errors = []
24+ ep = int(getattr(args, "expert_model_parallel_size", 1))
25+ # Megatron CLI owns num_experts; TransformerConfig owns num_moe_experts.
26+ configured = getattr(args, 'num_moe_experts', None)
27+ cli_experts = getattr(args, 'num_experts', None)
28+ if configured is not None and cli_experts is not None and int(configured) != int(cli_experts):
29+ errors.append('num_experts and num_moe_experts disagree')
30+ experts = int((configured if configured is not None else cli_experts) or 0)
31+ if ep <= 1 or experts <= 0 or experts % ep:
32+ errors.append("EP must be >1 and num_moe_experts must be positive and divisible by EP")
33+ if int(getattr(args, "expert_tensor_parallel_size", 1)) != 1:
34+ errors.append("expert tensor parallel size must be 1")
35+ if not _enabled(args, "bf16") or _enabled(args, "fp16"):
36+ errors.append("activation and expert weights must use BF16")
37+ # This validator is invoked both for the process-wide argument namespace
38+ # and for TransformerConfig during model finalization. The latter does
39+ # not own the DDP/optimizer setting, so only validate it when the field is
40+ # available. Bridge validates its two authoritative config owners before
41+ # model finalization.
42+ use_distributed_optimizer = getattr(args, "use_distributed_optimizer", None)
43+ if use_distributed_optimizer is not None and not bool(use_distributed_optimizer):
44+ errors.append("distributed optimizer is required")
45+ if not _enabled(args, "moe_grouped_gemm"):
46+ errors.append("moe_grouped_gemm must be enabled")
47+ if _enabled(args, "moe_single_grouped_weight"):
48+ errors.append("moe_single_grouped_weight must be false (per-expert checkpoint schema)")
49+ if _enabled(args, "add_bias_linear"):
50+ errors.append("grouped expert bias is unsupported")
51+ if not _enabled(args, "gemm_gradient_accumulation_fusion"):
52+ errors.append("gemm_gradient_accumulation_fusion must be enabled")
53+ if _enabled(args, "moe_shared_expert_overlap"):
54+ errors.append("shared expert overlap must be disabled")
55+ for name in (
56+ "overlap_moe_expert_parallel_comm",
57+ "moe_enable_fb_overlap",
58+ "moe_zero_memory",
59+ "use_cuda_graphs",
60+ "fp8",
61+ "fp4",
62+ ):
63+ if _enabled(args, name):
64+ errors.append(f"{name} is unsupported by MoonEP")
65+ for name in (
66+ "moe_permute_fusion",
67+ "moe_token_dispatcher_fused_permute",
68+ "use_fused_moe_token_permute_and_unpermute",
69+ ):
70+ if _enabled(args, name):
71+ errors.append(f"{name} must be disabled")
72+ recompute_modules = tuple(getattr(args, "recompute_modules", ()) or ())
73+ # Full-layer checkpointing runs the original forward under no_grad and the
74+ # replay under enable_grad. The executor classifies those calls before its
75+ # custom Autograd Functions, retires the original plan after combine, and
76+ # attaches the replay-created exact plan to the real backward graph.
77+ # Output-discarding selective MoE recompute has a different lifetime and is
78+ # intentionally kept outside the synchronous v1 contract.
79+ if "moe_act" in recompute_modules:
80+ errors.append(
81+ "selective moe_act recompute is unsupported; use full recompute"
82+ )
83+ if _enabled(args, "moe_enable_moonep"):
84+ errors.append("legacy moe_enable_moonep is removed; use flex + moonep")
85+ if errors:
86+ raise ValueError("invalid MoonEP L+B configuration: " + "; ".join(errors))
87+ 
@@ -0,0 +1,364 @@
1+"""MoonEP synchronous exact-plan Autograd boundaries and runtime helpers."""
2+ 
3+from __future__ import annotations
4+ 
5+from functools import wraps
6+import weakref
7+ 
8+from mindspeed.core.transformer.moe.moe_feature.moonep.virtual_expert_load_balancer import (
9+ _VirtualExperts,
10+ VirtualExpertPlan,
11+ build_physical_counts,
12+ clear_dispatch_padding,
13+)
14+ 
15+ 
16+def _backward_expectations(hidden, probs, virtual_experts):
17+ """Classify checkpoint original/recompute before Function.apply."""
18+ import torch
19+ 
20+ grad_enabled = torch.is_grad_enabled()
21+ dispatch_backward_expected = grad_enabled and (
22+ bool(getattr(hidden, "requires_grad", False))
23+ or bool(getattr(probs, "requires_grad", False))
24+ )
25+ expert_backward_expected = grad_enabled and (
26+ dispatch_backward_expected
27+ or any(
28+ bool(getattr(parameter, "requires_grad", False))
29+ for parameter in virtual_experts.source_parameters
30+ )
31+ )
32+ return dispatch_backward_expected, expert_backward_expected
33+ 
34+ 
35+def _types():
36+ import torch
37+ from mindspeed.ops.gmm import npu_gmm_v5_out, npu_grouped_matmul_add_ptr_
38+ from mindspeed.core.transformer.moe.moe_feature.moonep import moonep_runtime
39+ 
40+ class Dispatch(torch.autograd.Function):
41+ @staticmethod
42+ def forward(
43+ ctx,
44+ hidden,
45+ probs,
46+ indices,
47+ counts,
48+ manager,
49+ dispatch_backward_expected,
50+ expert_backward_expected,
51+ ):
52+ buffer = moonep_runtime.get_moonep_buffer()
53+ buffer.set_comm_buffers(None)
54+ z1, dispatched_probs, cu_seqlens, provider_plan = (
55+ buffer.dispatch(
56+ hidden,
57+ route_weights_sk=probs,
58+ topk_experts_sk=indices,
59+ tokens_per_expert=counts,
60+ zero_copy=moonep_runtime.strict_zero_copy_enabled(),
61+ router_weights_zero_copy=moonep_runtime.strict_zero_copy_enabled(),
62+ )
63+ )
64+ if moonep_runtime.strict_zero_copy_enabled():
65+ z1 = moonep_runtime.activation_alias(z1)
66+ dispatched_probs = moonep_runtime.activation_alias(dispatched_probs)
67+ import torch
68+ 
69+ padding_mask = clear_dispatch_padding(
70+ z1, dispatched_probs, cu_seqlens=cu_seqlens)
71+ physical_counts = build_physical_counts(
72+ cu_seqlens,
73+ rank=int(torch.distributed.get_rank(group=manager.group)),
74+ local_experts=manager.num_local_experts,
75+ global_experts=manager.num_experts,
76+ slots=manager.num_local_experts,
77+ carrier_rows=int(z1.shape[0]),
78+ )
79+ plan = VirtualExpertPlan(
80+ provider_plan=provider_plan,
81+ group_counts_2l=physical_counts,
82+ padding_mask=padding_mask,
83+ manager_cookie=manager._cookie,
84+ dispatch_backward_expected=bool(dispatch_backward_expected),
85+ expert_backward_expected=bool(expert_backward_expected),
86+ )
87+ _VirtualExperts.admit(plan)
88+ manager.accept_forward_plan(plan)
89+ ctx.plan = plan
90+ ctx.manager_ref = weakref.ref(manager)
91+ return z1, dispatched_probs
92+ 
93+ @staticmethod
94+ @torch.autograd.function.once_differentiable
95+ def backward(ctx, grad_hidden, grad_probs):
96+ manager = ctx.manager_ref()
97+ if manager is None:
98+ raise RuntimeError("MoonEP manager disappeared before dispatch backward")
99+ plan = ctx.plan
100+ manager.require_backward_plan(plan)
101+ try:
102+ buffer = moonep_runtime.get_moonep_buffer()
103+ buffer.set_comm_buffers(None)
104+ grad_input, grad_route, _ = buffer.combine(
105+ plan=plan.provider_plan,
106+ hidden_nvsh=grad_hidden,
107+ route_weights_nvs=grad_probs,
108+ zero_copy=moonep_runtime.strict_zero_copy_enabled(),
109+ router_weights_zero_copy=False,
110+ )
111+ if grad_probs is not None:
112+ moonep_runtime.record_route_grad_copy(grad_probs)
113+ manager.retire(plan)
114+ except Exception as exc:
115+ manager.fail_stop(plan, exc)
116+ raise
117+ return grad_input, grad_route, None, None, None, None, None
118+ 
119+ class Combine(torch.autograd.Function):
120+ @staticmethod
121+ def forward(ctx, expert_output, plan, manager):
122+ try:
123+ buffer = moonep_runtime.get_moonep_buffer()
124+ buffer.set_comm_buffers(None)
125+ output, _, _ = buffer.combine(
126+ plan=plan.provider_plan,
127+ hidden_nvsh=expert_output,
128+ zero_copy=moonep_runtime.strict_zero_copy_enabled(),
129+ router_weights_zero_copy=moonep_runtime.strict_zero_copy_enabled(),
130+ )
131+ except Exception as exc:
132+ manager.fail_stop(plan, exc)
133+ raise
134+ ctx.plan = plan
135+ ctx.manager_ref = weakref.ref(manager)
136+ return output
137+ 
138+ @staticmethod
139+ @torch.autograd.function.once_differentiable
140+ def backward(ctx, grad_output):
141+ manager = ctx.manager_ref()
142+ if manager is None:
143+ raise RuntimeError("MoonEP manager disappeared before combine backward")
144+ plan = ctx.plan
145+ manager.require_backward_plan(plan)
146+ try:
147+ dispatch_source = grad_output
148+ if not dispatch_source.is_contiguous():
149+ if moonep_runtime.strict_zero_copy_enabled():
150+ raise RuntimeError(
151+ "STRICT-ZC combine backward requires a contiguous upstream gradient"
152+ )
153+ dispatch_source = dispatch_source.contiguous()
154+ buffer = moonep_runtime.get_moonep_buffer()
155+ buffer.set_comm_buffers(None)
156+ z3, _, _, _ = buffer.dispatch(
157+ dispatch_source,
158+ plan=plan.provider_plan,
159+ zero_copy=moonep_runtime.strict_zero_copy_enabled(),
160+ router_weights_zero_copy=moonep_runtime.strict_zero_copy_enabled(),
161+ )
162+ if moonep_runtime.strict_zero_copy_enabled():
163+ z3 = moonep_runtime.activation_alias(z3)
164+ clear_dispatch_padding(z3, padding_mask=plan.padding_mask)
165+ moonep_runtime.activation_edge("Z3", z3)
166+ return z3, None, None
167+ except Exception as exc:
168+ manager.fail_stop(plan, exc)
169+ raise
170+ 
171+ class Experts(torch.autograd.Function):
172+ @staticmethod
173+ def forward(ctx, hidden, probs, original_hidden, plan, manager, *weights):
174+ virtual_experts = manager.virtual_experts
175+ count = virtual_experts.num_local_experts
176+ if probs.ndim != 1:
177+ raise RuntimeError("MoonEP expert-order probabilities must be one-dimensional")
178+ if len(weights) != 2 * count:
179+ raise RuntimeError("MoonEP expert boundary received an invalid weight set")
180+ try:
181+ buffer = moonep_runtime.get_moonep_buffer()
182+ virtual_experts.prefetch(buffer, "fc1", plan)
183+ virtual_experts.prefetch(buffer, "fc2", plan)
184+ 
185+ fc1_refs = virtual_experts.gmm_weight_refs("fc1", transpose=True)
186+ fc1_out = hidden.new_empty((hidden.shape[0], weights[0].shape[0]))
187+ npu_gmm_v5_out(hidden, fc1_refs, fc1_out, plan.group_counts_2l)
188+ 
189+ with torch.enable_grad():
190+ fc1_leaf = fc1_out.detach().requires_grad_(True)
191+ activated = virtual_experts.activation(fc1_leaf)
192+ probability = probs.unsqueeze(-1)
193+ weighted = (activated.detach() * probability).to(activated.dtype)
194+ 
195+ fc2_refs = virtual_experts.gmm_weight_refs("fc2", transpose=True)
196+ strict = moonep_runtime.strict_zero_copy_enabled()
197+ z2 = hidden if strict else hidden.new_empty(hidden.shape)
198+ npu_gmm_v5_out(weighted, fc2_refs, z2, plan.group_counts_2l)
199+ moonep_runtime.activation_edge("Z2", z2)
200+ if strict:
201+ ctx.mark_dirty(hidden)
202+ saved_probs = moonep_runtime.snapshot_route_probs(probs) if strict else probs
203+ ctx.plan = plan
204+ ctx.manager_ref = weakref.ref(manager)
205+ ctx.weight_versions = tuple(int(weight._version) for weight in weights)
206+ ctx.save_for_backward(
207+ original_hidden, fc1_leaf, activated, weighted, saved_probs, *weights
208+ )
209+ return z2
210+ except Exception as exc:
211+ manager.fail_stop(plan, exc)
212+ raise
213+ 
214+ @staticmethod
215+ @torch.autograd.function.once_differentiable
216+ def backward(ctx, grad_output):
217+ manager = ctx.manager_ref()
218+ if manager is None:
219+ raise RuntimeError("MoonEP manager disappeared before expert backward")
220+ plan = ctx.plan
221+ manager.require_backward_plan(plan)
222+ virtual_experts = manager.virtual_experts
223+ saved = ctx.saved_tensors
224+ original_hidden, fc1_leaf, activated, weighted, probs = saved[:5]
225+ weights = saved[5:]
226+ if tuple(int(weight._version) for weight in weights) != ctx.weight_versions:
227+ raise RuntimeError("expert Parameter changed between exact forward and backward")
228+ try:
229+ buffer = moonep_runtime.get_moonep_buffer()
230+ counts = plan.group_counts_2l
231+ 
232+ fc2_dgrad_refs = virtual_experts.gmm_weight_refs("fc2", transpose=False)
233+ grad_weighted = weighted.new_empty(weighted.shape)
234+ npu_gmm_v5_out(grad_output, fc2_dgrad_refs, grad_weighted, counts)
235+ npu_grouped_matmul_add_ptr_(
236+ grad_output,
237+ weighted,
238+ counts,
239+ virtual_experts.wgrad_targets("fc2"),
240+ )
241+ # Publish every rank's completed dW slots before peer reads.
242+ buffer.barrier_on_stream(torch.npu.current_stream())
243+ virtual_experts.reduce(buffer, "fc2", plan)
244+ 
245+ probability = probs.unsqueeze(-1)
246+ with torch.enable_grad():
247+ torch.autograd.backward(
248+ activated,
249+ grad_tensors=(grad_weighted * probability).to(activated.dtype),
250+ )
251+ grad_fc1 = fc1_leaf.grad
252+ grad_probs = (
253+ grad_weighted.float() * activated.detach().float()
254+ ).sum(dim=-1).to(probs.dtype)
255+ 
256+ buffer.set_comm_buffers(None)
257+ r1, _, _, _ = buffer.dispatch(
258+ original_hidden,
259+ plan=plan.provider_plan,
260+ zero_copy=moonep_runtime.strict_zero_copy_enabled(),
261+ router_weights_zero_copy=moonep_runtime.strict_zero_copy_enabled(),
262+ )
263+ moonep_runtime.activation_edge("R1", r1)
264+ if moonep_runtime.strict_zero_copy_enabled():
265+ r1 = moonep_runtime.activation_alias(r1)
266+ clear_dispatch_padding(r1, padding_mask=plan.padding_mask)
267+ npu_grouped_matmul_add_ptr_(
268+ grad_fc1,
269+ r1,
270+ counts,
271+ virtual_experts.wgrad_targets("fc1"),
272+ )
273+ # Publish every rank's completed dW slots before peer reads.
274+ buffer.barrier_on_stream(torch.npu.current_stream())
275+ virtual_experts.reduce(buffer, "fc1", plan)
276+ 
277+ z4 = None
278+ if plan.dispatch_backward_expected:
279+ fc1_dgrad_refs = virtual_experts.gmm_weight_refs(
280+ "fc1", transpose=False
281+ )
282+ z4 = r1 if moonep_runtime.strict_zero_copy_enabled() else r1.new_empty(r1.shape)
283+ npu_gmm_v5_out(grad_fc1, fc1_dgrad_refs, z4, counts)
284+ moonep_runtime.activation_edge("Z4", z4)
285+ 
286+ virtual_experts.finalize_grads()
287+ dummy = []
288+ for parameter in weights:
289+ if hasattr(parameter, "grad_added_to_main_grad"):
290+ parameter.grad_added_to_main_grad = True
291+ dummy.append(torch.empty_like(parameter))
292+ if not plan.dispatch_backward_expected:
293+ manager.retire(plan)
294+ return (z4, grad_probs, None, None, None, *dummy)
295+ except Exception as exc:
296+ manager.fail_stop(plan, exc)
297+ raise
298+ 
299+ return Dispatch, Combine, Experts
300+ 
301+ 
302+_AUTOGRAD_TYPES = None
303+ 
304+ 
305+def _autograd_types():
306+ global _AUTOGRAD_TYPES
307+ if _AUTOGRAD_TYPES is None:
308+ _AUTOGRAD_TYPES = _types()
309+ return _AUTOGRAD_TYPES
310+ 
311+ 
312+def dispatch_apply(hidden, probs, indices, counts, manager):
313+ from mindspeed.core.transformer.moe.moe_feature.moonep import moonep_runtime
314+ 
315+ dispatch_backward_expected, expert_backward_expected = _backward_expectations(
316+ hidden, probs, manager.virtual_experts
317+ )
318+ try:
319+ z1, dispatched_probs = _autograd_types()[0].apply(
320+ hidden,
321+ probs,
322+ indices,
323+ counts,
324+ manager,
325+ dispatch_backward_expected,
326+ expert_backward_expected,
327+ )
328+ plan = manager.forward_plan()
329+ moonep_runtime.activation_edge("Z1", z1)
330+ return z1, dispatched_probs, plan
331+ except Exception as exc:
332+ manager.fail_stop(None, exc)
333+ raise
334+ 
335+ 
336+def combine_apply(expert_output, manager, plan):
337+ return _autograd_types()[1].apply(expert_output, plan, manager)
338+ 
339+ 
340+def moonep_grouped_mlp_forward_wrapper(forward):
341+ @wraps(forward)
342+ def wrapper(experts, hidden, tokens_per_expert, probs, *args, **kwargs):
343+ manager_ref = getattr(experts, "_mindspeed_moonep_manager_ref", None)
344+ if manager_ref is None:
345+ return forward(experts, hidden, tokens_per_expert, probs, *args, **kwargs)
346+ if args or kwargs:
347+ raise RuntimeError("MoonEP routed experts do not accept extra forward arguments")
348+ manager = manager_ref()
349+ if manager is None:
350+ raise RuntimeError("MoonEP manager disappeared before expert forward")
351+ plan = manager.forward_plan()
352+ if (
353+ tuple(tokens_per_expert.shape) != tuple(plan.group_counts_2l.shape)
354+ or tokens_per_expert.data_ptr() != plan.group_counts_2l.data_ptr()
355+ ):
356+ raise RuntimeError("MoonEP expert counts do not belong to the exact dispatch plan")
357+ original = manager.consume_forward_source(plan)
358+ weights = manager.virtual_experts.source_parameters
359+ output = _autograd_types()[2].apply(
360+ hidden, probs, original, plan, manager, *weights
361+ )
362+ return output, None
363+ 
364+ return wrapper
@@ -0,0 +1,451 @@
1+"""Process Buffer and synchronous lifecycle for Ascend MoonEP."""
2+ 
3+from __future__ import annotations
4+ 
5+import hashlib
6+import json
7+from pathlib import Path
8+import weakref
9+ 
10+from mindspeed.core.transformer.moe.moe_feature.moonep.moonep_contract import (
11+ validate_moonep_args,
12+)
13+ 
14+ 
15+_MANAGERS: list[weakref.ReferenceType] = []
16+_BUFFER = None
17+_STRICT_ZERO_COPY = False
18+_FATAL_ERROR = None
19+_NATIVE_IDENTITIES = None
20+_SYNC_BUFFER_OPTIONS = None
21+ 
22+ 
23+_COPY_LEDGER = {
24+ edge: {"calls": 0, "bytes": 0} for edge in ("Z1", "Z2", "Z3", "Z4", "R1")
25+}
26+_METADATA_COPY_LEDGER = {
27+ name: {"calls": 0, "bytes": 0}
28+ for name in ("autograd_saved_route_probs", "dispatch_backward_route_grad")
29+}
30+ 
31+ 
32+def register_manager(manager) -> None:
33+ _MANAGERS.append(weakref.ref(manager))
34+ 
35+ 
36+def _live_managers():
37+ live = []
38+ for reference in _MANAGERS:
39+ manager = reference()
40+ if manager is not None:
41+ live.append(manager)
42+ return live
43+ 
44+ 
45+def _native_identity(module) -> dict[str, object]:
46+ path = Path(module.__file__).resolve()
47+ stat = path.stat()
48+ return {
49+ "realpath": str(path),
50+ "device": int(stat.st_dev),
51+ "inode": int(stat.st_ino),
52+ "sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
53+ }
54+ 
55+ 
56+def _expert_hidden_size(manager, fc1_shape, fc2_shape) -> int:
57+ configured = getattr(manager.config, "moe_latent_size", None)
58+ if configured is None:
59+ configured = getattr(manager.config, "hidden_size", None)
60+ hidden = int(configured or 0)
61+ if hidden <= 0 or int(fc1_shape[1]) != hidden or int(fc2_shape[0]) != hidden:
62+ raise ValueError(
63+ "MoonEP canonical expert Parameters disagree with the routed hidden width: "
64+ f"configured={hidden}, FC1={tuple(fc1_shape)}, FC2={tuple(fc2_shape)}"
65+ )
66+ return hidden
67+ 
68+ 
69+def _manifest(managers, *, rank_count, projection_shapes, token_capacity):
70+ first = managers[0]
71+ return {
72+ "abi": "expert-pointer-buffer-v11",
73+ "rank_count": int(rank_count),
74+ "local_experts": int(first.num_local_experts),
75+ "global_experts": int(first.num_experts),
76+ "router_topk": int(first.router_topk),
77+ "token_capacity": int(token_capacity),
78+ "projection_shapes": [list(shape) for shape in projection_shapes],
79+ "manager_count": len(managers),
80+ }
81+ 
82+ 
83+def _validate_manifest_across_group(manifest, *, group, device, rank_count):
84+ import torch
85+ 
86+ payload = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode("utf-8")
87+ digest = hashlib.sha256(payload).hexdigest()
88+ raw = torch.tensor(
89+ list(bytes.fromhex(digest)), dtype=torch.uint8, device=torch.device("npu", device)
90+ )
91+ peers = [torch.empty_like(raw) for _ in range(rank_count)]
92+ torch.distributed.all_gather(peers, raw, group=group)
93+ if any(bytes(peer.cpu().tolist()).hex() != digest for peer in peers):
94+ raise RuntimeError("MoonEP address-free layout manifest differs across EP ranks")
95+ return digest
96+ 
97+ 
98+def ensure_admission() -> None:
99+ if _FATAL_ERROR is not None:
100+ raise RuntimeError(f"MoonEP admission is closed after a native failure: {_FATAL_ERROR}")
101+ if _BUFFER is None:
102+ raise RuntimeError("MoonEP process resources are not initialized")
103+ 
104+ 
105+def fail_stop(error) -> None:
106+ """Close training admission; callers must propagate the original exception."""
107+ global _FATAL_ERROR
108+ if _FATAL_ERROR is None:
109+ _FATAL_ERROR = f"{type(error).__name__}: {error}"
110+ 
111+ 
112+def get_moonep_buffer():
113+ ensure_admission()
114+ return _BUFFER
115+ 
116+ 
117+def strict_zero_copy_enabled() -> bool:
118+ return _STRICT_ZERO_COPY
119+ 
120+ 
121+def activation_edge(edge, tensor, *, owner=None, generation=None):
122+ if edge not in _COPY_LEDGER:
123+ raise ValueError(f"unknown MoonEP activation edge: {edge}")
124+ carrier = get_moonep_buffer()._ctx["hidden_buf_local"]
125+ if _STRICT_ZERO_COPY:
126+ prefix_shape = (
127+ tensor.ndim == carrier.ndim
128+ and 0 < int(tensor.shape[0]) <= int(carrier.shape[0])
129+ and tuple(tensor.shape[1:]) == tuple(carrier.shape[1:])
130+ )
131+ if (
132+ tensor.data_ptr() != carrier.data_ptr()
133+ or tensor.storage_offset() != carrier.storage_offset()
134+ or not prefix_shape
135+ or tuple(tensor.stride()) != tuple(carrier.stride())
136+ ):
137+ raise RuntimeError(
138+ f"STRICT-ZC {edge} must alias a logical prefix of the MoonEP "
139+ "activation carrier"
140+ )
141+ return
142+ entry = _COPY_LEDGER[edge]
143+ entry["calls"] += 1
144+ entry["bytes"] += int(tensor.numel()) * int(tensor.element_size())
145+ 
146+ 
147+def record_route_grad_copy(tensor):
148+ """Account for a successful Combine route copy; this does not move data."""
149+ entry = _METADATA_COPY_LEDGER["dispatch_backward_route_grad"]
150+ entry["calls"] += 1
151+ entry["bytes"] += int(tensor.numel()) * int(tensor.element_size())
152+ 
153+ 
154+def snapshot_route_probs(tensor):
155+ snapshot = tensor.clone()
156+ entry = _METADATA_COPY_LEDGER["autograd_saved_route_probs"]
157+ entry["calls"] += 1
158+ entry["bytes"] += int(tensor.numel()) * int(tensor.element_size())
159+ return snapshot
160+ 
161+ 
162+def copy_ledger():
163+ return {edge: dict(entry) for edge, entry in _COPY_LEDGER.items()}
164+ 
165+ 
166+def metadata_copy_ledger():
167+ return {name: dict(entry) for name, entry in _METADATA_COPY_LEDGER.items()}
168+ 
169+ 
170+def _load_npu_provider():
171+ """Load the NPU provider and its prepared-pointer Python interface."""
172+ import npu_patch
173+ from moonep import Buffer
174+ 
175+ if Buffer is not npu_patch.Buffer:
176+ raise RuntimeError("MindSpeed MoonEP requires MOONEP_BACKEND=npu")
177+ for name in ('set_comm_buffers', 'prepare_comm_buffers', 'prepare_expert_binding',
178+ 'prefetch_weight_from_ptrs', 'reduce_grad_to_ptrs'):
179+ if not callable(getattr(Buffer, name, None)):
180+ raise RuntimeError(f"update MoonEP Python provider: missing {name}")
181+ return npu_patch, Buffer
182+ 
183+ 
184+def _create_moonep_buffer(buffer_type, *, options, **layout):
185+ """Register the process owner before any projection or SHMEM setup."""
186+ global _BUFFER
187+ if _BUFFER is not None:
188+ raise RuntimeError('MoonEP process already owns a Buffer')
189+ try:
190+ buffer = buffer_type(explicitly_destroy=True, **layout, **options)
191+ except BaseException as exc:
192+ fail_stop(exc)
193+ raise
194+ _BUFFER = buffer
195+ return buffer
196+ 
197+ 
198+def initialize_moonep(models=None, *, buffer_options=None):
199+ """Plan synchronous resources, then initialize SHMEM and bind projections."""
200+ del models
201+ global _STRICT_ZERO_COPY, _NATIVE_IDENTITIES, _SYNC_BUFFER_OPTIONS
202+ 
203+ if _FATAL_ERROR is not None:
204+ ensure_admission()
205+ if _BUFFER is not None:
206+ _require_synchronous_buffer()
207+ if buffer_options is not None:
208+ from .buffer_config import synchronous_buffer_options
209+ if synchronous_buffer_options(buffer_options) != _SYNC_BUFFER_OPTIONS:
210+ raise RuntimeError('synchronous Buffer options are frozen until close_moonep()')
211+ return _BUFFER
212+ 
213+ import torch
214+ from mindspeed.args_utils import get_full_args
215+ from mindspeed.core.transformer.moe.moe_feature.moonep.virtual_expert_load_balancer import (
216+ _VirtualExperts, VirtualExpertLoadBalancer,
217+ )
218+ 
219+ args = get_full_args()
220+ validate_moonep_args(args)
221+ managers = _live_managers()
222+ if not managers:
223+ return None
224+ if any(manager.virtual_experts is None for manager in managers):
225+ raise RuntimeError("all local MoonEP managers must bind TEGroupedMLP before setup")
226+ 
227+ first = managers[0]
228+ if any(manager.group is not first.group for manager in managers):
229+ raise RuntimeError("all local MoonEP layers must use one EP process group")
230+ group = first.group
231+ rank_count = int(torch.distributed.get_world_size(group=group))
232+ rank = int(torch.distributed.get_rank(group=group))
233+ projection_shapes = first.virtual_experts.projection_shapes
234+ if any(manager.virtual_experts.projection_shapes != projection_shapes for manager in managers):
235+ raise RuntimeError("synchronous MoonEP requires identical projection shapes across local layers")
236+ if any(
237+ manager.num_local_experts != first.num_local_experts
238+ or manager.num_experts != first.num_experts
239+ or manager.router_topk != first.router_topk
240+ for manager in managers
241+ ):
242+ raise RuntimeError("local MoonEP managers disagree on expert layout")
243+ 
244+ token_capacity = VirtualExpertLoadBalancer.token_capacity(args)
245+ device = int(torch.npu.current_device())
246+ manifest = _manifest(
247+ managers,
248+ rank_count=rank_count,
249+ projection_shapes=projection_shapes,
250+ token_capacity=token_capacity,
251+ )
252+ provider_error = None
253+ try:
254+ npu_patch, Buffer = _load_npu_provider()
255+ from .buffer_config import synchronous_buffer_options
256+ options = synchronous_buffer_options(buffer_options)
257+ except Exception as exc:
258+ provider_error = exc
259+ ready = torch.tensor([0 if provider_error else 1], dtype=torch.int32,
260+ device=torch.device("npu", device))
261+ torch.distributed.all_reduce(ready, op=torch.distributed.ReduceOp.MIN, group=group)
262+ if int(ready.item()) != 1:
263+ raise RuntimeError("MoonEP native provider preflight failed before VMM allocation: "
264+ f"{provider_error or 'another EP rank rejected its provider'}") from provider_error
265+ 
266+ if options:
267+ manifest['buffer_options'] = options
268+ _validate_manifest_across_group(
269+ manifest, group=group, device=device, rank_count=rank_count
270+ )
271+ 
272+ hidden = _expert_hidden_size(first, *projection_shapes)
273+ buffer = _create_moonep_buffer(
274+ Buffer,
275+ S=token_capacity,
276+ H=hidden,
277+ K=int(first.router_topk),
278+ E=int(first.num_experts),
279+ num_ep_ranks=rank_count,
280+ B=int(first.num_local_experts),
281+ group=group,
282+ options=options,
283+ )
284+ _SYNC_BUFFER_OPTIONS = dict(options)
285+ # The process owns the Buffer throughout setup and normal execution.
286+ # Setup errors close admission and propagate to the training launcher.
287+ try:
288+ if options:
289+ from .buffer_config import synchronous_buffer_receipt
290+ backend_error = None
291+ try:
292+ synchronous_buffer_receipt(buffer, options)
293+ except Exception as exc:
294+ backend_error = exc
295+ ready = torch.tensor([0 if backend_error else 1], dtype=torch.int32,
296+ device=torch.device('npu', device))
297+ torch.distributed.all_reduce(ready, op=torch.distributed.ReduceOp.MIN, group=group)
298+ if int(ready.item()) != 1:
299+ raise RuntimeError('synchronous Buffer options rejected before SHMEM initialization: '
300+ f'{backend_error or "another EP rank rejected its effective Buffer settings"}') from backend_error
301+ _VirtualExperts.allocate_shared(
302+ local_experts=first.num_local_experts,
303+ projection_shapes=projection_shapes,
304+ device=device,
305+ )
306+ npu_patch.ShmemRuntime.init_with_buffer(group=group,
307+ enable_udma=any(buffer._ctx.get(f'_{op}_use_udma', False)
308+ for op in ('dispatch', 'combine', 'prefetch', 'grad_reduce')))
309+ buffer._ensure_shmem_views()
310+ _VirtualExperts.bind_symmetric_views()
311+ binding_error = None
312+ try:
313+ for manager in managers:
314+ manager.virtual_experts.prepare_communication_bindings(buffer)
315+ except Exception as exc:
316+ binding_error = exc
317+ ready = torch.tensor([0 if binding_error else 1], dtype=torch.int32,
318+ device=torch.device("npu", device))
319+ torch.distributed.all_reduce(ready, op=torch.distributed.ReduceOp.MIN, group=group)
320+ if int(ready.item()) != 1:
321+ raise RuntimeError("synchronous expert pointer binding failed after SHMEM initialization: "
322+ f"{binding_error or 'another EP rank rejected its expert bindings'}") from binding_error
323+ shmem_identity = npu_patch.runtime_library_info()
324+ if not shmem_identity:
325+ raise RuntimeError("MoonEP could not audit the loaded CANN-SHMEM runtime")
326+ except Exception as exc:
327+ # A collective/native initialization may have begun; terminate training.
328+ fail_stop(exc)
329+ raise
330+ 
331+ _STRICT_ZERO_COPY = bool(getattr(args, "moonep_activation_zero_copy", False))
332+ _NATIVE_IDENTITIES = {
333+ "provider": _native_identity(npu_patch._C),
334+ "shmem": shmem_identity,
335+ }
336+ return _BUFFER
337+ 
338+ 
339+def checkpoint_drain() -> None:
340+ if _BUFFER is None:
341+ return
342+ _require_synchronous_buffer()
343+ from mindspeed.core.transformer.moe.moe_feature.moonep.virtual_expert_load_balancer import _VirtualExperts
344+ 
345+ if _VirtualExperts.active_exact_plan_count:
346+ raise RuntimeError(
347+ "checkpoint save refused while MoonEP exact Autograd plans are active"
348+ )
349+ import torch
350+ 
351+ torch.npu.synchronize()
352+ 
353+ 
354+def _adopt_buffer(buffer):
355+ """Register a caller-supplied Buffer as the process transport owner."""
356+ global _BUFFER
357+ if _BUFFER is not None:
358+ raise RuntimeError('MoonEP process already owns a Buffer')
359+ _BUFFER = buffer
360+ 
361+ 
362+def _forget_buffer(buffer):
363+ global _BUFFER, _STRICT_ZERO_COPY, _NATIVE_IDENTITIES, _SYNC_BUFFER_OPTIONS
364+ if _BUFFER is buffer:
365+ _BUFFER = None
366+ _STRICT_ZERO_COPY = False
367+ _NATIVE_IDENTITIES = None
368+ _SYNC_BUFFER_OPTIONS = None
369+ 
370+ 
371+def _require_synchronous_buffer():
372+ if _BUFFER is not None and _SYNC_BUFFER_OPTIONS is None:
373+ raise RuntimeError("MoonEP process already owns an explicit forward Buffer")
374+ 
375+ 
376+def _ensure_teardown_allowed():
377+ if _FATAL_ERROR is not None:
378+ raise RuntimeError(
379+ 'MoonEP training failed; normal teardown is disabled, terminate the worker'
380+ )
381+ 
382+ 
383+def _destroy_moonep_buffer(release_storage, *, preserve_managers=False):
384+ """Finalize SHMEM and destroy the process Buffer before releasing its banks."""
385+ _ensure_teardown_allowed()
386+ buffer = _BUFFER
387+ if buffer is not None:
388+ from .virtual_expert_load_balancer import _VirtualExperts
389+ import npu_patch
390+ import torch
391+ 
392+ if _VirtualExperts.active_exact_plan_count:
393+ raise RuntimeError(
394+ f"cannot close MoonEP with {_VirtualExperts.active_exact_plan_count} active plans"
395+ )
396+ try:
397+ torch.npu.synchronize()
398+ npu_patch.ShmemRuntime.finalize()
399+ buffer.destroy()
400+ release_storage(buffer)
401+ except BaseException as exc:
402+ fail_stop(exc)
403+ raise
404+ _forget_buffer(buffer)
405+ if not preserve_managers:
406+ _MANAGERS.clear()
407+ 
408+ 
409+def close_moonep(*, _preserve_managers=False) -> None:
410+ """Close the synchronous Buffer and shared expert storage."""
411+ from .virtual_expert_load_balancer import _VirtualExperts
412+ 
413+ _ensure_teardown_allowed()
414+ _require_synchronous_buffer()
415+ managers = _live_managers()
416+ _destroy_moonep_buffer(lambda _: _VirtualExperts.destroy_shared(),
417+ preserve_managers=_preserve_managers)
418+ for manager in managers:
419+ if manager.virtual_experts is not None:
420+ manager.virtual_experts._weight_bindings.clear()
421+ manager.virtual_experts._grad_bindings.clear()
422+ 
423+ 
424+initialize_runtime = initialize_moonep
425+close_runtime = close_moonep
426+ 
427+ 
428+def runtime_or_none():
429+ return _BUFFER
430+ 
431+ 
432+def _activation_tensor_from_pointer(tensor):
433+ from npu_patch.buffer_c import create_sym_tensor_from_ptr
434+ return create_sym_tensor_from_ptr(int(tensor.data_ptr()), tuple(tensor.shape), tensor.dtype, tensor.device)
435+ 
436+ 
437+def activation_alias(tensor, shape=None, dtype=None):
438+ """Use v10's fixed bank with call-local metadata, without copying payload."""
439+ shape = tuple(tensor.shape) if shape is None else shape
440+ dtype = tensor.dtype if dtype is None else dtype
441+ view = tensor.view(dtype).view(shape)
442+ if tensor.requires_grad or tensor.grad_fn is not None:
443+ raise RuntimeError('persistent activation bank acquired Autograd history')
444+ alias = _activation_tensor_from_pointer(view)
445+ if (alias is view or alias._base is not None or alias.requires_grad or alias.grad_fn is not None
446+ or alias.data_ptr() != view.data_ptr() or alias.dtype != view.dtype
447+ or alias.device != view.device or tuple(alias.shape) != tuple(view.shape)
448+ or tuple(alias.stride()) != tuple(view.stride()) or alias.storage_offset() != view.storage_offset()):
449+ raise RuntimeError('MoonEP activation alias must have independent metadata at the same address')
450+ alias._mindspeed_moonep_carrier_owner = tensor
451+ return alias
@@ -0,0 +1,695 @@
1+"""Exact-plan identity and virtual expert ownership for Ascend MoonEP."""
2+ 
3+from __future__ import annotations
4+ 
5+from dataclasses import dataclass, field
6+import weakref
7+ 
8+ 
9+@dataclass(frozen=True)
10+class GenerationKey:
11+ """Rank-comparable identity for one forward or replay execution."""
12+ 
13+ session_epoch: int
14+ pp_rank: int
15+ vpp_chunk: int
16+ layer_key: str
17+ microbatch_id: int
18+ execution_epoch: int = 0
19+ 
20+ def provider_key(self):
21+ return (self.session_epoch, self.pp_rank, self.vpp_chunk,
22+ self.layer_key, self.microbatch_id, self.execution_epoch)
23+ 
24+ 
25+@dataclass(slots=True)
26+class VirtualExpertPlan:
27+ """One exact forward/recompute pass, owned by its Autograd graph."""
28+ 
29+ provider_plan: object
30+ group_counts_2l: object
31+ manager_cookie: object
32+ dispatch_backward_expected: bool
33+ expert_backward_expected: bool
34+ generation_key: GenerationKey | None = None
35+ admitted: bool = False
36+ retired: bool = False
37+ backward_started: bool = False
38+ exact_graph_ref: object = None
39+ source_input: object = None
40+ source_version: int | None = None
41+ padding_mask: object = None
42+ _expert_backward_call: tuple | None = field(default=None, init=False, repr=False, compare=False)
43+ 
44+ 
45+def clear_dispatch_padding(hidden, probs=None, *, cu_seqlens=None, padding_mask=None):
46+ """Zero framework-owned GMM padding after Dispatch and before its consumer.
47+ 
48+ Cache the device mask in VirtualExpertPlan for Z3/R1 redispatches, which do
49+ not return new cumulative counts. Async callers use their existing Q1 wait;
50+ no host read, collective or additional completion event is introduced.
51+ """
52+ import torch
53+ 
54+ with torch.no_grad():
55+ if padding_mask is None:
56+ if cu_seqlens is None:
57+ raise ValueError("Dispatch padding requires counts or its saved mask")
58+ rows = torch.arange(hidden.shape[0], dtype=torch.int32, device=hidden.device)
59+ padding_mask = rows >= cu_seqlens[-1]
60+ if hidden.device.type == 'npu':
61+ cu_seqlens.record_stream(torch.npu.current_stream())
62+ hidden.masked_fill_(padding_mask.unsqueeze(-1), 0)
63+ if probs is not None:
64+ probs.masked_fill_(padding_mask, 0)
65+ if hidden.device.type == 'npu':
66+ padding_mask.record_stream(torch.npu.current_stream())
67+ return padding_mask
68+ 
69+ 
70+def build_physical_counts(
71+ global_cu_seqlens,
72+ *,
73+ rank: int,
74+ local_experts: int,
75+ global_experts: int,
76+ slots: int,
77+ carrier_rows: int | None = None,
78+):
79+ """Return device counts ordered as this rank's L natives followed by B slots.
80+ 
81+ MoonEP uses a fixed-capacity carrier. A rank may receive fewer routed rows
82+ than that capacity, but grouped GMM must still partition every carrier row.
83+ Assign the framework-zeroed suffix to the final slot without a device-to-host
84+ synchronization. clear_dispatch_padding owns this zero-fill contract.
85+ Zero activation rows make this padding mathematically
86+ inert in forward, dgrad, and pointer-target wgrad.
87+ """
88+ import torch
89+ 
90+ if global_cu_seqlens.dtype != torch.int32 or global_cu_seqlens.ndim != 1:
91+ raise TypeError("global_cu_seqlens must be a one-dimensional INT32 tensor")
92+ if not global_cu_seqlens.is_contiguous():
93+ raise ValueError("global_cu_seqlens must be contiguous")
94+ if slots != local_experts:
95+ raise ValueError("synchronous MoonEP requires B == L")
96+ if global_cu_seqlens.numel() != global_experts + slots:
97+ raise ValueError("global_cu_seqlens must describe E native groups followed by B slots")
98+ prefix = torch.zeros(
99+ 1, dtype=global_cu_seqlens.dtype, device=global_cu_seqlens.device
100+ )
@@ -0,0 +1,13 @@
1+"""MoonEP overlap integration, activated by the two-feature registration gate."""
2+from importlib import import_module
3+ 
4+_EXPORTS = {
5+ 'moonep_transformer_block_fb_overlap_init_wrapper': 'transformer_block',
6+ 'get_forward_backward_func_moonep_wrapper': 'adaptor',
7+}
8+ 
9+ 
10+def __getattr__(name):
11+ if name not in _EXPORTS:
12+ raise AttributeError(name)
13+ return getattr(import_module(__name__ + '.' + _EXPORTS[name]), name)
@@ -0,0 +1,207 @@
1+"""Connect MoonEP steps to the original FB schedule selector."""
2+from dataclasses import dataclass
3+from functools import wraps
4+ 
5+import torch
6+ 
7+from megatron.core import parallel_state
8+from megatron.core.utils import get_attr_wrapped_model, get_model_config
9+ 
10+from ..fb_overlap.adaptor import get_forward_backward_func_vpp_overlap_wrapper
11+from ..fb_overlap.vpp_schedules import (
12+ has_pipeline_model_parallel_layout,
13+)
14+from ..moonep import moonep_runtime
15+from . import session as fb_session
16+ 
17+ 
18+_training = None
19+ 
20+ 
21+@dataclass
22+class _TrainingState:
23+ models: tuple
24+ block_config: object = None
25+ config: object = None
26+ sequence_factor: int = 1
27+ training_ready: bool = False
28+ 
29+ 
30+def _validate_optimizer(optimizer):
31+ """Require Megatron's synchronous parameter gathering; never invoke it here."""
32+ if not callable(getattr(optimizer, 'step', None)):
33+ raise TypeError('MoonEP training requires the original optimizer.step')
34+ config = getattr(optimizer, 'config', None)
35+ children = getattr(optimizer, 'chained_optimizers', (optimizer,))
36+ gather_configs = (config, *(getattr(child, 'ddp_config', None) for child in children))
37+ if any(getattr(cfg, name, False) for cfg in gather_configs
38+ for name in ('overlap_param_gather', 'overlap_param_gather_with_optimizer_step')):
39+ raise TypeError('MoonEP FB requires synchronous optimizer parameter gathering')
40+ if getattr(config, 'use_distributed_optimizer', False):
41+ if any(getattr(child, '_defer_param_sync', False) for child in children):
42+ raise TypeError('ordinary MoonEP training requires optimizer parameter gathering without deferral')
43+ 
44+ 
45+def setup_wrapper(fn):
46+ @wraps(fn)
47+ def wrapper(*args, **kwargs):
48+ global _training
49+ result = fn(*args, **kwargs)
50+ 
51+ models = result[0] if isinstance(result, tuple) else getattr(result, 'model', None)
52+ optimizer = result[1] if isinstance(result, tuple) else getattr(result, 'optimizer', None)
53+ if models is None or optimizer is None:
54+ raise TypeError('MoonEP FB setup requires models and an optimizer from setup_model_and_optimizer')
55+ if _training is not None:
56+ raise RuntimeError('MoonEP FB training is already installed')
57+ models = tuple(models) if isinstance(models, (tuple, list)) else (models,)
58+ state = _TrainingState(models)
59+ try:
60+ _setup_training_resources(state, optimizer)
61+ except BaseException as exc:
62+ if fb_session._FORWARD_SESSION is not None:
63+ fb_session.poison_forward_session(exc)
64+ raise
65+ 
66+ _training = state
67+ return result
68+ return wrapper
69+ 
70+ 
71+def _close_training(state):
72+ global _training
73+ moonep_runtime._ensure_teardown_allowed()
74+ fb_session.close_forward_session()
75+ _training = None
76+ 
77+ 
78+def pretrain_wrapper(fn):
79+ @wraps(fn)
80+ def wrapper(*args, **kwargs):
81+ result = fn(*args, **kwargs)
82+ if _training is not None:
83+ _close_training(_training)
84+ return result
85+ return wrapper
86+ 
87+ 
88+def save_checkpoint_wrapper(fn):
89+ @wraps(fn)
90+ def wrapper(*args, **kwargs):
91+ fb_session.checkpoint_drain()
92+ return fn(*args, **kwargs)
93+ return wrapper
94+ 
95+ 
96+def destroy_model_parallel_wrapper(fn):
97+ @wraps(fn)
98+ def wrapper(*args, **kwargs):
99+ if _training is None:
100+ fb_session.close_forward_session()
101+ else:
102+ _close_training(_training)
103+ return fn(*args, **kwargs)
104+ return wrapper
105+ 
106+ 
107+def _setup_training_resources(state, optimizer):
108+ """Unwrap Megatron models and delegate initialization to the session owner."""
109+ blocks = tuple(get_attr_wrapped_model(model, 'decoder') for model in state.models)
110+ state.block_config = blocks[0].config
111+ state.config = get_model_config(state.models[0])
112+ error = None
113+ try:
114+ _validate_optimizer(optimizer)
115+ if state.block_config.tensor_model_parallel_size != parallel_state.get_tensor_model_parallel_world_size():
116+ raise ValueError('MoonEP model TP size differs from initialized parallel state')
117+ state.sequence_factor = state.block_config.tensor_model_parallel_size if state.block_config.sequence_parallel else 1
118+ if (parallel_state.get_pipeline_model_parallel_world_size() > 1
119+ and has_pipeline_model_parallel_layout(state.config)):
120+ raise ValueError('MoonEP requires regular PP/VPP work')
121+ except Exception as exc:
122+ error = exc
123+ fb_session.setup_training_resources(blocks if len(blocks) > 1 else blocks[0], _entry_error=error)
124+ 
125+ 
126+def _prepare_step_plan(arguments):
127+ """Extract schedule shapes and check the Megatron calling convention."""
128+ state = _training
129+ forward_only = arguments.get('forward_only', False)
130+ error, tokens = None, None
131+ try:
132+ if forward_only != (not torch.is_grad_enabled()):
133+ raise ValueError('MoonEP evaluation requires forward_only and no_grad together')
134+ # Megatron installs this callback after model setup; validate at the first training step.
135+ if not forward_only and not state.training_ready:
136+ if not callable(state.config.finalize_model_grads_func):
137+ raise ValueError('ordinary training must install finalize_model_grads_func before the first schedule')
138+ state.training_ready = True
139+ seq, batch, microbatches = arguments['seq_length'], arguments['micro_batch_size'], arguments['num_microbatches']
140+ if any(type(value) is not int or value <= 0 for value in (seq, batch, microbatches)):
141+ raise ValueError('MoonEP requires positive shapes and microbatch count')
142+ if arguments.get('decoder_seq_length') not in (None, seq):
143+ raise ValueError('MoonEP requires matching decoder length')
144+ if arguments.get('adjust_tensor_shapes_fn') is not None:
145+ raise ValueError('MoonEP outer loop excludes dynamic tensor shapes')
146+ if seq % state.sequence_factor:
147+ raise ValueError('MoonEP requires divisible sequence length')
148+ tokens = seq * batch // state.sequence_factor
149+ except Exception as exc:
150+ error = exc
151+ return fb_session.prepare_training_plan(num_microbatches=arguments.get('num_microbatches'),
152+ tokens=tokens, forward_only=forward_only, consumer_stream=torch.npu.current_stream(),
153+ seq_length=arguments.get('seq_length'), micro_batch_size=arguments.get('micro_batch_size'),
154+ eval_group_size=state.config.microbatch_group_size_per_vp_stage if forward_only else None,
155+ _entry_error=error)
156+ 
157+ 
158+def get_forward_backward_func_moonep_wrapper(fn):
159+ """Keep FB selection; prepare, execute and finish each MoonEP step."""
160+ get_fb_schedule = get_forward_backward_func_vpp_overlap_wrapper(fn)
161+ 
162+ @wraps(fn)
163+ def get_schedule(*args, **kwargs):
164+ schedule = get_fb_schedule(*args, **kwargs)
165+ 
166+ def forward_backward_moonep(**arguments):
167+ # 1. Prepare the plan and begin the session's execution scope.
168+ session = _prepare_moonep_step(arguments)
169+ forward_only = arguments.get('forward_only', False)
170+ try:
171+ # 2. Execute the original schedule with the installed Block/Layer patches.
172+ result = schedule(**arguments)
173+ 
174+ # 3. Check completion and finish the session's execution scope.
175+ if session is not None:
176+ fb_session.complete_moonep_step(forward_only=forward_only)
177+ return result
178+ except BaseException as exc:
179+ if session is not None:
180+ fb_session.poison_forward_session(exc)
181+ raise
182+ 
183+ return forward_backward_moonep
184+ 
185+ return get_schedule
186+ 
187+ 
188+def _prepare_moonep_step(arguments):
189+ """Validate model identity, prepare/reuse work, adapt inputs and begin execution."""
190+ state = _training
191+ if state is None:
192+ raise RuntimeError('MoonEP training setup must finish before selecting schedule work')
193+ models = arguments['model']
194+ models = tuple(models) if isinstance(models, (list, tuple)) else (models,)
195+ if len(models) != len(state.models) or any(model is not saved for model, saved in zip(models, state.models)):
196+ raise ValueError('MoonEP schedule models differ from setup models')
197+ forward_only = arguments.get('forward_only', False)
198+ session = _prepare_step_plan(arguments)
199+ 
200+ # The FB training engine indexes one iterator per model chunk.
201+ if (not forward_only and parallel_state.get_pipeline_model_parallel_world_size() > 1
202+ and len(_training.models) == 1 and not isinstance(arguments.get('data_iterator'), list)):
203+ arguments['data_iterator'] = [arguments.get('data_iterator')]
204+ 
205+ if session is not None:
206+ fb_session.begin_moonep_step(forward_only=forward_only)
207+ return session
@@ -0,0 +1,183 @@
1+"""Deterministic pre-init bank sizing from exact lease/final-use intervals.
2+ 
3+The FB schedule supplies intervals through each bank's final use. Setup owns
4+fixed physical pools; each schedule's interval demand must fit those pools.
5+"""
6+ 
7+from dataclasses import dataclass, field
8+import hashlib
9+import heapq
10+import json
11+ 
12+from .async_types import BankKey
13+ 
14+ 
15+_DTYPE_BYTES = {"bf16": 2, "fp32": 4, "int32": 4}
16+ 
17+ 
18+@dataclass(frozen=True, slots=True)
19+class LeaseInterval:
20+ role: str
21+ generation: object
22+ begin: int
23+ final_use: int
24+ shape: tuple[int, ...]
25+ dtype: str
26+ 
27+ 
28+@dataclass(frozen=True, slots=True)
29+class PoolSpec:
30+ count: int
31+ shape: tuple[int, ...]
32+ dtype: str
33+ 
34+ 
35+@dataclass(frozen=True, slots=True)
36+class CapacityPlan:
37+ pools: dict[str, PoolSpec]
38+ assignments: tuple[BankKey, ...]
39+ aliases: dict[str, str] = field(default_factory=dict)
40+ 
41+ @property
42+ def physical_pools(self):
43+ return {role: spec for role, spec in self.pools.items() if role not in self.aliases}
44+ 
45+ def physical_key(self, key):
46+ return BankKey(self.aliases.get(key.role, key.role), key.index)
47+ 
48+ def manifest(self, *, granularity, topology=None):
49+ if type(granularity) is not int or granularity <= 0:
50+ raise ValueError("VMM granularity must be a positive integer")
51+ return {
52+ "schema": 2 if self.aliases else 1,
53+ "lane_count": 1,
54+ "granularity": granularity,
55+ **({"topology": dict(topology)} if topology is not None else {}),
56+ "banks": {role: {"count": spec.count, "shape": list(spec.shape), "dtype": spec.dtype}
57+ for role, spec in sorted(self.physical_pools.items())},
58+ **({"aliases": dict(self.aliases)} if self.aliases else {}),
59+ }
60+ 
61+ def physical_bytes(self, granularity):
62+ if type(granularity) is not int or granularity <= 0:
63+ raise ValueError("VMM granularity must be a positive integer")
64+ total = 0
65+ for spec in self.physical_pools.values():
66+ logical = _DTYPE_BYTES[spec.dtype]
67+ for dimension in spec.shape:
68+ logical *= dimension
69+ total += spec.count * ((logical + granularity - 1) // granularity * granularity)
70+ return total
71+ 
72+ 
73+def derive_capacity(intervals, *, aliases=None):
74+ """Color half-open intervals, including explicitly shared physical pools.
75+ 
76+ Intervals ending at T release their bank before intervals beginning at T.
77+ Equal-start intervals retain caller work order, which is the Q0 schedule's
78+ semantic order. Shapes of one role may vary only within one rank; the
79+ physical bank uses the dimension-wise maximum shape.
80+ """
81+ intervals = tuple(intervals)
82+ aliases = dict(aliases or {})
83+ roles = {lease.role for lease in intervals if isinstance(lease, LeaseInterval)}
84+ if any(source not in roles or target not in roles or source == target or target in aliases
85+ for source, target in aliases.items()):
86+ raise ValueError('bank aliases must name present roles and direct physical pools')
87+ grouped = {}
88+ for position, lease in enumerate(intervals):
89+ if not isinstance(lease, LeaseInterval):
90+ raise TypeError("expected LeaseInterval")
91+ if not isinstance(lease.role, str) or not lease.role:
92+ raise ValueError("lease role must be nonempty")
93+ if lease.generation is None or type(lease.begin) is not int or type(lease.final_use) is not int:
94+ raise ValueError("lease needs exact generation and integer boundaries")
95+ if lease.begin < 0 or lease.final_use <= lease.begin:
96+ raise ValueError("final use must follow acquisition")
97+ if (not isinstance(lease.shape, tuple) or not lease.shape or
98+ any(type(dimension) is not int or dimension <= 0 for dimension in lease.shape)):
99+ raise ValueError("lease shape must contain positive integer dimensions")
100+ if lease.dtype not in _DTYPE_BYTES:
101+ raise ValueError("unsupported bank dtype")
102+ grouped.setdefault(aliases.get(lease.role, lease.role), []).append((position, lease))
103+ assignments = [None] * len(intervals)
104+ pools = {}
105+ for role, entries in grouped.items():
106+ dtype = entries[0][1].dtype
107+ rank = len(entries[0][1].shape)
108+ if any(lease.dtype != dtype or len(lease.shape) != rank for _, lease in entries):
109+ raise ValueError("one bank role needs one dtype and shape rank")
110+ shape = tuple(max(lease.shape[axis] for _, lease in entries) for axis in range(rank))
111+ active, free = [], []
112+ count = 0
113+ for position, lease in sorted(entries, key=lambda pair: (pair[1].begin, pair[0])):
114+ while active and active[0][0] <= lease.begin:
115+ _, available = heapq.heappop(active)
116+ heapq.heappush(free, available)
117+ if free:
118+ index = heapq.heappop(free)
119+ else:
120+ index = count
121+ count += 1
122+ assignments[position] = BankKey(lease.role, index)
123+ heapq.heappush(active, (lease.final_use, index))
124+ pools[role] = PoolSpec(count, shape, dtype)
125+ for source, target in aliases.items():
126+ pools[source] = pools[target]
127+ return CapacityPlan(pools, tuple(assignments), aliases)
128+ 
129+ 
130+def manifest_digest(manifest):
131+ """Address-free digest; callers compare it before one-shot SHMEM init."""
132+ payload = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode("utf-8")
133+ return hashlib.sha256(payload).hexdigest()
134+ 
135+ 
136+def local_token_capacity(tokens, *, tp_size=1, sequence_parallel=False):
137+ """Normalize the existing local token count for the sequence-parallel shard."""
138+ if type(tp_size) is not int or tp_size <= 0:
139+ raise ValueError('MoonEP requires positive TP size')
140+ factor = tp_size if sequence_parallel else 1
141+ if type(tokens) is not int or tokens <= 0 or tokens % factor:
142+ raise ValueError('MoonEP requires positive tokens divisible by the SP factor')
143+ return tokens // factor
144+ 
145+ 
146+def static_resource_capacity(layout, tokens, *, activation_zero_copy):
147+ """Allocate the supported FB upper bound without inventing microbatch work."""
148+ if type(tokens) is not int or tokens <= 0:
149+ raise ValueError('positive token capacity required')
150+ if not layout['has_moe']:
151+ return CapacityPlan({}, ())
152+ local_experts = layout['local_experts']
153+ fc1, fc2 = layout['projection_shapes']
154+ pools = {role: PoolSpec(count, (local_experts, *shape), dtype)
155+ for role, count, shape, dtype in (
156+ ('fc1_weight', 2, fc1, 'bf16'), ('fc2_weight', 2, fc2, 'bf16'),
157+ ('fc1_grad', 1, fc1, 'fp32'), ('fc2_grad', 1, fc2, 'fp32'))}
158+ aliases = {}
159+ if activation_zero_copy:
160+ shape = (tokens * layout['topk'], layout['hidden'])
161+ pools.update({role: PoolSpec(1, shape, 'bf16') for role in ('Z1', 'R1', 'Z4', 'Z3', 'Z2')})
162+ aliases['Z2'] = 'Z3'
163+ return CapacityPlan(pools, (), aliases)
164+ 
165+ 
166+def admit_plan_capacity(needed, available, *, activation_zero_copy):
167+ """Check demand against fixed backing and keep the resource's alias identity."""
168+ pools = dict(needed.pools)
169+ aliases = dict(available.aliases) if activation_zero_copy else {}
170+ for source, target in aliases.items():
171+ if source in pools and target not in pools:
172+ pools[target] = pools[source]
173+ for role, spec in pools.items():
174+ if role in ('Z1', 'Z2', 'Z3', 'Z4', 'R1') and not activation_zero_copy:
175+ continue
176+ physical = aliases.get(role, role)
177+ limit = available.physical_pools.get(physical)
178+ if (limit is None or spec.dtype != limit.dtype or spec.count > limit.count or
179+ len(spec.shape) != len(limit.shape) or
180+ any(value > maximum for value, maximum in zip(spec.shape, limit.shape))):
181+ raise ValueError(f'MoonEP plan exceeds initialized capacity: {role}')
182+ return CapacityPlan(pools, needed.assignments,
183+ {source: target for source, target in aliases.items() if source in pools})
@@ -0,0 +1,23 @@
1+"""Address-free schedule/capacity values; no operation or lifetime protocol."""
2+from dataclasses import dataclass
3+from enum import Enum
4+ 
5+ 
6+class OperationKind(str, Enum):
7+ PLAN_DISPATCH = "PLAN_DISPATCH"
8+ DISPATCH = "DISPATCH"
9+ PREFETCH_FC1 = "PREFETCH_FC1"
10+ PREFETCH_FC2 = "PREFETCH_FC2"
11+ COMBINE = "COMBINE"
12+ DISPATCH_BWD = "DISPATCH_BWD"
13+ REDISPATCH = "REDISPATCH"
14+ REDUCE_FC2 = "REDUCE_FC2"
15+ REDUCE_FC1 = "REDUCE_FC1"
16+ COMBINE_BWD = "COMBINE_BWD"
17+ EMPTY = "EMPTY"
18+ 
19+ 
20+@dataclass(frozen=True, slots=True)
21+class BankKey:
22+ role: str
23+ index: int
@@ -0,0 +1 @@
1+"""MoonEP routed/shared expert computation and common graph helpers."""
@@ -0,0 +1,161 @@
1+"""Expert Autograd tape and call-local delayed wgrad, without communication state."""
2+from contextlib import contextmanager
3+from functools import lru_cache, wraps
4+ 
5+from . import utils
6+ 
7+def _manual_grad(fn):
8+ @wraps(fn)
9+ def wrapper(*args, **kwargs):
10+ import torch
11+ with torch.no_grad():
12+ return fn(*args, **kwargs)
13+ return wrapper
14+ 
15+ 
16+@_manual_grad
17+@utils._experimental_limited(32, 56)
18+def forward_fc1(session, hidden, sources, slot, counts):
19+ from mindspeed.ops.gmm import npu_gmm_v5_out
20+ 
21+ shape = (hidden.shape[0], sources[0].shape[0])
22+ if session.get("manifest", {}).get("backward_keys"):
23+ # F0 and F1 may both remain live when B0 starts.
24+ out = hidden.new_empty(shape)
25+ else:
26+ if session["fc1_out"] is None or tuple(session["fc1_out"].shape) != shape:
27+ session["fc1_out"] = hidden.new_empty(shape)
28+ out = session["fc1_out"]
29+ refs = tuple(weight.t() for weight in (*sources, *tuple(slot)))
30+ npu_gmm_v5_out(hidden, refs, out, counts)
31+ return out
32+ 
33+ 
34+def expert_activation(fc1_out, experts):
35+ """SiTU is owned by the model module; ordinary TE SiLU is a scalar SwiGLU gate."""
36+ if getattr(experts, 'activation_kind', 'swiglu') == 'situ':
37+ return experts.activation(fc1_out)
38+ if getattr(experts, 'activation_kind', 'swiglu') != 'swiglu':
39+ raise ValueError('unsupported MoonEP expert activation protocol')
40+ import torch.nn.functional as F
41+ gate, linear = fc1_out.chunk(2, dim=-1)
42+ return F.silu(gate) * linear
43+ 
44+ 
45+@_manual_grad
46+@utils._experimental_limited(32, 56)
47+def forward_activate(fc1_out, probs, experts):
48+ activated = expert_activation(fc1_out, experts)
49+ weighted = (activated * probs.unsqueeze(-1)).to(activated.dtype)
50+ return activated, weighted
51+ 
52+ 
53+@_manual_grad
54+@utils._experimental_limited(32, 56)
55+def forward_fc2(weighted, sources, slot, counts, out):
56+ from mindspeed.ops.gmm import npu_gmm_v5_out
57+ 
58+ refs = tuple(weight.t() for weight in (*sources, *tuple(slot)))
59+ npu_gmm_v5_out(weighted, refs, out, counts)
60+ 
61+ 
62+@contextmanager
63+def expert_backward(plan, *, weights=(), output=None):
64+ """Supply already ordered weights/dX bank; collect only this call's dW tasks."""
65+ # The Autograd worker and the schedule can run on different threads.
66+ if plan._expert_backward_call is not None:
67+ raise RuntimeError('expert backward collector is already active for this plan')
68+ tasks = []
69+ plan._expert_backward_call = (plan, weights, output, tasks)
70+ try:
71+ yield tasks
72+ finally:
73+ plan._expert_backward_call = None
74+ 
75+ 
76+def _backward_call(plan):
77+ call = plan._expert_backward_call
78+ if call is None or call[0] is not plan:
79+ raise RuntimeError('expert backward requires this exact call and a local dW collector')
80+ return call
81+ 
82+ 
83+def run_wgrad(task, *, restored_input=None, remote_targets=()):
84+ """Consume one delayed task. Communication is owned by the calling schedule."""
85+ import torch
86+ kind, x, dy, targets, counts, fusion = task
87+ x = restored_input if x is None else x
88+ if x is None:
89+ raise RuntimeError('FC1 wgrad requires the restored original expert input')
90+ with torch.no_grad(), utils._experimental_stream_limit(32 if kind == 'routed' else 28, 56):
91+ if kind == 'routed':
92+ from mindspeed.ops.gmm import npu_grouped_matmul_add_ptr_
93+ npu_grouped_matmul_add_ptr_(dy, x, counts, targets + tuple(remote_targets))
94+ elif fusion:
95+ import fused_weight_gradient_mlp_cuda
96+ if targets.dtype == torch.float32:
97+ fused_weight_gradient_mlp_cuda.wgrad_gemm_accum_fp32(x, dy, targets)
98+ else:
99+ fused_weight_gradient_mlp_cuda.wgrad_gemm_accum_fp16(x, dy, targets)
100+ else:
101+ targets.add_(dy.t().matmul(x))
102+ 
103+ 
104+@lru_cache(maxsize=1)
105+def _types():
106+ import torch
107+ from ...moonep import moonep_runtime as runtime
108+ from .. import session as fb_session
109+ 
110+ class RoutedExperts(torch.autograd.Function):
111+ @staticmethod
112+ def forward(ctx, hidden, probs, plan, experts, buffers):
113+ slots, out = buffers
114+ session = fb_session.get_forward_session()
115+ weights = tuple(experts.weight_refs('fc1')) + tuple(experts.weight_refs('fc2'))
116+ counts = plan.group_counts_2l
117+ fc1 = forward_fc1(session, hidden, experts.weight_refs('fc1'), slots[0], counts)
118+ activated, weighted = forward_activate(fc1, probs, experts)
119+ forward_fc2(weighted, experts.weight_refs('fc2'), slots[1], counts, out)
120+ ctx.plan, ctx.experts = plan, experts
121+ ctx.versions = tuple((w._version, w.data_ptr()) for w in weights)
122+ # Forward activation banks are released before B. Keep an owned
123+ # probability snapshot, never a view of their reusable storage.
124+ ctx.save_for_backward(fc1, activated, weighted, runtime.snapshot_route_probs(probs), *weights)
125+ return out
126+ 
127+ @staticmethod
128+ @torch.autograd.function.once_differentiable
129+ def backward(ctx, dy):
130+ from mindspeed.ops.gmm import npu_gmm_v5_out
131+ from mindspeed.core.transformer.moe.moe_feature.fb_overlap.modules.utils import run_graph_backward
132+ plan, slots, out, tasks = _backward_call(ctx.plan)
133+ if len(slots) != 2 or out is None:
134+ raise RuntimeError('routed backward requires prefetched weights and the current dX bank')
135+ fc1, activated, weighted, probs, *weights = ctx.saved_tensors
136+ if tuple((w._version, w.data_ptr()) for w in weights) != ctx.versions:
137+ raise RuntimeError('expert Parameter changed between forward and backward')
138+ experts, counts = ctx.experts, plan.group_counts_2l
139+ with utils._experimental_stream_limit(32, 56):
140+ dweighted = torch.empty_like(weighted)
141+ npu_gmm_v5_out(dy, experts.weight_refs('fc2') + tuple(slots[1]), dweighted, counts)
142+ with torch.enable_grad():
143+ leaf = fc1.detach().requires_grad_(True)
144+ activation = expert_activation(leaf, experts)
145+ run_graph_backward((activation, None), (dweighted * probs[:, None]).to(activation.dtype),
146+ keep_graph=True, keep_grad=True)
147+ dfc1 = leaf.grad
148+ with utils._experimental_stream_limit(32, 64):
149+ dprobs = (dweighted.float() * activated.float()).sum(-1).to(probs.dtype)
150+ npu_gmm_v5_out(dfc1, experts.weight_refs('fc1') + tuple(slots[0]), out, counts)
151+ tasks.extend((('routed', weighted, dy, experts.grad_targets('fc2'), counts, False),
152+ ('routed', None, dfc1, experts.grad_targets('fc1'), counts, False)))
153+ return out, dprobs, None, None, None
154+ 
155+ return RoutedExperts,
156+ 
157+ 
158+def routed_forward(hidden, probs, plan, experts, slots, out):
159+ # The bank is a backend output, not an Autograd input/edge. Do not mutate
160+ # the runtime's persistent Tensor wrapper when attaching its grad_fn.
161+ return _types()[0].apply(hidden, probs, plan, experts, (slots, out.detach()))
@@ -0,0 +1,95 @@
1+"""Shared expert computation and Autograd; dW uses the exact plan's collector."""
2+from contextlib import nullcontext
3+from functools import lru_cache
4+ 
5+from . import utils
6+from .experts import _backward_call
7+ 
8+ 
9+@lru_cache(maxsize=1)
10+def _types():
11+ import torch
12+ 
13+ class SharedFC1(torch.autograd.Function):
14+ @staticmethod
15+ def forward(ctx, hidden, weights, config, plan, build_graph):
16+ with utils._experimental_stream_limit(28, 56):
17+ fc1 = torch.nn.functional.linear(hidden, weights[0].detach())
18+ # Autograd disables grad inside Function.forward, so the caller
19+ # supplies its mode for the saved SwiGLU backward graph.
20+ with torch.enable_grad() if build_graph else nullcontext():
21+ leaf = fc1.detach().requires_grad_(True) if build_graph else fc1
22+ if getattr(config, 'bias_activation_fusion', False):
23+ from megatron.core.fusions.fused_bias_swiglu import bias_swiglu_impl
24+ activation = bias_swiglu_impl(leaf, None, getattr(config, 'activation_func_fp8_input_store', False))
25+ else:
26+ gate, value = leaf.chunk(2, -1)
27+ activation = torch.nn.functional.silu(gate) * value
28+ if build_graph:
29+ ctx.save_for_backward(hidden, leaf, activation, *weights)
30+ ctx.versions = tuple((w._version, w.data_ptr()) for w in weights)
31+ ctx.config, ctx.plan = config, plan
32+ ctx.target = getattr(weights[0], 'main_grad', None)
33+ ctx.target_address = ctx.target.data_ptr() if ctx.target is not None else None
34+ return activation.detach()
35+ 
36+ @staticmethod
37+ @torch.autograd.function.once_differentiable
38+ def backward(ctx, dy):
39+ from mindspeed.core.transformer.moe.moe_feature.fb_overlap.modules.utils import run_graph_backward
40+ hidden, leaf, activation, *weights = ctx.saved_tensors
41+ if tuple((w._version, w.data_ptr()) for w in weights) != ctx.versions:
42+ raise RuntimeError('shared Parameters changed before backward')
43+ if weights[0].main_grad is not ctx.target or ctx.target.data_ptr() != ctx.target_address:
44+ raise RuntimeError('shared FC1 main_grad changed before backward')
45+ with utils._experimental_stream_limit(28, 56):
46+ run_graph_backward((activation, None), dy, keep_graph=True, keep_grad=True)
47+ dx = leaf.grad @ weights[0].detach()
48+ _backward_call(ctx.plan)[3].append(('shared', hidden, leaf.grad, weights[0].main_grad, None,
49+ getattr(ctx.config, 'gradient_accumulation_fusion', False)))
50+ return dx, None, None, None, None
51+ 
52+ class SharedFC2(torch.autograd.Function):
53+ @staticmethod
54+ def forward(ctx, hidden, weights, config, plan):
55+ ctx.save_for_backward(hidden, *weights)
56+ ctx.config, ctx.plan = config, plan
57+ ctx.versions = tuple((w._version, w.data_ptr()) for w in weights)
58+ ctx.target = getattr(weights[1], 'main_grad', None)
59+ ctx.target_address = ctx.target.data_ptr() if ctx.target is not None else None
60+ with utils._experimental_stream_limit(28, 56):
61+ return torch.nn.functional.linear(hidden, weights[1].detach())
62+ 
63+ @staticmethod
64+ @torch.autograd.function.once_differentiable
65+ def backward(ctx, dy):
66+ hidden, *weights = ctx.saved_tensors
67+ if tuple((w._version, w.data_ptr()) for w in weights) != ctx.versions:
68+ raise RuntimeError('shared Parameters changed before backward')
69+ if weights[1].main_grad is not ctx.target or ctx.target.data_ptr() != ctx.target_address:
70+ raise RuntimeError('shared FC2 main_grad changed before backward')
71+ with utils._experimental_stream_limit(28, 56):
72+ dx = dy @ weights[1].detach()
73+ _backward_call(ctx.plan)[3].append(('shared', hidden, dy, weights[1].main_grad, None,
74+ getattr(ctx.config, 'gradient_accumulation_fusion', False)))
75+ return dx, None, None, None
76+ 
77+ return SharedFC1, SharedFC2
78+ 
79+ 
80+def shared_fc1(hidden, layer, plan, weights):
81+ import torch
82+ 
83+ hidden = hidden.reshape(-1, hidden.shape[-1])
84+ if getattr(layer.config, 'sequence_parallel', False):
85+ from megatron.core.tensor_parallel.mappings import gather_from_sequence_parallel_region
86+ hidden = gather_from_sequence_parallel_region(hidden, group=layer.mlp.shared_experts.tp_group)
87+ return _types()[0].apply(hidden, weights, layer.mlp.shared_experts.config, plan, torch.is_grad_enabled())
88+ 
89+ 
90+def shared_fc2(hidden, layer, plan, weights):
91+ output = _types()[1].apply(hidden, weights, layer.mlp.shared_experts.config, plan)
92+ if getattr(layer.config, 'sequence_parallel', False):
93+ from megatron.core.tensor_parallel.mappings import reduce_scatter_to_sequence_parallel_region
94+ output = reduce_scatter_to_sequence_parallel_region(output, group=layer.mlp.shared_experts.tp_group)
95+ return output