已合并
[pytorch][bugfix] align minicpm loss #3297
wx_4e191bb7af创建于 2025年9月11日
[pytorch][bugfix] align minicpm loss #3297
已合并
wx_4e191bb7af创建于 2025年9月11日
refs/pull/3297/head合入到master
3 个文件变更+132-2
Mexamples/mcore/minicpm/ckpt_convert_minicpm_moe_hf2mcore.sh+1-0
@@ -15,4 +15,5 @@ python convert_ckpt.py \
15 --target-pipeline-parallel-size 4 \15 --target-pipeline-parallel-size 4 \
16 --target-expert-parallel-size 2 \16 --target-expert-parallel-size 2 \
17 --model-type-hf minicpm-moe \17 --model-type-hf minicpm-moe \
18+ --moe-grouped-gemm \
18 --params-dtype bf1619 --params-dtype bf16
Mexamples/mcore/minicpm/pretrain_minicpm_8x2b.sh+4-2
@@ -24,8 +24,10 @@ MOE_ARGS="
24 --moe-router-topk 2 \24 --moe-router-topk 2 \
25 --moe-router-load-balancing-type aux_loss \25 --moe-router-load-balancing-type aux_loss \
26 --moe-aux-loss-coeff 0.01 \26 --moe-aux-loss-coeff 0.01 \
27- --moe-token-dispatcher-type allgather \27+ --moe-token-dispatcher-type alltoall_seq \
28+ --moe-alltoall-overlap-comm \
28 --moe-permutation-async-comm \29 --moe-permutation-async-comm \
30+ --moe-permute-fusion \
29 --moe-grouped-gemm \31 --moe-grouped-gemm \
30 --moe-layer-freq -1 \32 --moe-layer-freq -1 \
31 --first-k-dense-replace -1 \33 --first-k-dense-replace -1 \
@@ -56,6 +58,7 @@ GPT_ARGS="
56 --micro-batch-size 1 \58 --micro-batch-size 1 \
57 --global-batch-size 128 \59 --global-batch-size 128 \
58 --make-vocab-size-divisible-by 1 \60 --make-vocab-size-divisible-by 1 \
61+ --gemm-gradient-accumulation-fusion \
59 --lr 1.25e-5 \62 --lr 1.25e-5 \
60 --train-iters 5000 \63 --train-iters 5000 \
61 --lr-decay-style cosine \64 --lr-decay-style cosine \
@@ -78,7 +81,6 @@ GPT_ARGS="
78 --adam-beta1 0.9 \81 --adam-beta1 0.9 \
79 --initial-loss-scale 65536 \82 --initial-loss-scale 65536 \
80 --adam-beta2 0.95 \83 --adam-beta2 0.95 \
81- --no-gradient-accumulation-fusion \
82 --no-load-optim \84 --no-load-optim \
83 --no-load-rng \85 --no-load-rng \
84 --use-distributed-optimizer \86 --use-distributed-optimizer \
Mmindspeed_llm/core/transformer/transformer_layer.py+127-0
@@ -14,12 +14,15 @@
14# limitations under the License.14# limitations under the License.
15 15 
16import math16import math
17+from typing import Any, Dict, Optional, Tuple
18+from torch import Tensor
17 19 
18from megatron.core import tensor_parallel20from megatron.core import tensor_parallel
19from megatron.core.transformer.transformer_layer import TransformerLayerSubmodules21from megatron.core.transformer.transformer_layer import TransformerLayerSubmodules
20from megatron.core.utils import WrappedTensor, deprecate_inference_params22from megatron.core.utils import WrappedTensor, deprecate_inference_params
21from megatron.core.transformer.transformer_layer import TransformerLayer as MegatronTransformerLayer23from megatron.core.transformer.transformer_layer import TransformerLayer as MegatronTransformerLayer
22from megatron.core.transformer.transformer_config import TransformerConfig24from megatron.core.transformer.transformer_config import TransformerConfig
25+from megatron.core.packed_seq_params import PackedSeqParams
23from megatron.core.transformer.moe.moe_layer import MoELayer26from megatron.core.transformer.moe.moe_layer import MoELayer
24from megatron.core.transformer.moe.experts import GroupedMLP, SequentialMLP27from megatron.core.transformer.moe.experts import GroupedMLP, SequentialMLP
25from megatron.core.utils import make_viewless_tensor28from megatron.core.utils import make_viewless_tensor
@@ -58,6 +61,130 @@ class TransformerLayer(MegatronTransformerLayer):
58 self.mtp_idx = 061 self.mtp_idx = 0
59 self.self_attention.core_attention.mtp_idx = 062 self.self_attention.core_attention.mtp_idx = 0
60 63 
64+ def _forward_attention(
65+ self,
66+ hidden_states: Tensor,
67+ attention_mask: Optional[Tensor] = None,
68+ context: Optional[Tensor] = None,
69+ context_mask: Optional[Tensor] = None,
70+ rotary_pos_emb: Optional[Tensor] = None,
71+ rotary_pos_cos: Optional[Tensor] = None,
72+ rotary_pos_sin: Optional[Tensor] = None,
73+ attention_bias: Optional[Tensor] = None,
74+ inference_context: Optional[Any] = None,
75+ packed_seq_params: Optional[PackedSeqParams] = None,
76+ sequence_len_offset: Optional[Tensor] = None,
77+ *,
78+ inference_params: Optional[Any] = None,
79+ ):
80+ """
81+ Perform a forward pass through the attention layer and the layernorms before and after
82+ the attention operations.
83+ 
84+ Args:
85+ hidden_states (Tensor): Input tensor of shape [s, b, h] where s is sequence length,
86+ b is batch size, and h is hidden size.
87+ attention_mask (Tensor): Mask tensor for self-attention.
88+ context (Tensor, optional): Context tensor for cross-attention.
89+ context_mask (Tensor, optional): Mask tensor for cross-attention.
90+ rotary_pos_emb (Tensor, optional): Rotary positional embeddings.
91+ attention_bias (Tensor, optional): Bias tensor for Q * K.T.
92+ inference_context (object, optional): Parameters for inference-time optimizations.
93+ packed_seq_params (object, optional): Parameters for packed sequence processing.
94+ sequence_len_offset (Tensor, optional): Offset along sequence dimension
95+ during inference.
96+ 
97+ Returns:
98+ Tuple[Tensor, Tensor, Tensor]: A tuple containing:
99+ pre_mlp_layernorm_output (Tensor): Transformed hidden states before the MLP.
100+ residual (Tensor): Residual connection.
101+ context (Tensor): Updated context tensor if cross-attention is used,
102+ otherwise None.
103+ """
104+ args = get_args()
105+ inference_context = deprecate_inference_params(inference_context, inference_params)
106+ 
107+ # Residual connection.
108+ residual = hidden_states
109+ 
110+ # Optional Input Layer norm
111+ if self.recompute_input_layernorm:
112+ self.input_layernorm_checkpoint = tensor_parallel.CheckpointWithoutOutput()
113+ input_layernorm_output = self.input_layernorm_checkpoint.checkpoint(
114+ self.input_layernorm, hidden_states
115+ )
116+ else:
117+ input_layernorm_output = self.input_layernorm(hidden_states)
118+ 
119+ # Self attention.
120+ attention_output_with_bias = self.self_attention(
121+ input_layernorm_output,
122+ attention_mask=attention_mask,
123+ inference_context=inference_context,
124+ rotary_pos_emb=rotary_pos_emb,
125+ rotary_pos_cos=rotary_pos_cos,
126+ rotary_pos_sin=rotary_pos_sin,
127+ attention_bias=attention_bias,
128+ packed_seq_params=packed_seq_params,
129+ sequence_len_offset=sequence_len_offset,
130+ )
131+ 
132+ # For minicpm model
133+ if args.scale_depth is not None:
134+ attention_output, attention_bias = attention_output_with_bias
135+ attention_output = attention_output * (args.scale_depth / math.sqrt(args.num_layers))
136+ attention_output_with_bias = (attention_output, attention_bias)
137+ 
138+ if self.recompute_input_layernorm:
139+ # discard the output of the input layernorm and register the recompute
140+ # as a gradient hook of attention_output_with_bias[0]
141+ self.input_layernorm_checkpoint.discard_output_and_register_recompute(
142+ attention_output_with_bias[0]
143+ )
144+ 
145+ # inside the module provided in the `bias_dropout_add_spec` module?
146+ with self.bias_dropout_add_exec_handler():
147+ hidden_states = self.self_attn_bda(self.training, self.config.bias_dropout_fusion)(
148+ attention_output_with_bias, residual, self.hidden_dropout
149+ )
150+ 
151+ # Residual connection.
152+ residual = hidden_states
153+ 
154+ # Optional Layer norm after self-attention
155+ pre_cross_attn_layernorm_output = self.pre_cross_attn_layernorm(hidden_states)
156+ 
157+ # Cross attention.
158+ attention_output_with_bias = self.cross_attention(
159+ pre_cross_attn_layernorm_output,
160+ attention_mask=context_mask,
161+ key_value_states=context,
162+ inference_context=inference_context,
163+ )
164+ 
165+ if isinstance(attention_output_with_bias, dict) and "context" in attention_output_with_bias:
166+ context = attention_output_with_bias["context"]
167+ 
168+ # inside the module provided in the `bias_dropout_add_spec` module?
169+ with self.bias_dropout_add_exec_handler():
170+ hidden_states = self.cross_attn_bda(self.training, self.config.bias_dropout_fusion)(
J
Jjzh62292025年9月11日

该代码无调用,无引用,用途是什么?

likedislike
171+ attention_output_with_bias, residual, self.hidden_dropout
W
Wwx_4e191bb7af2025年9月12日

该代码无调用,无引用,用途是什么?

megatron原生逻辑

likedislike
172+ )
173+ 
174+ # Residual connection.
175+ residual = hidden_states
176+ 
177+ # Optional Layer norm post the cross-attention.
178+ if self.recompute_pre_mlp_layernorm:
179+ self.pre_mlp_norm_checkpoint = tensor_parallel.CheckpointWithoutOutput()
J
Jjzh62292025年9月11日

该代码与transformer_layer的forward重复度较高,重新编写的目的是什么?

likedislike
180+ pre_mlp_layernorm_output = self.pre_mlp_norm_checkpoint.checkpoint(
W
Wwx_4e191bb7af2025年9月12日

该代码与transformer_layer的forward重复度较高,重新编写的目的是什么?

适配minicpm模型scale_depth特性

likedislike
181+ self.pre_mlp_layernorm, hidden_states
182+ )
183+ else:
184+ pre_mlp_layernorm_output = self.pre_mlp_layernorm(hidden_states)
185+ 
186+ return pre_mlp_layernorm_output, residual, context
187+ 
61 def _forward_mlp(self, pre_mlp_layernorm_output, residual):188 def _forward_mlp(self, pre_mlp_layernorm_output, residual):
62 args = get_args()189 args = get_args()
63 # MLP.190 # MLP.