Draft
[WIP]dev_npu_async #3
&NewgateAdd on 22 days ago
[WIP]dev_npu_async #3
Draft
Merged fromdev_npu_asyncintofix/moonep-33d7cfb
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: noqa | 4 | +"""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_util | 6 | +# MoonEP contract/config imports must remain usable before Megatron/NPU bootstrap. |
| 62 | -from mindspeed.core.transformer.moe.grouped_mlp import GroupedMLP | 7 | +_EXPORTS = { |
| 63 | -from mindspeed.core.transformer.moe.moe_utils import topk_softmax_with_capacity | 8 | + 'parallel_state': ('megatron.core', 'parallel_state'), |
| 64 | -from mindspeed.args_utils import get_full_args as get_args | 9 | + '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_detach | 1 | +"""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_forward | 2 | +from importlib import import_module as _import_module |
| 3 | -from .transformer_block import transformer_block_fb_overlap_init_wrapper, mtp_block_fb_overlap_forward_wrapper | 3 | + |
| 4 | -from .vpp_schedules import forward_backward_pipelining_with_interleaving | 4 | +_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 | + | ||
| 33 | def attention_forward( | 40 | def 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_output | 67 | 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 | |||
| 16 | PREMUTE_FINISH_EVENT = None | 16 | PREMUTE_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 | + | ||
| 19 | class MindSpeedMOEAlltoAllFbOverlapTokenDispatcher(MoEAlltoAllTokenDispatcher): | 29 | class MindSpeedMOEAlltoAllFbOverlapTokenDispatcher(MoEAlltoAllTokenDispatcher): |
| 20 | OVERLAP_STREAM = None | 30 | 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 output | 502 | # 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 = False | 72 | self.is_moe_layer = False |
| 73 | self.layer = layer | 73 | 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 = args | 82 | 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 = None | 140 | self.act_ckpt_manager = None |
| 134 | self.remote_hot_act_ckpt_manager = None | 141 | 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 = args | 150 | self.layer_inputs = args |
| 138 | 151 | ||
| @@ -167,7 +167,7 @@ class WeightGradStore: | |||
| 167 | cls._pop_te_linears() | 167 | cls._pop_te_linears() |
| 168 | return | 168 | 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].grad | 94 | model_graph[-1].mlp_mhc_post_graph[1].grad |
| 95 | ) # get final_layernorm input_tensor.grad | 95 | ) # 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.grad | 97 | + 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_step | 99 | # 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.grad | 133 | 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.grad | 135 | + 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 | |||
| 7 | from megatron.core.utils import make_viewless_tensor | 7 | from megatron.core.utils import make_viewless_tensor |
| 8 | from mindspeed.args_utils import get_full_args | 8 | from mindspeed.args_utils import get_full_args |
| 9 | from mindspeed.core.tensor_parallel.random import CheckpointWithoutOutput | 9 | from mindspeed.core.tensor_parallel.random import CheckpointWithoutOutput |
| 10 | -from ..modules.attention import attention_forward | 10 | +from ..modules.attention import attention_forward, has_standalone_norm |
| 11 | from ..modules.utils import ( | 11 | from ..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_states | 304 | 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_out | 327 | 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 | |||
| 13 | from mindspeed.core.transformer.moe.comm_utils import async_all_to_all | 13 | from mindspeed.core.transformer.moe.comm_utils import async_all_to_all |
| 14 | from mindspeed.core.tensor_parallel.random import CheckpointWithoutOutput | 14 | from mindspeed.core.tensor_parallel.random import CheckpointWithoutOutput |
| 15 | from ..modules.weight_grad_store import WeightGradStore | 15 | from ..modules.weight_grad_store import WeightGradStore |
| 16 | -from ..modules.attention import attention_forward, set_async_alltoall_inputs, get_async_alltoall_outputs | 16 | +from ..modules.attention import attention_forward, has_standalone_norm, set_async_alltoall_inputs, get_async_alltoall_outputs |
| 17 | from ..modules.utils import ( | 17 | from ..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_out | 745 | 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_out | 751 | 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 = False | 218 | + 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 = 0 | 221 | 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 = True | 225 | checkpoint = True |
| 225 | if self.config.recompute_method == 'uniform': | 226 | if self.config.recompute_method == 'uniform': |
| 226 | - assert self.config.recompute_num_layers == 1 | 227 | + assert self.config.recompute_num_layers > 0 |
| 227 | checkpoint = True | 228 | 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, context | 348 | 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 = False | 351 | + 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 = 0 | 354 | recompute_skip_num_layers = 0 |
| @@ -358,7 +361,7 @@ def transformer_block_forward_backward_overlaping( | |||
| 358 | ): | 361 | ): |
| 359 | checkpoint = True | 362 | 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 == 1 | 364 | + assert fwd_block.config.recompute_num_layers > 0 |
| 362 | checkpoint = True | 365 | checkpoint = True |
| 363 | bwd_layer_graph = bwd_block_graphs.pop(-1) if bwd_block_graphs else None | 366 | bwd_layer_graph = bwd_block_graphs.pop(-1) if bwd_block_graphs else None |
| 364 | cur_p2p_params = pp_comm_params | 367 | 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_states | 456 | 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 grad | 466 | # should call backward first for final_layernorm and postprocess grad |
| 458 | layer_output_grad = block_output_grad | 467 | 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_grad | 472 | 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_graph | 148 | 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) | |||
| 34 | Shape = Union[List[int], torch.Size] | 34 | Shape = 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 | + | ||
| 37 | def has_pipeline_model_parallel_layout(config): | 54 | def 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 = None | 178 | 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.forward | 300 | 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_func | 303 | + return fn(data_iterator, model) |
| 283 | - | 304 | + finally: |
| 284 | - return out | 305 | + if had_instance_forward: |
| 306 | + model.forward = orig_model_forward_func | ||
| 307 | + else: | ||
| 308 | + vars(model).pop('forward', None) | ||
| 285 | 309 | ||
| 286 | return wrapper | 310 | return wrapper |
| 287 | 311 | ||
| @@ -445,11 +469,8 @@ def forward_backward_pipelining_with_interleaving( | |||
| 445 | num_warmup_microbatches = total_num_microbatches | 469 | num_warmup_microbatches = total_num_microbatches |
| 446 | all_warmup_microbatches = True | 470 | all_warmup_microbatches = True |
| 447 | else: | 471 | else: |
| 448 | - num_warmup_microbatches = (pipeline_parallel_size - pipeline_parallel_rank - 1) * 2 | 472 | + num_warmup_microbatches = get_interleaved_warmup( |
| 449 | - num_warmup_microbatches += (num_model_chunks - 1) * pipeline_parallel_size | 473 | + 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_microbatches | 474 | num_microbatches_remaining = total_num_microbatches - num_warmup_microbatches |
| 454 | 475 | ||
| 455 | # Checkpoint the activations of partial Transformer layers in a number of micro-batches | 476 | # 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 chunks | 488 | # 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 - 1 | 505 | model_chunk_id = num_model_chunks - model_chunk_id - 1 |
| 484 | return model_chunk_id | 506 | 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_size | 508 | + 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 forward | 512 | 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_tensor | 649 | 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_shape | 824 | 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 = None | 939 | 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 tensors | 965 | + 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_shape | 980 | 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_store | 1010 | 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 | ||
Amindspeed/core/transformer/moe/moe_feature/moonep/moonep_contract.py+87-0File content is under review, please try again later
| @@ -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 | ||
Amindspeed/core/transformer/moe/moe_feature/moonep/moonep_runtime.py+451-0File content is under review, please try again later
| @@ -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) | ||
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/adaptor.py+207-0File content is under review, please try again later
| @@ -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())) | ||
Amindspeed/core/transformer/moe/moe_feature/moonep_fb_overlap/modules/utils.py+246-0File content is under review, please try again later
Mmindspeed/features_manager/moe/fb_overlap.py+25-11File content is under review, please try again later
Amindspeed/features_manager/moe/moonep_fb_overlap.py+105-0File content is under review, please try again later
Atests_extend/system_tests/deepseek/pretrain_deepseek_v3_moonep.py+54-0File content is under review, please try again later